Top 100 Java Interview Questions and Answers for Freshers in 2020

Sep 11, 2020

Basic Java Interview Questions and Answers for Beginners

1.Why is Java Platform Independent?

At the time of compilation, the java compiler converts the source code into a JVM interpretable set of intermediate form, which is termed as byte code. This is unlike the compiled code generated by other compilers and is non-executable. The java virtual machine interpreter processes the non-executable code and executes it on any specific machine. Hence the platform dependency is removed.

2.What is Method overloading? Why is it used in Java?

Method overriding is a process in which methods inherited by child classes from parent classes are modified as per requirement by the child class. It’s helpful in hierarchical system design where objects share common properties.

Example: Animal class has properties like fur colour, sound. Now dog and cat class inherit these properties and assign values specific to them to the properties.

class Animal { 
    void sound(){ 
 class Cat extends Animal{ 
     void sound(){ 

class Dog extends Animal{ 
    void sound(){ 

public class OverRide{ 
    public static void main(String args[]){ 
        Cat c=new Cat(); 

        Dog d=new Dog(); 

3. What is Method overloading? Why is it used in Java?

If multiple functions in a class have the same name but different function definitions it is called method overloading.
It is used to make a java function serve multiple purposes making the code cleaner and API less complex.

println() prints any data type passed to it as a string. 

public class Add_Overload { 
    void add(int x, int y){ 
    void add(double x, double y){ 
    void add(double x, int y){ 
    public static void main(String args[]){ 
        Add_Overload a= new Add_Overload(); 


4.Why is Java Robust?

Java is termed as robust because of the following features:
– Lack of pointers: Java does not have pointers which make it secure
– Garbage Collection: Java automatically clears out unused objects from memory which are unused
– Java has strong memory management.
– Java supports dynamic linking.

5.Why is Java Secure?

Java does not allow pointers. Pointers give access to actual locations of variables in a system. Also, java programs are bytecode executables that can run only in a JVM. Hence java programs do not have access to the host systems on which they are executing, making it more secure. Java has its own memory management system, which adds to the security feature as well.

6. What is the difference between JDK, JRE, and JVM?

JDK is a software environment used for the development of Java programs. It’s a collection of libraries that can be used to develop various applications. JRE (Java Runtime Environment) is a software environment that allows Java programs to run. All java applications run inside the JRE. JVM (java virtual machine) is an environment that is responsible for the conversion of java programs into bytecode executables. JDK and JRE are platform-dependent whereas JVM is platform-independent.

7.What is a singleton class in Java? What’s the benefit of making a class singleton?

A singleton class is a class in Java that can at most have one instance of it in an application. If new instances are created for the same class they point to the first instance created and thus have the same values for all attributes and properties.
Singleton classes are created to create global points of access to objects. Singleton classes find their primary usages in caching, logging, device drivers which are all entities for universal access.

8.What are the features of Java?

Java is a pure Object Oriented Programming Language with the following features:
– High Performance
– Platform Independent
– Robust
– Multi-threaded
– Simple
– Secure

9.Does Java Support Pointers?

Pointers are not supported in java to make it more secure.

10.Why are Static variables used in Java?

Static methods and variables are used in java to maintain a single copy of the entity across all objects. When a variable is declared as static it is shared by all instances of the class. Changes made by an instance to the variable reflect across all instances.

public class static_variable {

    static int a;
    static int b;
    int calc_b(){
        return b;
void print_val(){
public static void main(String args[]){
    static_variable v=new static_variable();
    static_variable v1=new static_variable();

11. What are static methods, static variables, and static blocks?

Static methods are methods that can be called directly inside a class without the use of an object.
Static variables are variables that are shared between all instances of a class.
Static blocks are code blocks that are loaded as the class is loaded in memory.

12. What’s the use of static methods?

Static methods are used when there is no requirement of instantiating a class. If a method is not going to change or overridden then it can be made static.

13. What’s the use of static variables?

Static variables are used for maintaining a common state of certain data which is modifiable and accessible by all instances of a class.

14. What are the interfaces?

An interface is a collection of constants, static methods, abstract methods, and default methods. Methods in an interface do not have a body.

15.How is Abstraction achieved in Java?

Abstraction is achieved in Java by the use of abstract class and abstract methods.

16.Why are strings immutable in Java?

Strings in java are frequently used for hashmap keys. Now if someone changes the value of the string it will cause severe discrepancies. Hence strings are made immutable.

17. What are wrapper classes in Java?

Wrapper classes are a functionality supported by java to accept primitive data types as inputs and then later convert those into string objects so that they can be compared to other objects.

18. Can interfaces in Java be inherited?

Yes, interfaces can be inherited in java. Hybrid inheritance and hierarchical inheritance are supported by java through inheritable interfaces.

19. Are static methods allowed in a Java interface?

Yes, static methods are allowed in java interfaces. They are treated as default methods so they need not be implemented.

20. How is garbage collection done in Java?

Java has an automatic built-in garbage collection mechanism in place. Apart from the built-in mechanism, manual initiation of garbage collection can also be done by using the gc() of system class.

21. Can there be two main methods in a class?

Yes, there can be two main methods. This also means that the main method is overloaded. But at the time of execution, JVM only calls the original main method and not the overloaded main method.

22. Can private variables be inherited?

Private variables have a class-specific scope of availability. They can only be accessed by the methods of the class in which they are present. Hence when the class is inherited, private variables are not inherited by the subclass.

23. Can the size of an array be increased after declaration?

The size of a java array cannot be increased after declaration. This is a limitation of Java arrays.

24. What is the size of the below array in memory?
int a[]=new int[10];

Each int block takes a size of 4 bytes and there are 10 such blocks in the array. Hence, the size the array takes in memory is 40 bytes.

25. How many data types does java support?

Java supports 8 primitive data types, namely byte, short, int, long, float, double, char, boolean.

26. How to find out the ASCII value of a character in java?

int c=char(‘A’) would give the ASCII value of A in java.

27. How to get a string as user input from the console?

We have to instantiate an input reader class first. There are quite a few options available, some of which are BufferedReader, InputStreamReader Scanner.
Then the relative functionality of the class can be used. One of the most prevalently used is nextLine() of Scanner class.

28. How to check the size of strings?

The size of strings in java can be checked by using the length() function.

29. How can we sort a list of elements in Java?

The built-in sorting utility sort() can be used to sort the elements. We can also write our custom functions but it’s advisable to use the built-in function as its highly optimized.

30. If we sort a list of strings how would be the strings arranged? The strings would be arranged alphabetically in ascending order.

31. The difference between throw and throws in Java?

Throw is used to actually throw an instance of java.lang.Throwable class, which means you can throw both Error and Exception using throw keyword e.g.

throw new IllegalArgumentException("size must be multiple of 2") 

On the other hand, throws is used as part of method declaration and signals which kind of exceptions are thrown by this method so that its caller can handle them. It’s mandatory to declare any unhandled checked exception in throws clause in Java. Like the previous question, this is another frequently asked Java interview question from errors and exception topic but too easy to answer.

32. Can we make an array volatile in Java?

Yes, you can make an array volatile in Java but only the reference which is pointing to an array, not the whole array. What I mean, if one thread changes the reference variable to points to another array, that will provide a volatile guarantee, but if multiple threads are changing individual array elements they won’t be having happens before guarantee provided by the volatile modifier.

33. Can I store a double value in a long variable without casting?

No, you cannot store a double value into a long variable without casting because the range of double is more than long and we need to type cast. It’s not difficult to answer this question but many developer get it wrong due to confusion on which one is bigger between double and long in Java.

34. Which one will take more memory, an int or Integer?

An Integer object will take more memory as Integer is an object and it stores metadata overhead about the object but int is a primitive type, so it takes less space.

35. The difference between nested static class and top-level class?

A public top-level class must have the same name as the name of the source file, there is no such requirement for a nested static class. A nested class is always inside a top-level class and you need to use the name of the top-level class to refer nested static class e.g. HashMap.Entry is a nested static class, where HashMap is a top-level class and Entry is nested, static class.

36. What is the use of the final keyword?

The final keyword is used to declare the final state of an entity in java. The value of the entity cannot be modified at a later stage in the application. The entity can be a variable, class, object, etc.
It is used to prevent unnecessary modifications in a java application.

37. What’s the difference between deep copy and shallow copy?

Shallow copy in java copies all values and attributes of an object to another object and both objects reference the same memory locations.

Deep copy is the creation of an object with the same values and attributes of the object being copied but both objects reference different memory locations.

38. What’s the use of default constructor?

The default constructor is a constructor that gets called as soon as the object of a class is declared. The default constructor is un-parametrized. The generic use of default constructors is in the initialization of class variables.

class ABC{ 
    int i,j; 

Here ABC() is a default constructor.

39. What is object cloning?

Object cloning is the process of creating an exact copy of an object of a class. The state of the newly created object is the same as the object used for cloning.
The clone() method is used to clone objects. The cloning done using the clone method is an example of a deep copy.

40. Why are static blocks used?

They serve the primary function of initializing the static variables. If multiple static blocks are there they are executed in the sequence in which they are written in a top-down manner.

41. What is the use of this keyword in java?

This keyword is used to reference an entity using the current object in java. It’s a multi-purpose keyword which serves various functionalities

42. What’s the difference between String and String Builder class in java?

Strings are immutable while string Builder class is mutable. The string builder class is also synchronized.

43. How to calculate the size of an object?

The size of an object can be calculated by summing the size of the variables of the class the object is instantiated from.
If a class has an integer, a double variable defined in it then the size of the object of the class is size(int)+size(double).
If there is an array, then the size of the object would be the length of array*size of data type of array.

44. What’s the difference between == and .equals()?

“==” is an operator, whereas .equals() is a function.
“==” checks if the references share the same location, whereas .equals() checks if both object values are the same on evaluation.

Java Interview Questions for Experienced Professionals

1. Can static methods reference non-static variables?

Yes, static methods can reference non-static variables. It can be done by creating an object of the class the variable belongs to.

2. How do static blocks get executed if there are multiple static blocks?

Multiple static blocks are executed in the sequence in which they are written in a top-down manner. The top block gets executed first, then the subsequent blocks are executed.

3. Can we override static methods?

Static methods cannot be overridden because they are not dispatched to the object instance at run time. In their case, the compiler decides which method gets called.

4. Which class do all classes inherit from in java?

All classes in java inherit from the Object class which is the superclass of all classes.

5. What is classloader?

ClassLoader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

  • Bootstrap ClassLoader: This is the first classloader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, package classes, java.util package classes, package classes, java.sql package classes, etc.
  • Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
  • System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using “-cp” or “-classpath” switch. It is thus also known as Application classloader.

6. The difference between Serializable and Externalizable in Java?

Serializable interface is used to make Java classes serializable so that they can be transferred over a network or their state can be saved on disk, but it leverages default serialization built-in JVM, which is expensive, fragile and not secure. Externalizable allows you to fully control the Serialization process, specify a custom binary format and add more security measure.

7. Can we use String in the switch case?

We can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch. See the detailed answer for more explanation and discussion.

8. What are object serialization and deserialization?

The use of to convert an object into a sequence of bytes is known as object serialization. Deserialization is the process of recovering back the state of the object from the byte stream.

9. The difference between checked and unchecked exception in Java?

A checked exception is checked by the compiler at compile time. It’s mandatory for a method to either handle the checked exception or declare them in their throws clause. These are the ones which are a subclass of Exception but doesn’t descend from RuntimeException. The unchecked exception is the descendant of RuntimeException and not checked by the compiler at compile time. This question is now becoming less popular and you would only find this with interviews with small companies, both investment banks and startups are moved on from this question.

10. Is ++ operator is thread-safe in Java?

No, it’s not a thread-safe operator because it involves multiple instructions like reading a value, incriminating it and storing it back into memory which can be overlapped between multiple threads.

11. Which class contains the clone method? Cloneable or Object?

java.lang.Cloneable is a marker interface and doesn’t contain any method clone method is defined in the object class. It is also knowing that clone() is a native method means it’s implemented in C or C++ or any other native language.

Java Coding Interview Questions

1. Explain the exception handling mechanism of Java?

Exception class inherits from the Throwable class in java. Java has a try-catch mechanism for handling exceptions without them being generated as errors.

public class Exception_Handling { 
    String gender; 
    Exception_Handling(String s){ 
     void Check_Gender(String s) throws GenderException{ 
        if (gender!="Male" || gender!="Female") 
            throw new GenderException("Gender Invalid"); 
        System.out.println("Gender valid"); 
    public static void main(String args[]){ 
        Exception_Handling n=new Exception_Handling("None"); 
        }catch (Exception e){ 
            System.out.println("Exception : "+e); 
class GenderException extends Exception{ 
    GenderException(String s){ 

2. When do we use the Array list?

Whenever there is a need for random access of elements in java we use ArrayList. Get and set methods provide really fast access to the elements using the array list.

3. What is the use of generics in Java?

Generics allow classes and interfaces to be a type for the definition of new classes in java which enables stronger type checking. It also nullifies the probability of type mismatch of data while insertion.

4. What is an iterator?

An iterator is a collection framework functionality which enables sequential access of elements. The access can be done in one direction only. Java supports two types of iterators:
1. Enumeration Iterator
2. List Iterator

5. What is a hashmap?

Hashmap is a collection framework functionality which is used for storing data into key-value pairs. To access data we need the key. A hashmap uses linked lists internally for supporting the storage functionality.

6. What is a stack?

A stack is a data structure that supports LAST IN FIRST OUT methodology. The element pushed last is at the top of the stack. A stack supports the following functionality:

  • Push-operation to push an element into the stack
  • Pop-operation to push an element out of the stack
  • Peek-An option to check the top element

7. What is a treemap?

Treemap is a navigable map interpretation in java which is built around the concepts of red and black trees. The keys of a treemap are sorted in ascending order by their keys.

8. What is a vector?

A vector is an ArrayList like data structure in java whose size increases as per the demands. Moreover, it also supports some legacy functions not supported by collections.
You should also know that a vector is more suitable to work with threads, unlike collection objects.

9. What is the difference between ArrayList and vector?

An ArrayList is not suitable for working in a thread based environment. A vector is built for thread-based executions. ArrayList does not support legacy functions whereas a vector has support for legacy functions.

10. Write a program to calculate the factorial of a number in java.

import java.util.Scanner; 

public class star { 
     public static void main(String[] args) { 
         Scanner sc=new Scanner(; 
         int fact=1; 
         int n=sc.nextInt(); 

         for (int i=1;i<=n;i++) 




11. Write a program to check if a number is prime.

import java.util.Scanner; 
public class star { 
     public static void main(String[] args) { 
         Scanner sc=new Scanner(; 
         int n=sc.nextInt(); 
         int count=0; 
         for (int i=1;i<=n;i++) 
             if (n%i==0) 
         if (count==2) 
         System.out.println("Not Prime"); 

12. Write a program to convert decimal numbers to binary.

import java.util.Scanner; 

class star 
public static void main(String arg[])    
    Scanner sc=new Scanner(; 
    System.out.println("Enter a decimal number"); 
    int n=sc.nextInt(); 
    int  bin[]=new int[100]; 
    int i = 0; 
    while(n > 0) 
    bin[i++] = n%2; 
       n = n/2; 
   System.out.print("Binary number is : "); 
    for(int j = i-1;j >= 0;j--) 

13. Write a program to convert decimal numbers to octal.

import java.util.Scanner; 
class star 
  public static void main(String args[]) 
    Scanner sc = new Scanner( ); 
    System.out.print("Enter a decimal number : "); 
    int num =sc.nextInt(); 
    String octal = Integer.toOctalString(num); 
    System.out.println("Decimal to octal: " + octal); 

14. Which utility function can be used to extract characters at a specific location in a string?

The charAt() utility function can be used to achieve the above-written functionality.

15. How to get the length of a string in java?

Length of string in java can be found using the .length() utility.

58. Which of the following syntax for defining an array is correct?
– Int []=new int[];
– int a[]=new int[];
– int a[] =new int [32];

int a[]=new int[32] is the correct method.

16. What will this return 3*0.1 == 0.3? true or false?

This is one of the really tricky questions and can be answered only if your concepts are very clear. The short answer is false because some floating-point numbers can not be represented exactly.

17. Write a program to do bubble sort on an array in java.

import java.util.Scanner; 
class star 
  public static void main(String args[]) 
    int arr[] =new int [10]; 
    Scanner sc = new Scanner( ); 
    System.out.println("Enter size of array"); 
    int n=sc.nextInt(); 
    System.out.print("Enter an arry : "); 
    for (int i=0;i<n;i++) 
    for (int i=0;i<n;i++) 
        for (int j=0;j<n-i-1;j++) 
            if (arr[j]>arr[j+1]) 
                int t=arr[j]; 
 for (int i=0;i<n;i++) 

18. Write a program to generate the following output in java?

public class star { 
     public static void main(String[] args) { 
         int i; 
         int count=1; 
        for (i=1;i<=5;i++){ 
            for (int j=1;j<=i;j++) 
            System.out.println(" "); 



19. Write a program to generate the following output.

public class star { 
     public static void main(String[] args) { 
         int i; 
         int count=1; 
        for (i=5;i>=1;i--){ 
            for (int j=1;j<=i;j++) 
            System.out.println(" "); 



20. Write a program in java to remove all vowels from a string.

import java.util.Scanner; 

public class star { 
     public static void main(String[] args) { 
         Scanner sc=new Scanner(; 
         String n=sc.nextLine(); 
         String n1=n.replaceAll("[AEIOUaeiou]", ""); 


21. Write a program in java to check for palindromes.

String str, rev = ""; 
      Scanner sc = new Scanner(; 

      System.out.println("Enter a string:"); 
      str = sc.nextLine(); 

      int length = str.length(); 

      for ( int i = length - 1; i >= 0; i-- ) 
         rev = rev + str.charAt(i); 

      if (str.equals(rev)) 
         System.out.println(str+" is a palindrome"); 
         System.out.println(str+" is not a palindrome"); 

22. What is the underlying mechanism in java’s built-in sort?

Java’s built-in sort function utilizes the two pivot quicksort mechanism. Quicksort works best in most real-life scenarios and has no extra space requirements.

23. Which utility function is used to check the presence of elements in an ArrayList?

hasNext() is used for the presence of the next element in an ArrayList.

24. How to remove an element from an array?

To remove an element from an array we have to delete the element first and then the array elements lying to the right of the element are shifted left by one place.

25. Difference between a = a + b and a += b ?

The += operator implicitly cast the result of addition into the type of the variable used to hold the result. When you add two integral variables e.g. variable of type byte, short, or int then they are first promoted to int and them addition happens. If the result of the addition is more than the maximum value of a then a + b will give compile-time error but a += b will be ok as shown below
byte a = 127;
byte b = 127;
b = a + b; // error : cannot convert from int to byte
b += a; // ok

Java OOPS Interview Questions

1. What is Constructor Overloading?

When a class has multiple constructors with different function definitions or different parameters it is called constructor overloading.

import java.lang.*; 
public class constructor_overloading { 
    double sum; 
    constructor_overloading(int x,int y){ 
    constructor_overloading(double x,double y){ 
    void print_sum(){ 
    public static void main(String args[]){ 
        constructor_overloading c=new constructor_overloading(); 
        constructor_overloading c1=new constructor_overloading(10,20); 
        constructor_overloading c2=new constructor_overloading(10.11,20.11); 

2. How many types of Inheritance are possible in Java?

Single, multiple, multilevel, hybrid and hierarchical inheritance are possible in java. Hybrid inheritance and hierarchical inheritance are only possible through interfaces.

3. How many types of constructor does Java support?

Java supports the following types of constructors:
– Non-Parameterized or Default Constructors
– Parameterized Constructors
– Copy constructor

4. What is the role of finalize()?

Finalize() is used for garbage collection. It’s called by the Java run environment by default to clear out unused objects. This is done for memory management and clearing out the heap.

5. Explain encapsulation in Java.

Encapsulation is the process of wrapping variables and functions together into a single unit in order to hide the unnecessary details. The wrapped up entities are called classes in java. Encapsulation is also known as data hiding because it hides the underlying intricacies.

6. Explain abstraction in Java.

Abstraction is the process of revealing the essential information and hiding the trivial details across units in java. Java has abstract classes and methods through which it does data abstraction.

7. If a child class inherits base class then are the constructor of the base class also inherited by the child class?

Constructors are not properties of a class. Hence they cannot be inherited. If one can inherit constructors then it would also mean that a child class can be created with the constructor of a parent class which can later cause referencing error when the child class is instantiated. Hence in order to avoid such complications, constructors cannot be inherited. The child class can invoke the parent class constructor by using the super keyword.

8. What is the use of super?

super() is used to invoke the superclass constructor by the subclass constructor. In this way, we do not have to create different objects for super and subclasses.

9. How is encapsulation achieved in Java?

Encapsulation is achieved by wrapping up data and code into simple wrappers called classes. Objects instantiate the class to get a copy of the class data.

10. What is an abstract class in Java?

An abstract class is a class that can only be inherited and it cannot be used for object creation. It’s a type of restricted class with limited functionality.

11. How is polymorphism achieved in Java?

An example of polymorphism is the == operator which can be used to compare both numerics and strings.

12. Can the main method be declared as private in Java?

Yes, the main method can be declared as private.

13. What is an object in Java?

An object is an instance of a class in java. It shares all attributes and properties of a class.

14. What happens if we make the constructor final?

If we make the constructors final then the class variables initialized inside the constructor will become unusable. Their state cannot be changed.

15. What is constructor chaining?

constructor chaining is the process of invoking constructors of the same class or different classes inside a constructor. In this way multiple objects are not required for constructor invocation with constructors having different parameters.

Java Multithreading Interview Questions

1. If we clone objects using the assignment operator does the references differ?

When objects are cloned using the assignment operator, both objects share the same reference. Changes made to the data by one object would also be reflected in the other object.

2. What is Thread?

A thread is a lightweight program that allows multiple processes to run concurrently. Every java program has at least one thread called the main thread, the main thread is created by JVM. The user can define their own threads by extending the Thread class (or) by implementing the Runnable interface. Threads are executed concurrently.

public static void main(String[] args){//main thread starts here 

3. Can we start a thread twice in java?

Once a thread is started, it can never be started again. Doing so will throw an IllegalThreadStateException

4. How can java threads be created?

Threads can be created by implementing the runnable interface.
Threads can also be created by extending the thread class

This brings us to the end of the Java Interview Questions. Glad to see you are now better equipped to face an interview. 

Leave a Reply

Your email address will not be published. Required fields are marked *