Top 367 Core Java Interview Questions for 2021


This article will guide you to prepare to face interview questions related to Core Java. It covers all the topics like Basics of Java, OOPs concepts, String handling, multithreading, Collections, etc.

1. What is Java?

Java is the simplest and the most commonly used programming language which is based on the object-oriented programming concept. It supports cross-platform, multithreading and is platform-independent, and robust. Sun Microsystems developed Java in the year 1995 and later acquired by Oracle Systems.

2. What are the features of the Java Programming language?

Java has the below features:

  • Simple: Java is easy to learn and does not require any complex programming concepts like pointers or multiple inheritance.
  • Platform-independent: Java is not dependent on any platform since the code we compile and execute is the same in any operating system. This means we can compile the code in one system and execute it in another.
  • Object-oriented: Java uses a collection of objects of a class to perform any operation and follows object-oriented methodology.
  • Secure: It is highly secure since it does not produce any security flaws like stack overflow, etc. This is because it does not use the concept of pointers.
  • Robust: Java is robust and reliable since it identifies errors at an early stage and avoids issues like garbage collection, memory allocation, exception handling, etc
  • Multithreaded: Supports multithreading concept which means we can execute 2 or programs simultaneously and thus utilizing CPU to the maximum.
  • High performance: Java uses a Just-in-time compiler and thereby providing high performance.
  • Distributed: Java supports distributed programming which means we can distribute java programs in more than 1 system which is connected through the internet. We can use features like EJB(Enterprise Java Bean) and RMI(Remote Method Invocation) in Java to support distributed features.
  • Dynamic: Java is more dynamic when we compare to other programming languages like C or C++. This is because it can carry a large amount of run time information which we can use to verify runtime object access.

3. What is the difference between C++ and Java?

Comparison MethodC++Java
Platform IndepenedenceIt is platform dependent. Should be compiled on every platformIt is platform independent. It can be compiled in one platform and executed in another
Compiler and InterpreterIt is a compiled languageIt is a compiled and interpreted language
PortabilityIt is not portableIt is portable since the bytecode output can be executed on any system
Memory managementMemory management is manualMemory management is system controlled
Multiple InheritanceSupports multiple inheritanceDoes not support multiple inheritance. But can be achieved through interface
OverloadingSupports operator overloadingDoes not support operator overloading
Virtual keywordIt uses virtual keyword to override functionIt does not use virtual keyword. By default all non-static methods are overridden or virtual
PointersUses the pointers conceptDoes not have pointers concept
Documentation commentsThere is no support for documentation commentsIt has built-in support for documentation comments(/** ... */
Thread supportC++ does not have in-built thread mechanism and uses third party librariesJava has in-built thread support using the class "Thread"
Call by value and Call by referenceSupports both Call by value and Call by ReferenceSupports only call by value
Structure and UnionSupports both structure and unionDoes not support Structures and union
Unsigned right shift >>> operatorDoes not support unsigned right shift operatorSupports unsigned right shift operator
Root hierarchyThere is no root hierarchyIt has a single root hierarchy which is java.lang.Object
Input mechanismUses Cin and Cout for I/O operationsUses System.in and System.out for I/O operations.
Goto statementSupports Goto statementDoes not support Goto statement
Data and functions scopeData and functions can reside outside the classData and functions should be present within the class
Object managementUses new and delete to manage objectsUses automatic garbage collection to manage objects
ApplicationsUsed for system programmingUsed for application programming like windows-based, web-based, enterprise and mobile applications.

4. What is the Java Virtual Machine(JVM)?

JVM or Java Virtual Machine is a virtual machine that executes the java program. It executes the bytecode generated by the compiler while compiling the program. JVM acts like a run-time engine that executes the program by calling the main method. The output which the JVM produces after executing the bytecode is the same in all operating system. This is why Java is platform-independent.

5. What do the terminologies JDK, and JRE mean?

JDK means Java Development Kit which contains many components like JRE, compilers, various tools like JavaDoc, JavaDebugger, libraries, etc. It is mandatory to install the JDK in our systems to compile and run any java programs.

JRE means Java Runtime Environment which is part of the JDK that is used to execute any java program. It also includes browser plugins, applets support, and JVM.

6. What are the different types of memory areas allocated by JVM?

JVM contains 5 different memory areas as given below:

  • Class(Method) area: It stores all the class related data like variables, methods, runtime constant pool.
  • Heap: It allocates memory for objects during runtime.
  • Stack: It stores the result of the method execution like returning the value or value used for dynamic linking. Stack also stores frames and every thread has a private JVM stack.
  • Program counter register: Contains the address of the JVM instructions of the method.
  • Native method stack: It contains all native methods that are used in the application.

7. What is a JIT compiler?

JIT stands for Just-in-time. It is a compiler that is part of the JRE. It compiles all the bytecode that has similar functionality together and thereby reduces the compilation time. Hence JIT compiler supports performance optimization.

8. What is a platform?

A platform is a combination of a hardware and software environment that helps in software execution. Java has its own environment named JRE(Java Runtime Environment)

9. What is the difference between a Java platform and other platforms?

  • Java is a software-based platform while others may be hardware-software or only hardware-based.
  • Java runs on top of other hardware platforms while others can run only on hardware-based components.
  • We can run Java code on any OS while other platforms do not have this capability.
  • Java has its own environment(JRE) and JVM while other platforms do not have this functionality.

10. What does ‘Write once and Run anywhere’ mean?

Java is a platform-independent programming language where we can write Java code and compile in one platform and execute it on another platform. We can execute this java program on any operating system since the output of the compilation which is the bytecode is not platform-specific.

11. What is a class loader?

Java classloader is part of the JRE(Java Runtime Environment) that loads the class files into the JVM(Java Virtual Machine) whenever it is required by the application. A single classloader does not load all the classes. Based on the type of the class, the corresponding class loader loads the class files whenever needed.

Below are the different types of Java classloaders:

  • Bootstrap class loader: This is the first classloader which loads all the files from the location rt.jar. It is also called the primordial class loader which is the parent of all other classloaders.
  • Extension class loader: This is the child class of the bootstrap class loader which loads the extensions of the core java classes from the Extensions directory jre/lib/ext.
  • System class loader: It is also called as the Application class loader that loads the application type classes or class files from the CLASSPATH variable. It is the subclass of the Extension class loader.

12. Can a java file name be saved as an empty .java file?

Yes, we can save a java file without a filename by using only .java. To compile, we use the command javac .java , and to execute, we use the command java classname.

13. Are delete, null, next, main, and exit keywords in Java?

Yes, delete, null, exit, next, main, and null are the keywords in Java programming language.

14. When we do not pass any values in the String array arguments of the main method, does the value hold empty or null?

The value will be empty but not null when we do not pass any values to the String array arguments in the main method.

public static void main(String[] args)

15. What happens when we write a static public void instead of public static void for the main method?

It compiles and runs successfully since the order does not matter and both are correct.

16. What is the default value of a local variable?

The local variables do not have any default value since they are visible only within the method where it is declared. We must initialize the local variable before we use it else it will throw a compilation error.

17. What are the different types of access specifiers in Java?

Java has 4 different types of  access specifiers:

  • public: It is visible to any class in any package. We can declare public access type for class, variable, or method.
  • protected: It is accessible within any class of the same package or within the subclass of the class where it is declared. To access outside, we can achieve through inheritance.
  • default: The scope is within the package and does not require any keyword to specify.
  • private: It can be accessed only within the same class.

Java Access Modifiers

You can refer Java access modifier tutorial for more details.

18. What is the use of static methods and variables?

When we declare a variable or a method using the static keyword, it becomes a static method or static variable. This means it belongs to a class and not the object. In other words, we do not need to create an object to access a static method or variable. It is shared among all objects within a class. For example, all students in a school use the same school name. Hence we can declare the school name as a static variable. You can refer to Java static keyword for more details on this topic.

19. What are the advantages of using packages in Java?

Using packages in Java provides the below advantages:

  • Avoids naming conflicts of classes. This means we can use the same class names in 2 different packages.
  • Provides reusability by accessing a class from 1 package in another.
  • Easy maintenance since the classes will be organized
  • Provides access protection for protected and default classes.
  • It helps in encapsulation or data hiding.

20. What is the output of the following Java program?

public class StringExample {

  public static void main(String[] args) {
    System.out.println(90 + 10 + "Java");
    System.out.println("Java" + 15 + 15);

  }

}
100Java
Java1515

In the first case, it first adds the 2 integers and then concatenates the output with the string value. Hence it results in “100Java”.

In the second case, it concatenates the string value with the integers instead of first adding the integers. Hence it results in “Java1515”. This is because since all operators are + it follows left to right precedence for concatenation.

21. What is the output of the below Java code?

public class StringExample {

  public static void main(String[] args) {
          System.out.println(10 * 10 + "Java");
    System.out.println("Java" + 10 * 10);
    
  }

}
100Java
Java100

In the first case, the output is “100Java” since the multiplication operator precedes the addition operator. Hence it first multiplies 10 and 10 and then concatenates the product with the string.

The same logic applies to the second case as well. Since the multiplication operator precedes the addition operator, it multiplies the 2 values and then concatenates with the string. Hence the result “Java 100”.

22. What is the output of the below Java code?

public class Sample {

  public static void main(String[] args) {
    for(int i=0;5;i++)
      System.out.println("Java");
  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  Type mismatch: cannot convert from int to boolean

  at Sample.main(Sample.java:4)

It throws a compilation error since the second argument in for loop needs to be a boolean condition. In the above code, it is an integer value instead of a boolean expression.

23. What is object-oriented programming?

Object-oriented programming uses objects that contain methods and variables. Every class contains objects that are instances of class using which we can access methods or data. It promotes reusability and improves the code readability and thereby results in faster product development. Java follows the object-oriented programming concept.

Below are the features of object-oriented programming:

  • Contains methods with data that we can use along with the object.
  • Supports encapsulation and abstraction functionality that hides data to the users.
  • Implements inheritance and polymorphism and hence increase the code reusability.

24. What is an object?

An object represents a real-life entity which is an instance of a class. It contains both data and methods(behaviors). Objects have mainly 2 characteristics of state and behaviors. The state is nothing but an identity of the object(data) and behavior describes the function(method) of the object. We can create an object in Java using the new keyword. An object is one of the important features of OOPs.

25. What is the difference between object-oriented programming and object-based programming language?

Object-oriented programmingObject-based programming
Uses all concepts of OOPs.Does not use few OOPs concepts like inheritance, polymorphism
It does not have built-in objectsIt has built-in objects like windows object in JavaScript
Eg: Java, C, C++, etcEg: JavaScript, VBScript, etc

26. What will be the initial value of an object reference which is defined as an instance variable?

All object references will have a null value by default in Java during initialization.

27. What is a constructor?

A constructor in Java is a special method that is executed during instance creation of a class. Whenever we create an object for the class, the java compiler calls the default constructor of that class implicitly. We can use the constructor to initialize arguments for the object which we use within the class. The constructor should have the same name as its class name.

28. What are the different types of constructors in Java?

There are 3 different types of constructors in Java:

  • Default constructor: When we do not create any constructor, the Java compiler internally creates a default constructor that has an empty body. This constructor will not be visible to us.
  • No argument constructor: This constructor does not have any arguments or parameters but can contain code within the constructor.
  • Parameterized constructor: It contains arguments or parameters that are used to initialize or assign values to variables.

29. What is the use of a default constructor?

The main purpose of a default constructor is to assign default values to objects. The Java compiler internally creates a default constructor if we do not create it. This code will not be visible to us. The default value for integer value is 0 and for String is null.

Constructor in Java

30. Does a constructor return any value?

The constructor implicitly returns the current class instance. But we cannot explicitly use a return type with a constructor.

31. Is constructor inherited?

The constructor does not support inheritance and cannot be inherited.

32. Can we create a final constructor?

No, we cannot create a constructor as a final.

33. Can we overload a constructor?

Yes, we can overload a constructor based on the number of arguments or type of parameters. Below is a simple example of constructor overloading. The first constructor does not have any arguments. The second has 2 arguments and the third has only 1 argument. Based on the parameter, it calls the corresponding constructor.

public class Employee {
  int empId;
  String empName;
  String empRole;
  
  public Employee() {
    this.empId = 100;
  }
  
  public Employee(int id, String name) {
    this.empId = id;
    this.empName = name;
  }
  
  public Employee(String designation) {
    this.empRole = designation;
  }
  
  public static void main(String[] args) {
    Employee e1 = new Employee();
    Employee e2 = new Employee(102,"Rakesh");
    Employee e3 = new Employee("Java Developer");
    Employee e4 = new Employee("Tester");
    System.out.println("Default value of Empid: " + e1.empId);
    System.out.println("Employee id: " + e2.empId + " " + "Employee Name:" + e2.empName);
    System.out.println("Employee Role: " + e3.empRole + " and " + e4.empRole);
    
  }
}
Default value of Empid: 100
Employee id: 102 Employee Name:Rakesh
Employee Role: Java Developer and Tester

34. What is a copy constructor in Java?

There is no copy constructor as such in Java but we can copy values of one object to another using the constructor which is similar to a copy constructor in C++. There are different ways to copy values:

  • By using constructor
  • Using the clone() method
  • Assigning values of one object to another.

Below is an example of copy constructor where we pass the object as parameter to a constructor and there by we can copy the values from one object to another.

public class Employee {
  int empId;
  String empName;
  public Employee(int id, String name) {
    this.empId = id;
    this.empName = name;
  }
  
   //Copy constructor
  public Employee(Employee emp) {
    empId = emp.empId;
    empName = emp.empName;
  }
  
  public void displayDetails() {
    System.out.println("Employee ID:" + empId);
    System.out.println("Employee Name:" + empName);
  }
  
  public static void main(String[] args) {
    Employee e1 = new Employee(102,"Dev");
    //Create a copy of another object
    Employee e2 = new Employee(e1);
    e1.displayDetails();
    e2.displayDetails();
  }
}
Employee ID:102
Employee Name:Dev
Employee ID:102
Employee Name:Dev

35. What are the differences between a constructor and a method?

Even though we call a constructor as a special method, there are several differences between a constructor and a method.

Java ConstructorJava Method
Initializes a state of objectDescribes the behavior of the object
Does not have return typeIt has return type
It is invoked implicitlyIt is invoked explicitly
Constructor name should be same as class nameMethod name can be anything irrespective of class name

36. What is the output of the following code?

public class Sample {
  
  Sample(int a) {
    System.out.println("Value of a: " + a);
  }
  
  Sample(float a) {
    System.out.println("Value of a: " + a);
  }

  public static void main(String[] args) {
    byte x = 5;
    Sample s = new Sample(5);

  }

}
Value of a: 5

In the above code, we have 2 constructors, one with argument type int and the other with a float data type. During object creation, we pass a byte value. In this case, it invokes the first constructor of integer type as the byte type gets promoted to an integer type.

37. What is the output of the following code?

class Result {
  int a;
  String s;
}
public class Demo {

  public static void main(String[] args) {
    Result r = new Result();
    System.out.println(r.a);
    System.out.println(r.s);

  }

}
0
null

We have 2 variables of data type integer and String. Since there is no constructor, the JVM internally calls the default constructor and initializes these variables with a default value which is 0 and null respectively.

38. What is the output of the below code?

class Result {
  int a;
  String s;
  
  Result(int a, String s) {
    this.a = a;
    this.s = s;
  }
}
public class Demo {

  public static void main(String[] args) {
    Result r = new Result();
    System.out.println(r.a);
    System.out.println(r.s);

  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The constructor Result() is undefined

  at Demo.main(Demo.java:13)

In this scenario, we get a compilation error. This is because when we define any constructor, the JVM does not internally call the default constructor. Hence if we define a constructor, we need to create the object using that constructor, else it will result in a compilation error.

39. What is a static variable?

When we declare a variable with a static keyword, we call it a static variable. These are also called class variables which means it is not specific to any object and does not require any object to access the static variables. It is mainly used to manage memory efficiently since it allocates memory only once(class area) for static variables which happen when the class loads. We can use a static variable when we want the same value to be shared among different objects or instances of a class. Eg: school name, college name, company name, etc

40. What is a static method?

When we declare a method using the static keyword, it becomes a static method. We can directly access the static methods and their variables without using the object. These methods belong to a class. We cannot call a non-static method or instance variable from a static method since it will throw a compilation error. Static methods can be used only to initialize static variables and not instance(object) variables.

41. What are the restrictions of using a static method?

  • We cannot access non-static members within a static method
  • Cannot call any non-static methods from a static method
  • Cannot use super keyword within a static method

42. Why do we declare the main method as static?

We declare the main method as static since it does not require any object and loads the methods during class loading. Also, the main method is the entry point for any execution in Java

43. Can we override static methods?

No, we cannot override static methods and it will result in compilation error.

44. What is a static block?

When a block contains the name as java keyword static, we call it a static block. We use static block when we want to initialize any static members while loading the class. It first executes this static block before it calls the main method.

public class StaticBlockExample {
  static int i;
  static {
    System.out.println("Inside the static block");
    i = 10;
  }
  public static void main(String[] args) {
    System.out.println("Inside the main method");
    System.out.println("Value of i: " + i);
  }
}
Inside the static block
Inside the main method
Value of i: 10

45. Is it possible to execute a java program without the main method?

We can execute a java program without the main method by using the static block. A static block is executed before the main method and when the class loads. But if we do not have a static block, then the compiler will look for the main() method and throws compilation error if not found.

Note: This is not possible for the Java 7 version.

46. What happens when we define the main method without a static keyword?

The java code compiles successfully but however, it will throw “NoSuchMethodError”.

47. What is the difference between static(class) method and instance method?

Static MethodInstance method
Method declaration contains the static keywordMethod declaration does not have static keyword
Does not require object to access static methodObject is required to access instance method
We cannot access non-static methods or variables within a static methodWe can access both static and non static members within an instance method
Static method belongs to the class. Hence it is also called as class methodInstance methods belong to object.

48. Can we create a static constructor?

We cannot make a constructor static since we need objects to invoke a constructor. Static does not require any objects hence it will throw compilation error as “Illegal access modifier”.

49. Can we make abstract methods as static?

No, we cannot make abstract methods as static because we cannot override static methods. We need to override abstract methods to provide its implementation or functionality in the class that extends the abstract class.

50. Can we declare static methods and static variables inside an abstract class?

We can declare static methods and static variables inside an abstract class because we do not need any object to access them. We can directly access them from the subclass using the abstract class name.

Pages: 1 2 3 4 5 6 7

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions