Top 50 Java Interview Questions and Answers

We have already shared AWS interview questions and now we are going to provide you with Top 50 Java Interview Questions and Answers
Top 50 Java Interview Questions and Answers

We have already shared AWS interview questions and now we are going to provide you with Top 50 Java Interview Questions and Answers

Top 50 Java Interview Questions and Answers

Question 1: What is Collection? What is a Collections Framework? What are the benefits of Java Collections Framework?

Collection: A collection (also called as container) is an object that groups multiple elements into a single unit.

Collections Framework: Collections framework provides unified architecture for manipulating and representing collections.

Benefits of Collections Framework:

  1. Improves program quality and speed
  2. Increases the chances of reusability of software
  3. Decreases programming effort.
Question 2: What are the various access specifiers for Java classes?

In Java, access specifiers are the keywords used before a class name which defines the access scope. The types of access specifiers for classes are:

  1. Public: Class, Method, Field is accessible from anywhere.
  2. Protected: Method, Field can be accessed from the same class to which they belong or from the sub-classes, and from the class of same package, but not from outside.
  3. Default: Method, Field, class can be accessed only from the same package and not from outside of its native package.
  4. Private: Method, Field can be accessed from the same class to which they belong.
Question 3: What is data encapsulation and what’s its significance?

Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.

Encapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves data hiding purpose.

Question 4: What are Loops in Java? What are three types of loops?

Looping is used in programming to execute a statement or a block of statement repeatedly. There are three types of loops in Java:

1) For Loops

For loops are used in java to execute statements repeatedly for a given number of times. “For” loops are used when number of times to execute the statements is known to programmer.

2) While Loops

While loop – is used when certain statements need to be executed repeatedly until a condition is fulfilled. In “while loops”, condition is checked first before execution of statements.

3) Do While Loops

Do While Loop is same as while loop with only difference that condition is checked after execution of block of statements. Hence in case of do while loop, statements are executed at least once.

Question 5: What is the difference between a class variable and an instance variable in Java?

Class Variables only have a single copy of the variable and are declared with static modifiers. Every object of the class shares a single copy of the class variable, so if any changes are made to a class variable they will be seen by all the objects of a class. A class variable is allocated memory when the class is loaded first time.

Example of a Class Variable Declaration in Java

Public class Product {

    public static int Barcode;

}

Instance variables belong to an object and are specified without a static modifier. Every object of the class will have its own personal copy of the instance variable unlike class variables where single copy of the variable is shared by different objects of the class.

Example of an Instance Variable Declaration in Java

public class Product {

    public int Barcode;

}
Question 6:  What is the difference between an abstract class and interface?

Interface is different from an abstract class because interface is just a type that can be satisfied by a class which implements the interface. Interfaces in java help implement multiple inheritance because a class can extend only one other class.

Interface do not have any implementation and just are limited to constants and public methods whereas abstract class in java can have partial implementation along with static methods and protected access blocks. A class can extend only one abstract class but it can implement several interfaces.

Question 7: Name The Core Collection Interfaces?
Collection Interfaces
Collection Interfaces

Important Ones Are: Collection , Set , Queue , List , Map

Other interface also in the list:  SortedSet, SortedMap , Deque, ListIterator etc.

Question 8: Differentiate between Throw and Throws in Exception Handling.

Throw clause is used when a user wants to throw a customized explicit exception. Throw clause is used if there is a need for a specific exception to be thrown to the calling method.

try {

if (age>=100) {throw new AgeBarException (); //This is a customized exception

} else {

....}

}

} catch (AgeBarException ex) {

...code to handle Exception.....

}

Throws Clause lists all the exceptions that piece of code might throw. Throws clause provides a warning to the invoking method that these are the list of exceptions it might throw and all these need to be handled.

  • throws is used to declare an exception whereas throw clause is used to explicitly throw an exception.
  • throws clause is specified in the method signature whereas throw clause is used within a method.
  • Throws clause is often followed by a class whilst throw clause is often followed by an instance.
Question 9: How will you achieve multi-threading in Java?

Multithreading in Java can be achieved in two ways –

  • By defining a new class which implements the runnable interface. An object of that class is then passed to constructor method of Thread.
  • By defining a new class that extends the thread class.
Question 10: Can you explain the difference between path and classpath?

These are the operating system environment variables wherein PATH variable defines the system where executable files are present while CLASSPATH is used to specify the location of .class files.

Difference Between Path and Classpath

  1. The main difference between PATH and CLASSPATH is that  PATH is an environment variable which is used to locate JDK binaries like “java” or “javac” command used to run java program and compile java source file. On the other hand, CLASSPATH, an environment variable is used by System or Application ClassLoader to locate and load compile Java bytecodes stored in the .class file.
  2. In order to set PATH in Java, you need to include JDK_HOME/bin directory in PATH environment variable while in order to set CLASSPATH in Java you need to include all those directories where you have put either your .class file or JAR file which is required by your Java application.
  3. Another significant difference between PATH and CLASSPATH is that PATH cannot be overridden by any Java settings but CLASSPATH can be overridden by providing command line option -classpath or -cp to both “java” and “javac” commands or by using Class-Path attribute in Manifest file inside JAR archive.
  4. PATH environment variable is used by operating system to find any binary or command typed in the shell, this is true for both Windows and Linux environment while CLASSPATH is only used by Java ClassLoaders to load class files.
Question 11: What is the difference between HashMap and Hashtable?

It is one of the most popular collections interview question for java developer . Make sure you go through this once before appearing for the interview.

Main differences between HashMap and Hashtable are:

  1. HashMap allows one null key and any number of null values while Hashtable does not allow null keys and null values.
  2. HashMap is not synchronized or thread-safe while Hashtable is synchronized or thread-safe.
  3. One of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you were using Hashtable.
Question 12: What is the difference between continue and break statement?

Break and continue are two important keywords used in Loops. When a break keyword is used in a loop, loop is broken instantly while when continue keyword is used, current iteration is broken and loop continues with next iteration.

In below example, Loop is broken when counter reaches 4.

for (counter=0;counter<10;counter++)

system.out.println(counter);

 if (counter==4) {

 break;}

 }

In the below example when counter reaches 4, loop jumps to next iteration and any statements after the continue keyword are skipped for current iteration.

for (counter=0;counter<10;counter++)

system.out.println(counter);

if (counter==4) {

continue;

}

system.out.println("This will not get printed when counter is 4");

}

for (counter=0;counter<10;counter++)

system.out.println(counter);

if (counter==4) {

continue;

}

system.out.println("This will not get printed when counter is 4");

}
Question 13: What is Final Keyword in Java? Give an example.

In java, a constant is declared using the keyword Final. Value can be assigned only once and after assignment, value of a constant can’t be changed.

In below example, a constant with the name const_val is declared and assigned avalue:

Private Final int const_val=100

When a method is declared as final,it can NOT  be overridden by the subclasses.This method are faster than any other method,because they are resolved at complied time.

When a class is declares as final,it cannot be subclassed. Example String,Integer and other wrapper classes.

Question 14: What are Java Packages? What’s the significance of packages?

In Java, package is a collection of classes and interfaces which are bundled together as they are related to each other. Use of packages helps developers to modularize the code and group the code for proper re-use. Once code has been packaged in Packages, it can be imported in other classes and used.

Question 15: What’s the difference between an Abstract Class and Interface in Java?

The primary difference between an abstract class and interface is that an interface can only possess declaration of public static methods with no concrete implementation while an abstract class can have members with any access specifiers (public, private etc) with or without concrete implementation.

Another key difference in the use of abstract classes and interfaces is that a class which implements an interface must implement all the methods of the interface while a class which inherits from an abstract class doesn’t require implementation of all the methods of its super class.

A class can implement multiple interfaces but it can extend only one abstract class.

Question 16:  What do you mean by Mutable and immutable objects?

If the value of the object can be changed then it is referred to as a Mutable object. If after the creation of an objects, it value cannot be changed then it is an immutable object. String, Integer, Float in java are examples of immutable object whereas String Buffer object is an example of mutable object in java.

Question 17: What is the difference between method overloading and overriding in Java?

Method overloading happens during compile time within a class whereas Method Overriding happens between two classes that have IS-A i.e. inheritance relationship. For method overriding we require parent and child classes whereas for method overloading a single class is enough.

  • Static binding is used for method overloading as the call to the overloaded method is made during the compile time whereas dynamic binding is used for method overriding as the call to the overridden method is made at run time.
  • Method overloading requires different argument list to the method whereas in method overriding the argument list has to be same.
  • Method overloading gives better performance over method overriding since the binding of the overloaded methods is done at compile time and not run time.
Question 18: What is the fundamental difference between shallow copy and deep copy in Java?

In Shallow copy a new object is created that has the same values like the original object. If any of the fields in the object reference other objects in that case only the memory address is copied.

In deep copy all fields are copied and copies are created for dynamically allocated memory that points to by the fields. In deep copy, an object is copied along with the other objects it refers to.

The default version of the clone () method will create a shallow copy of the object.

Question 19: Explain about garbage collection in Java.

Java manages memory automatically by removing the unused variable or objects from the memory. This process is referred to as garbage collection. User java programs cannot free the object memory, so the garbage collector (gc) in java freeze the objects or variables that are no longer being used by a program. JVM considers an object or variable as alive as long as it is being referenced by a program. Once it finds that the object cannot be reached by the program code, it is removed so that the unused memory can be reclaimed.

Question 20: What is a Transient variable in Java?

Java has a special keyword known as transient which indicates that a variable should not be serialized when it is stored to streams of bytes. Whenever an object is transferred through a network it should be serialized to convert the object state into serial bytes.

Transient variables are initialized by their default value during de-serialization. For instance, for object transient variable, the value would be NULL.

Question 21: Is it mandatory to have a catch block after every try block in the program code?

It is not necessary to have a catch block after every try block in the program code. All exceptions that are likely to be thrown should be mentioned in the throws clause of the method followed by either a catch block or a finally block.

Question 22: What is synchronization in Java?

The process of monitoring the access to shared resources by multiple threads so that only one thread can access one resource at time is known as synchronization. Synchronization is used to avoid data consistency and corruption problems and also to prevent any kind of thread interference.

Java provides a special keyword known as “synchronized” which can be used either for synchronizing a block of code or for synchronizing a method.

  1. The keyword “synchronized” can be used a part of the method declaration.
  2. Or a block of code can be placed in synchronized keyword using ‘this’ java operator.
Question 23: Differentiate between a process and a thread.

In simple terms, threads are a part of a process i.e. a single process in java can spawn multiple threads.  Threads and processes in Java are independent paths of execution .A process gets its own memory address space whereas a thread shares the heap space belonging to the parent process. Every process in java has a unique process identifier, executable code and memory space whereas a thread has its own stack in Java but makes use of the process memory and shares it with other threads.

Question 24: I have 10 .java files in a folder. What is the process to compile all the files using a single command line execution instead of compiling each .java file separately?

Executing the “javac *.java “command from the directory location will compile all the files present in the folder with .java extension.

Question 25: What is the difference between ArrayList and Vector? Which one shall be preferred?

ArrayList and Vector both use Array as a data structure internally. However there are few differences in the way they store and process the data. In this post we will discuss the difference and similarities between ArrayList and Vector.

ArrayList Vs Vector:

1) Synchronization: ArrayList is non-synchronized which means multiple threads can work on ArrayList at the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be an another thread performing remove operation on ArrayList at the same time in a multithreaded environment

While Vector is synchronized: This means if one thread is working on Vector, no other thread can get a hold of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.

2) Resize: Both ArrayList and Vector can grow and shrink dynamically to maintain the optimal use of storage; however the way they resized is different. ArrayList grow by half of its size when resized while Vector doubles the size of itself by default when grows.

3) Performance: ArrayList gives better performance as it is non-synchronized. Vector operations gives poor performance as they are thread-safe, the thread which works on Vector gets a lock on it which makes other thread wait till the lock is released.

4) fail-fast: First let me explain what is fail-fast: If the collection (ArrayList, vector etc) gets structurally modified by any means, except add or remove methods of iterator, after creation of iterator then the iterator will throw ConcurrentModificationException. Structural modification refers to the addition or deletion of elements from the collection.

As per the Vector javadoc the Enumeration returned by Vector is not fail-fast. On the other side the iterator and listIterator returned by ArrayList are fail-fast.

Question 26: What Are the Similarities Between ArrayList Vs Vector?

There are few similarities between these classes which are as follows:

  1. Both Vector and ArrayList use growable array data structure.
  2. The iterator and listIterator returned by these classes (Vector and ArrayList) are fail-fast.
  3. They both are ordered collection classes as they maintain the elements insertion order.
  4. Vector & ArrayList both allows duplicate and null values.
  5. They both grows and shrinks automatically when overflow and deletion happens.
Question 27: When to use ArrayList and when to use a vector?

It totally depends on the requirement. If there is a need to perform “thread-safe” operation the vector is your best bet as it ensures that only one thread access the collection at a time.

Question 28: How to make ArrayList synchronized?

As I stated above ArrayList methods are non-synchronized but still if there is a need you can make them synchronized like this –

//Use Collecions.synzhonizedList method

List list = Collections.synchronizedList(new ArrayList());

...

//If you wanna use iterator on the synchronized list, use it

//like this. It should be in synchronized block.

synchronized (list) {

  Iterator iterator = list.iterator();

  while (iterator.hasNext())

      ...

      iterator.next();

      ...

}
Question 29: What is the difference between HashSet and TreeSet?

Main differences between HashSet and TreeSet are:

  1. HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order
  2. HashSet can store null object while TreeSet cannot store null object.
    find detailed explanation here TreeSet vs HashSet in Java
Question 30: When we should use serialization?

Serialization is used when data needs to be transmitted over the network. Using serialization, object’s state is saved and converted into byte stream. The byte stream is transferred over the network and the object is re-created at destination.

Question 31: What is multi-threading?

Multi-threading is a programming concept to run multiple tasks in a concurrent manner within a single program. Threads share same process stack and running in parallel. It helps in performance improvement of any program.

Question 32: Why Runnable Interface is used in Java?

Runnable interface is used in java for implementing multi-threaded applications. Java.Lang.Runnable interface is implemented by a class to support multi-threading.

Question 33: What are the two ways of implementing multi-threading in Java?

Multi-threaded applications can be developed in Java by using any of the following two methodologies:

  1. By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi-threading. There is a Run() method in this interface which is implemented.
  2. By writing a class that extends Java.Lang.Thread class.
Question 34:  In multi-threading how can we ensure that a resource isn’t used by multiple threads simultaneously?

In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization. Using synchronized keyword, we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it has become free from the other one using it.

Question 35: What is the difference between String, StringBuilder and StringBuffer?

String:

A string is immutable (once created cannot be changed) object. The object created as a String is stored in the Constant String Pool.

Every immutable object in Java threads safe that implies String is also threaded safe. A string cannot be used by two threads simultaneously.

String once assigned cannot be changed.

StringBuffer

StringBuffer is mutable means one can change the value of the object. The object created through StringBuffer is stored in the heap. StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized that is StringBuffer is threaded safe.

StringBuilder

StringBuilder is same as the StringBuffer, that is it stores the object in heap and it can also be modified. The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not threaded safe. StringBuilder is fast as it is not threaded safe.

Question 36: How to convert Vector to String array in java?

Let’s have a look at the below example where we are converting a Vector of Strings to an array. We are using toString() method of Vector class to do this.
public String toString(): It returns a string representation of this Vector, containing the String representation of each element.

import java.util.Vector;

public class VectorToArray {

  public static void main(String[] args) {

     // Creating a Vector of String elements

     Vector<String> vector = new Vector<String>();

     // Add elements to Vector

     vector.add("Item1");

     vector.add("Item2");

     vector.add("Item3");

     vector.add("Item4");

     vector.add("Item5");

     vector.add("Item6");

    //Converting Vector to String Array

    String[] array = vector.toArray(new String[vector.size()]);

    //Displaying Array Elements

    System.out.println("String Array Elements :");

    for(int i=0; i < array.length ; i++){

       System.out.println(array[i]);

    }

  }

}

Output:

String Array Elements:

Item1

Item2

Item3

Item4

Item5

Item6

The steps we followed in above code are:

1) Created a Vector of type String

2) Added elements to it using add(Element E) method of Vector class.

3) Converted the Vector to Array using toArray(new String[vector.size()]).

Question 37: How can we make the copy of a Java object?

We can use the concept of cloning to create the copy of an object. Using clone, we create copies with the actual state of an object.

Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.

Question 38: How can we restrict inheritance for a class so that no class can be inherited from it?

If we want a class not to be extended further by any class, we can use the keyword Final with the class name.

In the following example, Stone class is Final and can’t be extend

public Final Class Stone {

// Class methods and Variables

}

public Final Class Stone {

// Class methods and Variables

Question 39: What’s the access scope of Protected Access specifier?

When a method or a variable is declared with protected access specifier, it becomes accessible in the same class, any other class of the same package as well as a sub-class.

Protected Access specifier
Protected Access specifier
Question 40: How can we use primitive data types as objects?

Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.

Question 41: Which types of exceptions are caught at compile time?

Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using try-catch block in the code in order to successfully compile the code.

Question 42: Describe different states of a thread.

A thread in Java can be in either of the following states:

Ready: When a thread is created, it’s in the Ready state.

Running: A thread currently being executed is in running state.

Waiting: A thread waiting for another thread to free certain resources is in waiting state.

Dead: A thread which has gone dead after execution is in the dead state.

Question 43: Can we override a method by using same method name and arguments but different return types?

The basic condition of method overriding is that method name, arguments, as well as return type, must be exactly same as is that of the method being overridden.  Hence using a different return type doesn’t override a method.

Question 44: What are the two environment variables that must be set in order to run any Java programs?

Java programs can be executed in a machine only once following two environment variables have been properly set:

PATH variable

CLASSPATH variable

Question 45: Is it possible to define a method in Java class but provide it’s implementation in the code of another language like C?

Yes, we can do this by use of native methods. In case of native method based development, we define public static methods in our Java class without its implementation and then implementation is done in another language like C separately.

Question 46: How destructors are defined in Java?

In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the job automatically by destroying the objects when no longer referenced.

Question 47: Can we have static methods in an Interface?

Static methods can’t be overridden in any class while any methods in an interface are by default abstract and are supposed to be implemented in the classes being implementing the interface. So it makes no sense to have static methods in an interface in Java.

Question 48: In Java thread programming, which method is a must implementation for all threads?

Run() is a method of Runnable interface that must be implemented by all threads.

Question 49: How can an exception be thrown manually by a programmer?

In order to throw an exception in a block of code manually, throw keyword is used. Then this exception is caught and handled in the catch block.

public void topMethod(){

try{

excMethod();

}catch(ManualException e){ }

}

public void excMethod{

String name=null;

if(name == null){

throw (new ManualException(“Exception thrown manually “);

}

}

public void topMethod(){

try{

excMethod();

}catch(ManualException e){ }

}

public void excMethod{

String name=null;

if(name == null){

throw (new ManualException(“Exception thrown manually “);

}

}

Question 50: Which API is provided by Java for operations on set of objects?

Java provides a Collection API which provides many useful methods which can be applied on a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet and TreeMap.

That’s it!!!!

Whether you are a fresher or highly experienced professional, java plays a vital role in any Java/JEE interview. Java is the favorite area in most of the interviews and plays a crucial role in deciding the outcome of your interview. That’s why we have come up with these most commonly asked interview questions.

To learn more about Java Programming, join Java Tutorial Chat for FREE and get FREE training material and Guide!

Furthermore, Subscribe JNTU World today to get instant career alerts!

Also, don’t ever forget to share this post with your friends via WhatsApp groups!

Rate this post