Core Java interview questions help you in preparing for java based interviews. Whether you are a fresher or highly experienced professional, core java plays a vital role in any Java/JEE interview.
Core Java is the favorite area in most of the interviews and plays a crucial role in deciding the outcome of your interview.
This post comes directly from my 14+ years of Java programming and lots of interviewing experience. Java 16 has been released recently and I have updated the post to include some of the questions from the latest releases.
I have already written a lot about java interview questions for specific topics such as String, Collections, and Multithreading.
Here I am providing some of the important core java interview questions with answers that you should know. You can bookmark this post to brush up on your knowledge before heading for an interview.
Java 14 was released on March 17, 2020. It is a Non-LTS version. Some of the developer specific Java 14 Features are:
Java 13 was launched on Sept 17, 2019. It is a Non-LTS version. Some of the developer specific Java 13 Features are:
Java 12 was launched on March 19, 2019. It is a Non-LTS version. Some of the Java 12 Features are:
Java 11 is the second LTS release after Java 8. They’ve changed the licensing and support model which means if you download the Java 11 Oracle JDK, it will be paid for commercial use. If you want to use a free version, you can download it from the OpenJDK website.
Some of the important features of Java 11 are:
java
command. The source file will be implicitly compiled and executed. It’s part of the JEP 330 feature implementation.For a complete overview, please read Java 11 Features.
Java 10 is the first every-six-months from Oracle corporation, so it’s not a major release like earlier versions. However, some of the important features of Java 10 are:
Java 10 is mostly a maintenance release, however I really liked the local variable type inference feature. For a detailed overview of Java 10, please go through Java 10 Features.
Java 9 was a major release and brought a lot of features. Some of the important features are:
You will find more details about them at Java 9 Features.
Java 8 has been released in March 2014, so it’s one of the hot topics in java interview questions. If you answer this question clearly, it will show that you like to keep yourself up-to-date with the latest technologies.
Java 8 has been one of the biggest releases after Java 5 annotations and generics. Some of the important features of Java 8 are:
I strongly recommend to go through above links to get proper understanding of each one of them, also read Java 8 Features.
Java is based on Object Oriented Programming Concepts, following are some of the OOPS concepts implemented in java programming.
Read more about them at OOPS Concepts in Java.
Platform independence means that you can run the same Java Program in any Operating System. For example, you can write java program in Windows and run it in Mac OS.
Java Virtual Machine (JVM) is the heart of java programming language. JVM is responsible for converting byte code into machine-readable code. JVM is not platform-independent, that’s why you have different JVM for different operating systems. We can customize JVM with Java Options, such as allocating minimum and maximum memory to JVM. It’s called virtual because it provides an interface that doesn’t depend on the underlying OS.
Java Development Kit (JDK) is for development purposes and JVM is a part of it to execute the java programs.
JDK provides all the tools, executables, and binaries required to compile, debug and execute a Java Program. The execution part is handled by JVM to provide machine independence.
Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t contain any development tools like java compiler, debugger, etc. If you want to execute any java program, you should have JRE installed.
java.lang.Object
is the root class for all the java classes and we don’t need to extend it.
Java doesn’t support multiple inheritance in classes because of “Diamond Problem”. To know more about diamond problem with example, read Multiple Inheritance in Java.
However multiple inheritances are supported in interfaces. An interface can extend multiple interfaces because they just declare the methods and implementation will be present in the implementing class. So there is no issue of the diamond problem with interfaces.
Java is not said to be pure object-oriented because it supports primitive types such as int, byte, short, long, etc. I believe it brings simplicity to the language while writing our code. Java could have wrapper objects for the primitive types but just for the representation, they would not have provided any benefit.
As we know, for all the primitive types we have wrapper classes such as Integer, Long etc that provides some additional methods.
PATH is an environment variable used by the operating system to locate the executables. That’s why when we install Java or want any executable to be found by OS, we need to add the directory location in the PATH variable. If you work on Windows OS, read this post to learn how to set up PATH variable on Windows.
Classpath is specific to Java and used by java executables to locate class files. We can provide the classpath location while running the java application and it can be a directory, ZIP files, JAR files, etc.
The main() method is the entry point of any standalone java application. The syntax of the main method is public static void main(String args[])
.
Java’s main method is public and static so that Java runtime can access it without initializing the class. The input parameter is an array of String through which we can pass runtime arguments to the java program. Check this post to learn how to compile and run a java program.
When we have more than one method with the same name in a single class but the arguments are different, then it is called method overloading.
The overriding concept comes into the picture with inheritance when we have two methods with the same signature, one in the parent class and another in the child class. We can use @Override annotation in the child class overridden method to make sure if the parent class method is changed, so is the child class.
Yes, we can have multiple methods with the name “main” in a single class. However, if we run the class, the java runtime environment will look for the main method with syntax as public static void main(String args[])
.
We can’t have more than one public class in a single java source file. A single source file can have multiple classes that are not public.
Java package is the mechanism to organize the java classes by grouping them. The grouping logic can be based on functionality or modules based. A java class fully classified name contains package and class name. For example, java.lang.Object
is the fully classified name of Object
class that is part of java.lang
package.
The java.lang
package is imported by default and we don’t need to import any class from this package explicitly.
Java provides access control through public, private and protected access modifier keywords. When none of these are used, it’s called default access modifier.
A java class can only have public or default access modifier. Read Java Access Modifiers to learn more about these in detail.
The final keyword is used with Class to make sure no other class can extend it. For example, the String class is final and we can’t extend it.
We can use the final keyword with methods to make sure child classes can’t override it.
Java’s final keyword can be used with variables to make sure that it can be assigned only once. However the state of the variable can be changed, for example, we can assign a final variable to an object only once but the object variables can change later on.
Java interface variables are by default final and static.
The static keyword can be used with class-level variables to make it global i.e all the objects will share the same variable.
We can use static keyword with methods also. A static method can access only static variables of class and invoke only static methods of the class.
Read more in detail at java static keyword.
The finally block is used with try-catch to put the code that you want to get executed always, even if an exception is thrown by the try-catch block. finally block is mostly used to release resources created in the try block.
The finalize() is a special method in Object class that we can override in our classes. This method gets called by the garbage collector when the object is getting garbage collected. This method is usually overridden to release system resources when the object is garbage collected.
We can’t declare a top-level class as static however an inner class can be declared as static. If the inner class is declared as static, it’s called a static nested class.
The static nested class is the same as any other top-level class and is nested for only packaging convenience.
Read more about inner classes at java inner class.
If we have to use any static variable or method from other class, usually we import the class and then use the method/variable with class name.
import java.lang.Math;
//inside class
double test = Math.PI * 5;
We can do the same thing by importing the static method or variable only and then use it in the class as if it belongs to it.
import static java.lang.Math.PI;
//no need to refer class now
double test = PI * 5;
Use of static import can cause confusion, so it’s better to avoid it. Overuse of static import can make your program unreadable and unmaintainable.
One of the Java 7 features is the try-with-resources statement for automatic resource management. Before Java 7, there was no auto resource management and we should explicitly close the resource. Usually, it was done in the finally
block of a try-catch statement. This approach used to cause memory leaks when we forgot to close the resource.
From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon as try-catch block gets finished. Read more at Java Automatic Resource Management.
Java 7 one of the improvement was a multi-catch block where we can catch multiple exceptions in a single catch block. This makes our code shorter and cleaner when every catch block has a similar code.
If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, the exception parameter (ex) is final, so you can’t change it.
Read more at Java multi catch block.
Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. It is used to initialize static variables of the class. Mostly it’s used to create static resources when class is loaded.
Interfaces are core concepts of java programming language and used a lot not only in JDK but also java design patterns, most of the frameworks and tools. Interfaces provide a way to achieve abstraction in java and used to define the contract for the subclasses to implement.
Interfaces are good for starting point to define Type and create top level hierarchy in our code. Since a java class can implements multiple interfaces, it’s better to use interfaces as super class in most of the cases. Read more at java interface.
Abstract classes are used in java to create a class with some default method implementation for subclasses. An abstract class can have an abstract method without the body and it can have methods with implementation also.
The abstract keyword is used to create a abstract class. Abstract classes can’t be instantiated and mostly used to provide base for sub-classes to extend and implement the abstract methods and override or use the implemented methods in abstract class. Read important points about abstract classes at java abstract class.
Some more differences in detail are at Difference between Abstract Class and Interface.
Interfaces don’t implement another interface, they extend it. Since interfaces can’t have method implementations, there is no issue of diamond problem. That’s why we have multiple inheritances in interfaces i.e an interface can extend multiple interfaces.
From Java 8 onwards, interfaces can have default method implementations. So to handle diamond problem when a common default method is present in multiple interfaces, it’s mandatory to provide implementation of the method in the class implementing them. For more details with examples, read Java 8 interface changes.
A marker interface is an empty interface without any method but used to force some functionality in implementing classes by Java. Some of the well known marker interfaces are Serializable and Cloneable.
Java wrapper classes are the Object representation of eight primitive types in java. All the wrapper classes in java are immutable and final. Java 5 autoboxing and unboxing allows easy conversion between primitive types and their corresponding wrapper classes.
Read more at Wrapper classes in Java.
Enum was introduced in Java 1.5 as a new type whose fields consist of a fixed set of constants. For example, in Java, we can create Direction as an enum with fixed fields as EAST, WEST, NORTH, SOUTH.
enum is the keyword to create an enum type and similar to the class. Enum constants are implicitly static and final. Read more in detail at java enum.
Java Annotations provide information about the code and they have no direct effect on the code they annotate. Annotations are introduced in Java 5. Annotation is metadata about the program embedded in the program itself. It can be parsed by the annotation parsing tool or the compiler. We can also specify annotation availability to either compile-time only or till runtime. Java Built-in annotations are @Override, @Deprecated and @SuppressWarnings. Read more at java annotations.
Java Reflection API provides the ability to inspect and modify the runtime behavior of java application. We can inspect a java class, interface, enum and get their methods and field details. Reflection API is an advanced topic and we should avoid it in normal programming. Reflection API usage can break the design pattern such as Singleton pattern by invoking the private constructor i.e violating the rules of access modifiers.
Even though we don’t use Reflection API in normal programming, it’s very important to have. We can’t have any frameworks such as Spring, Hibernate or servers such as Tomcat, JBoss without Reflection API. They invoke the appropriate methods and instantiate classes through reflection API and use it a lot for other processing.
Read Java Reflection Tutorial to get in-depth knowledge of reflection api.
Composition is the design technique to implement has-a relationship in classes. We can use Object composition for code reuse.
Java composition is achieved by using instance variables that refer to other objects. The benefit of using composition is that we can control the visibility of other objects to client classes and reuse only what we need. Read more with example at Java Composition example.
One of the best practices of Java programming is to “favor composition over inheritance”. Some of the possible reasons are:
You can read more about above benefits of composition over inheritance at java composition vs inheritance.
We need to implement Comparable interface to support sorting of custom objects in a collection. The Comparable interface has compareTo(T obj) method which is used by sorting methods and by providing this method implementation, we can provide default way to sort custom objects collection.
However, if you want to sort based on different criteria, such as sorting an Employees collection based on salary or age, then we can create Comparator instances and pass it as sorting methodology. For more details read Java Comparable and Comparator.
We can define a class inside a class and they are called nested classes. Any non-static nested class is known as an inner class. Inner classes are associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with the instance, we can’t have any static variables in them.
We can have local inner class or anonymous inner class inside a class. For more details read java inner class.
A local inner class without a name is known as an anonymous inner class. An anonymous class is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface.
Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class. Anonymous inner classes are accessible only at the point where it is defined.
Java Classloader is the program that loads byte code program into memory when we want to access any class. We can create our own classloader by extending ClassLoader class and overriding loadClass(String name) method. Learn more at java classloader.
There are three types of built-in Class Loaders in Java.
Java ternary operator is the only conditional operator that takes three operands. It’s a one liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators. An example can be found at java ternary operator.
The super keyword can be used to access the superclass method when you have overridden the method in the child class.
We can use the super keyword to invoke superclass constructors in child class constructor but in this case, it should be the first statement in the constructor method.
package com.journaldev.access;
public class SuperClass {
public SuperClass(){
}
public SuperClass(int i){}
public void test(){
System.out.println("super class test method");
}
}
Use of super keyword can be seen in below child class implementation.
package com.journaldev.access;
public class ChildClass extends SuperClass {
public ChildClass(String str){
//access super class constructor with super keyword
super();
//access child class method
test();
//use super to access super class method
super.test();
}
@Override
public void test(){
System.out.println("child class test method");
}
}
We can use break statement to terminate for, while, or do-while loop. We can use a break statement in the switch statement to exit the switch case. You can see the example of break statement at java break. We can use a break with the label to terminate the nested loops.
The continue statement skips the current iteration of a for, while, or do-while loop. We can use the continue statement with the label to skip the current iteration of the outermost loop.
this keyword provides the reference to the current object and it’s mostly used to make sure that object variables are used, not the local variables having the same name.
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
We can also use this keyword to invoke other constructors from a constructor.
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
No argument constructor of a class is known as default constructor. When we don’t define any constructor for the class, java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then compiler won’t create default constructor for us.
Yes, we can have try-finally statement and hence avoiding catch block.
Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, the process of deallocating memory is handled automatically by the garbage collector.
We can run the garbage collector with code Runtime.getRuntime().gc()
or use utility method System.gc()
. For a detailed analysis of Heap Memory and Garbage Collection, please read Java Garbage Collection.
We can convert a Java object to a Stream that is called Serialization. Once an object is converted to Stream, it can be saved to file or send over the network or used in socket connections.
The object should implement a Serializable interface and we can use java.io.ObjectOutputStream to write objects to file or to any OutputStream object. Read more at Java Serialization.
The process of converting stream data created through serialization to Object is called deserialization. Read more at Java Deserialization.
We can run a jar file using java command but it requires Main-Class entry in jar manifest file. Main-Class is the entry point of the jar and used by java command to execute the class. Learn more at java jar file.
Java System Class is one of the core classes. One of the easiest ways to log information for debugging is System.out.print() method.
System class is final so that we can’t subclass and override its behavior through inheritance. System class doesn’t provide any public constructors, so we can’t instantiate this class and that’s why all of its methods are static.
Some of the utility methods of System class are for array copy, get the current time, reading environment variables. Read more at Java System Class.
We can use the instanceof keyword to check if an object belongs to a class or not. We should avoid it’s usage as much as possible. Sample usage is:
public static void main(String args[]){
Object str = new String("abc");
if(str instanceof String){
System.out.println("String value:"+str);
}
if(str instanceof Integer){
System.out.println("Integer value:"+str);
}
}
Since str is of type String at runtime, first if statement evaluates to the true and second one as false.
One of the Java 7 feature was improvement of switch case of allow Strings. So if you are using Java 7 or higher version, you can use String in switch-case statements. Read more at Java switch-case String example.
This is a very confusing question, we know that object variables contain the reference to the Objects in heap space. When we invoke any method, a copy of these variables is passed and gets stored in the stack memory of the method. We can test any language whether it’s pass by reference or pass by value through a simple generic swap method, to learn more read Java is Pass by Value and Not Pass by Reference.
Major difference between Heap and Stack memory are as follows:
For a detailed explanation with a sample program, read Java Heap vs Stack Memory.
The task of java compiler is to convert java program into bytecode, we have javac
executable for that. So it must be stored in JDK, we don’t need it in JRE and JVM is just the specs.
Context: static method in class
package com.journaldev.util;
public class Test {
public static String toString(){
System.out.println("Test toString called");
return "";
}
public static void main(String args[]){
System.out.println(toString());
}
}
Answer: The code won’t compile because we can’t have an Object class method with the static keyword. Note that the Object class has toString() method. You will get a compile-time error as “This static method cannot hide the instance method from Object”. The reason is that the static method belongs to the class and since every class base is an Object, we can’t have the same method in the instance as well as in class. You won’t get this error if you change the method name from toString() to something else that is not present in the superclass Object
.
Context: static method invocation
package com.journaldev.util;
public class Test {
public static String foo(){
System.out.println("Test foo called");
return "";
}
public static void main(String args[]){
Test obj = null;
System.out.println(obj.foo());
}
}
Answer: Well this is a strange situation. We all have seen NullPointerException
when we invoke a method on the object that is NULL. But here this program will work and prints “Test foo called”.
The reason for this is the java compiler code optimization. When the java code is compiled to produced byte code, it figures out that foo() is a static method and should be called using class. So it changes the method call obj.foo()
to Test.foo()
and hence no NullPointerException
.
I must admit that it’s a very tricky question and if you are interviewing someone, this will blow his mind off. 🙂
That’s all for core java interview questions and answers. I will keep on adding more questions to the list, if you think I missed any important one, please let me know through comments.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
good article it helps to Come up with the différents version of java
- wade
Thank you so much for your articles, You’re the best
- Azin
Thanks Pankaj. 10 years of experience . preparing for an interview now. Your articles helped a lot to brush up the things in a easy and memorable way. really a fan of journalDev.
- Nisha
Which of the following statements are correct: "Annotations are introduced in Java 5. " https://www.journaldev.com/2366/core-java-interview-questions-and-answers#annotations-java “Java 1.5 introduced annotations and now it’s heavily used in Java EE frameworks like Hibernate, Jersey, and Spring.” journaldev.com/721/java-annotations
- Royal Summers
public class Test { public static String toString1(){ System.out.println(“Test toString called”); return “”; } public static void main(String args[]){ System.out.println(toString1()); } } toString() is an in build function.
- Dev
Great Article. Very well defined answers Really Appreciated
- Shubham Chaudhary
The answer to Question 17 seems incorrect. The evidence for this should be evident when you look at question 23. Great list BTW.
- Peter Xenos
The best book when it comes to most commonly interview asked questions is “TOP 30 Java Interview Coding Tasks” by Matthew Urban, deeply-explained, most commonly used data structures, algorithms, text manipulation methods, recursion, matrices, and other top topics to discuss during the job interview. I bought mine on Amazon: https://www.amazon.com/TOP-Java-Interview-Coding-Tasks-ebook/dp/B07F8CKS2S. really recommend
- Voctor
Hi, thanks for the article and the interview materials. You can also find the very common interview questions in Matthew Urban’s book “TOP 30 Java Interview Coding Tasks”. Really useful when I was preparing for my meeting. Thanks again. https://www.amazon.com/dp/B07F8CKS2S/?tag=myga0ba-20
- Edd
I am so greatfull that you have shared all questions and answers. It helped me a lot. Thank u so much Sir.
- Mayur0707