Top 75 Java Interview Questions and Answers in 2022

image of Top 75 Java Interview Questions and Answers in 2022

Do you want to ace your Java Interview and want to know how to answer java interview questions? Well, we are here to help you! Java is one of the most integrated and widely used programming languages currently used in the information technology industry. One of the fundamental reasons the freshers and professionals are switching to a programming career path is because of its high potential. This programming language has evolved and shares the largest digital world today by offering authentic platforms on which several services and applications are formed.

This article will list some of the most important Java Interview Questions that will help you crack it best. Here is the list of Java interview questions for experienced professionals. So, without wasting your time, let’s get started!

Java Interview Questions: Freshers

Are you just a fresher who is seeking career opportunities in Software development? Here are the top Java interview questions for freshers or beginners that will help you crack the interview. It includes Java interview questions for 1-2 years experienced candidates.

Q1: What is Java?

Ans: Java is a general-purpose, object-oriented, and high-level programming language originally developed by James Gosling and further developed by the Oracle Corporation. It is one of the most popular programming languages in today’s world. It works on multiple platforms supported by Java JVM such as Linux, Windows, Mac, etc. JVM comes packed inside the Java JRE, and operating systems like Linux, Unix, Windows, or Mac have their own Versions of Java JRE. However, it is widely used for web servers, games, database connections, desktop applications, mobile applications, and more.

One of the most common Interview Questions Java, which an interviewer can ask you.

Q2: What is JVM?

Ans: JVM stands for Java Virtual Machine. It is a Virtual Machine that provides a runtime environment to execute the Java Code.

Performs the Following Operations:

  1. Loads Code
  2. Verifies Code
  3. Executes Code

Q3: What is JRE?

Ans: JRE Stands for Java Runtime Environment. In simple terms, the Software Layer runs on the top of the operating system and also provides class libraries or other resources required by the java program to run.

JRE works with JDK (Java Development Kit) to build a sustainable runtime environment that enables the execution of Java programs easily.

JRE Architecture:

  1. ClassLoader
  2. Bytecode Verifier
  3. Interpreter

Q4: What is a ClassLoader?

Ans: A classLoader is a subsystem of Java Virtual Machine that is persistent to the loading class field when a program is carried out. It is one of the first systems to load the executable file.

ClassLoader is included in the core Java interview questions you must prepare before your interview.

Q5: What is ByteCode Verifier?

Ans: It Guarantees the Structure/Format and accuracy of any Java Code before it can pass to the Interpreter. If the code violates any system integrity, the class will be marked as corrupted and not loaded.

Q6: What is an Interpreter?

Ans: Java Interpreter is system software that is designed to read & implement the program. In Simple terms, Java Interpreter converts the high-level language into Machine language ( assembly language ).

Java Interpreter is one of the significant reasons Java is considered a platform for an independent programming language. You can run java programs on any system that supports Java Interpreter.

The Java Interpreter converts the Java bytecode (.class file ) into code compatible with the operating system.


Q7: What are the meaning of an instance and a local variable?

Ans: Instance variables are those variables that are accessible and operated by all the procedures in the class. They are announced outside the methods and inside the class and are represented as the properties of an object and remain bound to it anyhow.

Every object of this class will have a copy of its variables for usage. If any changes are made in these variables, only instance variables will be affected, and all other variables will remain unchanged.

Local variables present within a function, block, or constructor can only be accessed inside. The usage of these variables is restricted to the block scope. The other class methods would not know the local variables whenever a local variable is announced inside the procedure.

Example of Instance Variable

public class VarEx{
int myVar;
static int db = 40;

public static void main(String args[]){
int i = 200;
VarEx obj = new VarEx();

System.out.println("Value of instance variable myVar: "+obj.myVar);
System.out.println("Value of static variable db: "+VarEx.db);
System.out.println("Value of local variable i: "+i);


Value of instance variable myVar: 0
Value of static variable db: 40
Value of local variable i: 200

Q8: What are the fundamental allocations available in Java?

Ans: Java has five preeminent memory allocations, which are class memory, stack memory, heap memory, program counter-memory, and native method stack memory.

Q9: What are Memory Allocations in Java?

Ans: In Java, Memory Allocation is a process where the program and services are allocated to virtual memory spaces. The Virtual Memory Spaces are divided into two sections.

  • Stack Memory
  • Heap Space Memory

Differentiate between Stack and Heap Space Memory

Heap Space Memory Stack Memory
Heap Memory can be accessed by all parts of an application or program. The Execution of Stack Memory is restricted or limited to a single thread.
Objects can be created anytime and it is eventually stored in the heap space. The Stack Memory only comprises its local primitive variables.
Objects created in Heap Space can be accessed globally across the program or application. Other Threads cannot access stack memory Objects
Heap Space Memory is defined according to young and old Generation Stack Memory management occurs on a Last-In-First-Out basis.
Heap Space Memory remains according to the scope of Program or Application. Stack Memory is Temporary
The Methods Like JVM are used to define or allocate the optimal size of the Heap memory Stack Memory gets determined by using XSS Method
java.lang.OutOfMemoryError occurs if memory is full java.lang.StackOverFlowError appears whenever memory is full.
The Size is large, but the processing time is more than Stack Memory. The Size is smaller; execution is faster due to LIFO ( Last In First Out) operation.

Q10: What is the significant difference between double and float variables in Java?

Ans: Float takes 4 bytes in memory in Java, whereas Double takes 6 bytes in memory. Float is a single accurate floating-point decimal number, and double is the double accurate decimal number.

Example of Double and Float Variable

float pie = 22/7f;
float pieby4096 = pie/4096;
double dpie = 22/7d;
double dpieby4096 = dpie/4096;
System.out.println("Float Pie is - " + pie);
System.out.println("Double pie is - " + dpie);
System.out.println("Float Pie divided by 4096 - " + pieby4096);
System.out.println("Double Pie divided by 4096 - " + dpieby4096);
double pieby4096usingfloatpie = pie/4096;
System.out.println("Float Pie divided by 4096 with result as double - " + pieby4096usingfloatpie);


Float Pie is - 3.142857
Double pie is - 3.142857142857143
Float Pie divided by 4096 - 7.672991E-4
Double Pie divided by 4096 - 7.672991071428571E-4
Float Pie divided by 4096 with result as double - 7.672990905120969E-4

 Q11: What is Java IDE? Which Java IDE is the best?

Ans: A Java IDE is a software that permits Java Developers to write and debug Java programs. In simple words, it is the collection of multiple programming tools, which can be accessed via a single platform, along with multiple features such as syntax highlighting, code completion, and more. Eclipse, NetBeans, and Codenvy are some of the best Java IDEs.

Q12: What is the meaning of Java Packages? What is its importance?

Ans: Java Packages are the collection of interfaces and classes that are gathered together as they are related to each other. It helps the developers to modularize the group and the code to re-use it. Once the code has been collected together, it can be brought to other classes and used.

Java Packages are divided into 2 categories

  1. Built-in Packages
  2. User-defined Packages


import java.util.*;

package mypack;
class mypackClass {
public static void main(String[] args) {
System.out. println(“package delivered!”);


package delivered!

Q13: What is the method to serialize an object in Java?

Ans: To convert an object into a byte stream by serialization in Java, the class executes an interface with the name Serializable. All the class objects executing serializable interface are serialized, and their state is retained in the byte stream.

If you are going for the interview, it is one of the essential Java technical interview questions that you should know.

Q14: What is the right time to use serialization?

Ans: The perfect time to use the serialization is when data is needed to be transferred over the network. The object’s state is retained and transmitted through serialization into a byte stream. The byte stream 9is transmitted over the network, and the object is re-formed at the destination.

Q15: Can a class have more than one constructor?

Ans: Yes. A class can have more than one constructor with various parameters. The usage of the constructor for the object depends on the arguments passed wh8ile establishing the objects.

When you go for the interview, remember it is one of the essential Java interview questions interviewers can ask.

Q:16 List five major features of the Java programming language.

Ans: Here are the top five features of the Java programming language:

  • Highly simple: Java is simply easy to learn, and you do need to be from a science background to get a hold of it. It is based on C++, making it easier to do programming on it.
  • Independent platform: Java is an open-source and independent programming language. Hence, it is varied from multiple programming languages such as C and C++ that have to be carried out.
  • Secured: Java is a secured programming language that does not use definite pointers. It also offers ByteCode and Exception handling that makes it safer.
  • High Performance: Java is comparatively faster than other programming languages as Java bytecode is close to its other native code.
  • Dynamic: Java is dynamic, which supports different loading of classes. Besides that, it also supports functions from its constitutional languages like C and C++.

Q17: What is the difference between HashMap and HashTable in Java?

Ans: HashMap is unsynchronized, and it cannot be shared with multiple threads without a proper synchronization code. It is faster, traversed via the iterator, and enables null keys and various null values. Finally, it inherits the AbstractMap class.

HashTables are synchronized in nature. It is highly safe and can be shared with various threads. It did not enable null keys or value and was present in previous versions of Java. However, it is slow and is traversed through iterators and enumerators. Besides that, it inherits the Dictionary class.

These are some essential terms that can be asked in Java technical interview questions.

Table to Differentiate between HashMap and HashTable

HashMap HashTable
It is Unsynchronized It is synchronized
It allows null key and multiple null values It doesn’t allow any null value
It is Fast It is Slow
It is traversed by Iterator It is traversed by Enumerator & Iterator
Iterator in HashMap is fail-fast Enumerator is not fail-fast
It inherits AbstractMap Class It Inherits Dictionary Class

Q18: Why are pointers not concluded in Java?

Ans: Java does not permit pointers because it is highly unsafe and increases the complications of the program. Hence, Java is famous for its simplicity; adding pointers will make it more disputing.

Q19: What is the purpose of a JIT compiler in Java?

Ans: JIT, also known as Just-In-Time compiler in Java. It is an essential program that helps transform the Java bytecode into instructions, which are directly sent to the processor. The JIT compiler is permitted in Java and is activated whenever the Java method is supplied. Afterward, it gathers the bytecode into native machine code, compiling it just in time. Once it is done, the JVM holds on to the compiled code of the method directly instead of expounding it.

Hence, it is included in top Java interview questions and answers in 2022. So, before giving the interview, learn more about it.

Q20: What is object-oriented programming?

Ans: Object-oriented programming is also known as OOPs. It is a programming model or a process where programs are settled around the objects instead of logic and functions. In simple words, OOP is highly focused on the objects that are needed to be manipulated rather than logic. It is considered one of the best processes for programs with large and complex codes to be maintained promptly.


Q21: Why are strings called immutable in Java?

Ans: Strings objects are immutable in Java because once the value has been assigned to a string, it cannot be varied. However, if it is changed, a new object is created.

Q22: What is the meaning of multi-threading?

Ans: Multi-threading is a programming concept to run different tasks simultaneously on a single platform. These threads share the same process stack and run in parallel, and also help enhance the performance of any program.

Q23: What are the two different ways of implementing multi-threading in Java?

Ans: Multithreaded applications can be formed in Java by any of the following methods:

  • It can be created by using Java.Lang.Runnable Interface.
  • By writing a class that expands Java.Lang, Thread Class.

It is mentioned in the top Java programming interview questions and answers. So, do not forget to go through it before your interview.

Q24: How can you execute any code before the main method?

Ans: If you want to execute any statement before the formation of objects at the load time of class, you can consider using a static block of code in the class. Any statement mentioned in this block of code will get implemented once at the time of loading the class, even before the main method creates the object.

class exampleStatic {
// static block
System.out. println(“Static Block Running”);

//main method
public static void main(String args[])
System.out. println(“ Now main method is running “);

Output: ( as per JDK 1.6 )

Static Block Running

If you are using JDK 1.7


Error: Main method not found in class exampleStatic, please define the main method as: public static void main(String args[])

Q25: What is the meaning of overloading?

Ans: Overloading is the occurrence of two or more methods or when the operators have the same representation.

For example, the + operator adds two figure values but connects the two strings. Likewise, an overloaded function called Add can be used for two different purposes, which are as follows:

  • To add two integers
  • To connect two strings

Overloading needs two overloaded methods to have the same name but different disputes. Hence, the functions may or may not have different return types.


public class Add {
//overloaded add() which takes 2 integer parameters
public int add(int a, int b)
return (a+ b);

//overloaded add() which takes 3 integer parameters
public int add(int a, int b, int c)
return (a + b + c);

//overloaded add() which takes 2 double parameters
public double add( double a, double b)
return (a + b);

//main code
public static void main(String args[ ] )
Add a = new Add();
System.out. println(a.add(20, 30));
System.out. println(a.add(20, 30, 40));
System.out. println(a.add(20.5, 30.5));



Q26: What is the difference between, string builder, and string buffer?

Ans: String variables are kept in a constant stirring pool. With the forming change in the string reference, it becomes infeasible to delete the old value. For example, if a string has a stored value “up,” then adding the new value “down” would not delete the old value. It will be stored there in a resting state. The string buffer is synchronized and shows slower performance than the stringer buffer. However, the string builder shows faster performance and is also not synchronized.

Table to Differentiate Between StringBuilder, and StringBuffer

Sno StringBuffer StringBuilder
1 StringBuffer is synchronized, which means 2 threads can’t call the methods of StringBuffer. StringBuilder is non-synchronized, meaning threads are not safe and they can call the methods of StringBuilder
2 It is less efficient as compare to String Builder It is more efficient as compare to String Buffer
3 It was introduced in Java Version 1.0 It was introduced in Java Version 1.5

It is one of the important core Java interview questions that you should not forget.

Q27: What is the meaning of string pool in Java?

Ans: Java has a collection of strings stored in the heap memory that refers to the String pool. Hence, whenever a new object is formed, it is checked to see if it is already available or not. If it is there, the same reference is returned to the variable, or a new object is formed in the string pool, and the other one is returned.

Q28: What is the platform?

Ans: A platform is a hardware or software environment where software is implemented. There are two types of platforms, which are software-based and hardware-based, and Java provides the software-based platform.

It is one of the basic questions that interviewers can ask during interview questions in Java.

Q29: Why yield() methods are used in Java?

Ans: The yield method is associated with the thread class, which helps transfer the currently running thread to a runnable state and permits others to be implemented. In simple words, it gives equal chances to the threads to run as it is a static method, and it does not reveal any lock.

Q30: What are the primitive data types in Java?

Ans: There are eight different types of primitive data, which are as follows:

  • Boolean
  • Char
  • Byte
  • Long
  • Short
  • Double
  • Float
  • Int

In simple words, it serves as the building block of data manipulation in Java.

Q31: What is the meaning of inheritance in Java?

Ans: Inheritance in Java is when one class can extend to another. The goal is to reuse the codes from one class to another class. Hence, the existing class is called the Super Class, whereas the obtained class is called a sub class.

Q32: How many types of constructors are used in Java programming?

Ans: There are two types of constructors in Java, which are as follows:

  • Default Constructor: One of those constructors does not accept any value. It is highly used to adjust the occurred variable with the default values. However, it can also be used for performing essential tasks on the creation of objects. A reverted constructor is created by the compiler if no constructor is presented in the class.
  • Parameterized Constructor: It is a constructor in which one can reset the mentioned variable with the provided values. In simple words, we can mention that the constructors which can accept disputes are called parameterized constructors.

Do not forget to read more about constructors before your Java interview questions!

Q33: Can you overload the constructors in Java?

Ans: Yes, the constructors can be overloaded in Java by chasing the number of disputes accepted by the constructor. You can also change the data type of the parameters to overload the constructors.

Also Read: Reason for Job Change

Java Interview Questions: Intermediate

Java is one of the eminent programming languages that has gained popularity. If you have basic knowledge of Java and want to prepare for the intermediate level, here are the top Java interview questions for the intermediate level. It also includes senior Java developer interview questions for experts, who have more than 5 years of experience.

Q1: Which API is offered by Java for operations on a set of objects?

Ans: Java offers a Collection API that offers several useful methods that can be implemented on a set of objects. Some of the essential classes offered by the Collection API consist of HashMap, ArrayList, TreeMap, and TreeSet.

Q2: What are wrapper classes?

Ans: Wrapper classes are used to transform or wrap Java primitives into reference objects. Here are some of the top features of Java wrapper classes that you should prepare while participating in Java interview for intermediate level:

  • It converts numeric strings into numeric values.
  • It is used to keep primitive data in the object.
  • All wrapper classes use the type value () method, which returns the object and primeval objects.

Q3: What is an immutable object?

Ans: An immutable object cannot be amended once formed. Hence, software developers depend on immutable objects for forming simple and reliable codes. Object immutability prevents essential files from being deleted, corrupted, and damaged. However, the files can be freely accessed, giving complete access to view the documents. It can be used in multiple cases such as aiding recovery from ransomware attacks, protecting the company during lawsuits, enhancing version control while software development, supporting record retention needs, and more.

Q4: Describe the term object cloning?

Ans: An object cloning is a process of creating an exact copy of an object. The class must implement the interface whose object clone you want to recreate. Hence, it saves the extra processing task for forming the exact copy of an object. If you execute it by using the new keyword, it will take a lot of processing time, and it is one of the reasons why developers use object cloning.

Q5: Explain different types of maps in Java.

Ans: A Java Map is an object which maps keys to values. It cannot keep duplicate keys, and each key can map only one specific value. To see whether keys are the same or different, Map uses the equals () method. Here are the four types of Maps in Java:

  • HashMap – It is an unordered and complicated map. It is an ideal choice when there is no prominence in the order. It permits one null key and several null values and does not maintain any specific order.
  • TreeMap – It is a stated map offering support for constructing a sorted order with the help of a constructor.
  • LinkedHashMap – It is comparatively slower than HashMap but has a justified insertion order.
  • HashTable – It does not allow anything null and has methods that sync together. It offers threat safety; hence, the performance is low.

Keep these four types of maps in your mind while giving your Java programming interview.

Q6: Which operator is examined with the highest precedence?

Ans: Postfix operators are considered as the highest precedence.

Q7: What is the fundamental difference between throw and throws?

Ans: A throw is used to activate an exception, whereas throws are used in the exception declaration.

These two are essential terms that you should know before giving your Java interview.

Q8: What is the JAR file?

Ans: A JAR, also known as Java Archive, keeps the Java classes in a library. This format is based on the ZIP file format used for aggregating multiple files into one.

Q9: How can you execute the singleton pattern?

Ans: One can execute a singleton pattern by the following methods:

  • A private static variable of the same class, which is the only occurrence of the class
  • Private constructor to limit instantiation of the class from different classes
  • Public static method that restores the occurrence of the class

It is one of the essential Java technical interview questions that you should note before giving your interview.

Q10: What is the one difference between the continue and break statement?

Ans: The continue statement is implemented to stop the current loop iteration while the break statement is used inside a loop. Afterwards, the loop gets discontinued and returns at the next statement.

Q11: How is the queue implemented in Java?

Ans: A queue is a linear data structure similar to the stack data structure. In simple words, it is an interface available in the Java.util package and used to store the elements that have insertion and deletion options. In the procedure, the first element is placed from the one end called REAR (Tail), and the existing element is deleted from the other end, known as FRONT (Head). The whole operation of queue implementation is called FIFO (First in First Out).

Q12: How can you avoid deadlock in Java?

Ans: One can attain this by cracking the circular wait condition. It can be done by arranging the code to impose the ordering on the acquisition and release of locks.

Q13: How can one execute to use an object as a key in HashMap?

Ans: To use any object as a key in HashMap or Hashtable, executing equals and hashcode methods in Java is necessary.

Q14: How are bytes converted to a character in Java?

Ans: It is one of the standard questions to ask in Java interview you should know.

One can convert bytes to character or text data by using character encoding. However, incorrect character encoding can change the message’s meaning as it clarifies it differently.

Q15: What is an Anonymous Class?

Ans: An Anonymous Class is explained without a name in the single code using a new keyword. It is implemented when one needs to build a class created in an instance.

You should know a common term before answering the questions in Java interview.

Q16:Difference between an object-based and an object-oriented programming?

Ans: An object-based programming language does not keep up the features of OOPs except for inheritance. Object-oriented languages are C, C++, and Java.

Sno.  Basis C C++ Java
1 Programming Pattern Procedural language Object-oriented programming Object-oriented programming
2 Dynamic or static Programming language is static Programming language is dynamic Programming language is dynamic
3 Platform Dependency Dependent Dependent Platform-independent due to byte code
4 Translator Use compiler, translate code to machine language Use compiler, translate code to machine language Use both translator and interpreter
5 Pointer Concept It supports pointer Supports pointer Does not support pointer
6 Constructor/ Destructor Does not Support Does support constructor and destructor Support constructor Only
7 Memory Use methods like calloc(), malloc(), free(), realloc() Use new and delete operator Use Garbage Collector to manage memory
8 Used in Build or developing drivers and Operating System Used in System Programming Used in Development of web & mobile and Windows applications

Q17: Most common package used for matching with regular expressions.

Ans: Java.util.regex. package

Q18: What are some of the most commonly used Java tools?

Ans: Java is one of the most popular and widely used programming languages, and its most commonly used tools are:

  • Eclipse IDE
  • JDK (Java Development Kit)
  • NetBeans

Q19: Perfect way to arrange the elements of GridBagLayout in Java programming?

Ans: In Gridbaglayout, the elements are arranged in the form of a grid. Here, the elements are present in various sizes and hold the space according to their volumes. It can cover rows and columns depending on the various sizes.

Q20: What are the major advantages of Java packages?

Ans: A Java package is a collection of classes and interfaces that are gathered together so that they are associated with each other. It offers multiple benefits such as help in organizing source code, protection against name collisions, hiding execution for multiple classes, control access, locating and usage of classes, and making interpretation easy.


Q21: What is a Java servlet?

Ans: Java developers use servlets to outstretch the capabilities of a server. It is used to extend the applications hosted by a web server and is positioned to create a dynamic web page. It runs on JVM and prevents attacks.

Q22: What is an abstract method?

Ans: It is one of the essential terms to remember before giving your Java programming interview.

It is a function that is announced without an execution. It is located in the heart of benefaction when one defines specific tasks and functions that are dealt with in the child’s classes.

Q23: What is considered the best class out of all the classes in Java?

Ans: The object class is considered the best class in Java.

Also Read: Interview Questions for Freshers

Advanced Java Interview Questions: Experienced

Java is one of the most used programming languages in the world. Here are some of the advanced Java Interview questions asked from professionals having years of experience. This section includes Java interview questions for 5 years experience candidates.

Q1: How Garbage collection prevent a Java application from going out of memory?

Ans: It does not prevent a Java application from going out of memory. Garbage collection simply cleans up the unused memory when an object goes out of scope and is no longer required. Although, an application could form many large objects that can cause OutOfMemoryError.

Q2: What is a reflection, and why is it essential?

Ans: The reflection is a term used to describe code, which can find out other code in the system to make amendments at runtime.

Here is an example; If an object of an unknown type in Java, you call it the ‘try’ method if it is there. Java’s static typing system is not designed to support this till the object conforms to a known interface. However, using reflection, your code can consider the object and inspect if it has a method called ‘try’ and call it if you say so.


Method method = foo.getClass().getMethod(“try”, null);
method.invoke(foo, null);

Q3: What is Java pass-by-reference or pass-by-value?

Ans: Every object reference in Java is passed by a value, which means that a copy of a value will be passed to a method for the procedure. Pass-by-reference is the process of passing the reference of an argument in the fundamental calling function in correlation with the formal parameter.

Whereas, pass-by-value is referred to as passing by reference only if the address of the variable is passed as an argument. However, the pass by reference is not enabled in Java.

Here is an example:

public class Demo {   
         int x=10;     
         void chg(int x){    
         x=x+100;//Changing values  It will be locally)   
         public static void main(String args[]){    
        	Demo d=new Demo();  //Creating object  
           System.out.println(" Output (before change)="+d.x);    
           d.chg(50);  //Passing value  
           System.out.println(" Output (after change)="+d.x);    


Output (before change)=10
Output (after change)=10

Q4: Why is Java called platform independent?

Ans: Java is called platform independent because of its byte codes. It can run on any system regardless of its primary operating system.

Q5: What is the difference between Vector and Array list in Java?

Ans: Here are the major differences between Vector and Array list in Java:

Array List  Vector 
It is not synchronized It is synchronized
It is slow It is slow
It does not define any increment size It defines the increment size
If any element is put into the array list, it will increase its Array size by 50% It fails to doubling size of its array
It can only use Iterator for covering an Array list It can use both Iterator and Enumeration for covering

Q6: What are Lambda Expressions?

Ans: Lambda Expressions are also called Lambdas, a new feature introduced with Java 8. It offers one of the easiest ways to work with interfaces, with only one method. It is also used in multiple places where programmers use anonymous classes.

Q7: How and when do deadlocks occur in any program?

Ans: A deadlock appears when two or more threads are blocked on locks, and every thread that’s blocked holds a lock that another lock desires.

Q8: What are JDBC Drivers?

Ans: JDBC Driver is a simple Java library that contains classes that execute the JDBC API. It is because all the JDBC drivers have to execute the same interface. However, it is not difficult to change the data sources that the application uses.    

Q9: Mention one advantage and one disadvantage of using Java Sockets?

Ans: Advantage: Java sockets are used in Java programming because it has greater flexibility and easy communication protocols. It also causes low network traffic, such as CFI scripts and HTML forms that transfer and create the complete web pages for each new data request.

Disadvantage: The communication process via Socket only permits sending packets of raw data between applications.

Q10: What is the responsibility of attributes in servlets?

Ans: An attribute is a map object which permits the Servlets to share information between one servlet to another. It can be used to set, get, and remove in request, session or application scope.

Q11: What is the difference between HashSet and TreeSet?

Ans: Here are the fundamental differences between HashSet and TreeSet:

HashSet  TreeSet 
It is executed through a hash table It executes SortedSet Interface which uses trees for storing information
It permits the null object It does not permit the null object
It is faster than TreeSet in terms of search, delete, insert, and operations It is comparatively slower than HashSet for inserting, searching, deleting, and operating
It uses equals() method to compare two objects It uses compareTo() method to compare two objects
No elements are maintained in a decided order All the elements are maintained in a sorted order

Q12: Define the term Object Oriented Programming?

Ans: Object oriented programming is also known as OOps, a programming model or a process where the programs are organized around the objects instead of logic and functions. In simpler words, it focuses on the objects needed to be controlled instead of logic. It is the perfect approach for large programs and complex codes and must be maintained actively.

Q13: What is an infinite loop in Java?

Ans: An infinite loop is an instruction sequence in Java that loops without an end when a functional exit is not met. This kind of loop can result from a programming error or may also be a deliberate action based on application behavior. Once the application exists, the infinite loop will be terminated instantly.

Q14: What is the difference between static and non-static methods in Java?

Ans: Here are the significant differences between static and non-static method in Java:

Static Method  Non-Static Method 
The static keyword should be used prior to the method name There is no requirement to use the static keyword before the method name in the program
It is known as using the class (className.methodName) It can be said as any general method
Static methods cannot access non-static instance methods or variables Non-static methods can access any static method and any static variable without creating an occurrence of the class

Q15: What is encapsulation in Java?

Ans: Encapsulation is a process where the data (variables) and code (methods) are together as a single unit. Here, the data is hidden from the outer world and can be retrieved only through class methods. It helps in protecting the data from any unnecessary changes. You can attain encapsulation in Java by:

  • Announcing the variables of a class private
  • Offering public setter and getter methods to amend and view the values of the variables.

Q16: What is the meaning of aggregation?

Ans: An aggregation is a distinguished form of association where all the objects have their lifecycle, but ownership and child objects can not be owned to another parent object.

Q17: What is a marker interface?

Ans: A marker interface is a term used to define when interfaces have no data member and member functions. In simple words, an empty interface is called a Marker interface. Some of the most common examples are Cloneable, Serializable, etc. Here is an example:

Q18: What is Hibernate architecture?

Ans: Hibernate has a stacked architecture that helps the user start without knowing the underlying APIs. It uses database and configuration to offer consistent services to the application. It includes several objects such as session factory, persistent object, session, connection factory, transaction factory, etc.

Q19: What is the OutOfMemoryError in Java?

Ans: OutOfMemoryError is a subclass of java.lang.Error that generally appears when the JVM goes out of memory.

Q20: What are the two ways to form a thread?

Ans: The two ways to create threads are:

  • By executing the Runnable interface
  • By expanding the Thread

Q21: What is the ternary operator?

Ans: Ternary operator is also known as conditional operator, which is used to decide which value to assign to a variable based on a Boolean value evaluation.

Here is the example:

public class testCondition {
public static void main ( String args[ ] ){
String state;
int position = 5;
state = ( position == 1 ) ? “Completed” : “ Work in Process “;
System.out. println(state);

Q23: What is a default switch case? Show an example.

Ans: A default case is implemented in a switch statement where there are no other switch matches. However, it is an optional case, which can be declared only once when other switch cases have been coded.

Let’s have a look at the example:

public class exampleSwitch {
int scr = 4;
public static void main(String args [ ] ) {
case 1:
System.out. println(“scr is 1 “);
case 2:
System.out. println(“scr is 2 “);
System.out. println(“Default Case “);

Q24: When is the constructor of the class invoked?

Ans: It is invoked every time an object is formed with a new keyword.

Here is the example:

Q25: How can you restrict inheritance for a class?

Ans: If you want a class not to be expanded further by any class, you can use the Final keyword with the class name. Here is the example in which the Stone class is Final, which cannot be extended anymore.

Wrapping Up!

These are some common core Java interview questions that you can prepare before giving your interview. As per the resources, these are mostly asked questions in 2022. So, if you are looking for jobs as a Java developer, you must know these basic questions and answers. We hope these detailed Java interview questions and answers will help you clear your doubts and will help you get the job!

Search Articles


Recent Blogs

  • Top 10 Best job portals in India in 2023
    Feb 6, 2023
  • Top 10 Highest Paying Jobs in Mumbai
    Jan 20, 2023
  • Top 10 Highest Paying Jobs In Bangalore
    Jan 16, 2023
  • Top 10 Highest Paying Jobs In Delhi 2023
    Jan 9, 2023
  • 6 Basic Rules for Resume Writing
    Dec 30, 2022
  • How To List Certifications on Resume (With Examples)
    Dec 28, 2022
  • What is a CV?
    Nov 28, 2022
  • What Are Interpersonal Skills? Importance & Examples
    Nov 9, 2022
  • How to Write Profile Summary for Freshers?
    Nov 7, 2022
  • How To Write a Follow Up Email
    Nov 4, 2022

Latest videos

Looking for a job?