Among the most commonly used programming languages in the world, Java holds a significant importance in developing software applications. Unlike other complex language methods like C++, Java is known for its simplicity and robust performance. Moreover, many businesses look for Java developers to design and manage their programs. Nevertheless, being prepared for Java interviews can be difficult though having knowledge of common questions can make a big difference.
This blog will discuss the top Java interview questions for different experience levels. We will begin with freshers’ questions and then go on to intermediate coding issues and finally advanced concepts for experts. This guide will help you to prepare thoroughly and boost your confidence for your next Java interview.
Java Interview Questions for Freshers
1. What is Java?
Java is a high-level class-based object-oriented programming language, specially designed to reduce the number of dependencies while program implementation. Java was developed by Sun Microsystems in 1995 and is currently owned by Oracle.
Using the Java Virtual Machine (JVM), Java applications can be easily compiled into bytecode that can run on any computer architecture. Hence, portability can be said to be one of the most important key strengths of Java.
2. What are the differences between an instance variable and a class variable?
Feature
Instance Variable
Class Variable
Declaration
Inside a class but outside any method
Inside a class, using the static keyword
Scope
Specific to an instance of the class
Shared among all instances of the class
Memory Allocation
Allocated when an instance is created
Allocated once when the class is loaded
Access
Accessed using an instance of the class
Accessed using the class name
3. Which class serves as the superclass for all classes?
Object class in Java serves as the superclass for all other classes. Unless explicitly stated otherwise, every class in Java implicitly inherits from the Object class.
4. What are constructors in Java?
Constructors are special methods in Java that are used in instantiating objects which refers to creating an instance or occurrence of anything such as a class or struct., It has no return type and must have the same name as the class itself i.e., the constructor name should be the same as its class name including case letter sensitivity. There exist two types of constructors:
Default Constructor: No argument constructor is provided by Java if there are no other constructors defined
parameterised Constructor: A method that takes arguments initialises only once with specific values and an object called a parameterised constructor.
5. Explain the different types of access specifiers.
Access Specifier
Visibility
Class
Package
Subclass
Global
private
Only within the same class
Yes
No
No
No
default
(no modifier)
Within the same package
Yes
Yes
No
protected
Within the same package and subclasses
Yes
Yes
Yes
No
public
Anywhere
Yes
Yes
Yes
Yes
6. Why Is Java a Platform-Independent Language?
Java is platform-independent due to the fact that it is compiled into bytecode, a kind of intermediate code. Java compiler transforms Java source code into JVM instructions which can then be executed directly by JVM just in time or saved as machine code before execution. Because there are many operating systems with JVMs, the same bytecode would run on any OS that has a compatible JVM. This ability to “write once and run anywhere” is one of the key features of Java.
7. What are the FileInputStream and FileOutputStream?
Feature
FileInputStream
FileOutputStream
Purpose
Reads raw byte data from a file
Writes raw byte data to a file
Usage
Suitable for reading binary data like images
Suitable for writing binary data like images
Methods
read(), read(byte[] b), close()
write(int b), write(byte[] b), close()
Constructor
FileInputStream(String name)
FileOutputStream(String name)
Example Usage
FileInputStream fis = new FileInputStream(“file.txt”);
FileOutputStream fos = new FileOutputStream(“file.txt”);
8. Explain public static void main(String args[]).
This is the method used as the entry point of any Java application, written as a whole command line and we can break down each part as:
public: This means the method is accessible from anywhere.
static: Static refers to the method which belongs to only the class, not an instance of the class, hence can be called without creating an instance of the class.
void: This means the method does not return any value.
main: This is the name of the method. It is the starting point of any Java program.
String args[]: This is an array of String objects that stores command-line arguments.
9. What is a method in Java?
Method refers to a specific block of code that performs any specific tasks, commonly used to execute code to avoid any redundancy and to make the code more modular. It can be also called an instance of that class because a method can be defined within a class. Methods can accept parameters and return values. The syntax for defining a method is:
returnType methodName(parameters) {
// method body
}
10. What is the difference between equals() and == in Java?
Feature
equals()
==
Purpose
Checks the logical equality of two objects
Checks reference equality (if two references point to the same object)
Method Type
The method from Object class can be overridden
Operator
Usage
obj1.equals(obj2)
obj1 == obj2
11. Explain Destructors in Java.
Java does not support any type of destructors, unlike the destructors in C++, because Java primarily relies on automatic garbage collection to handle memory leaks and the efficiency of the program. The memory which is no longer in use is directly collected by an automatic garbage collector and deallocated.
12. Explain the difference between this() and super() in Java.
Feature
this()
super()
Usage
Calls another constructor in the same class
Calls a constructor in the parent class
Position
It must be the first statement in a constructor
It must be the first statement in a constructor
Use Case
Used to initialise the current class’s constructor
Used to initialise the parent class’s constructor
13. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println(a + b);
}
}
Answer:
15
14. What are the different ways to create objects in Java?
There are several ways to create objects in Java:
Using the new keyword:
Example obj = new Example();
Using reflection:
Example obj = (Example) Class.forName(“Example”).newInstance();
Using clone() method:
Example obj1 = new Example(); Example obj2 = (Example) obj1.clone();
Using factory methods:
Example obj = Example.createInstance();
Using deserialization:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(“file.ser”));
Example obj = (Example) in.readObject();
15. What is the use of Static methods and static variables?
Rather than any particular instance of a class, the static methods and variables can be directly associated with the class. They can be accessed directly with the help of a class name and do not create any instance of that class.
16. Differentiate between instance and local variables.
Feature
Instance Variables
Local Variables
Declaration
Inside a class, outside any method
Inside a method, constructor, or block
Scope
Belongs to an instance of the class
Belongs to the method, constructor, or block
Default Value
Initialised to default value if not set
Must be explicitly initialised before use
Lifespan
Exists as long as the object exists
Exists only during method execution
Access Modifiers
Can use access modifiers
Cannot use access modifiers
17. What are Classes in Java?
Classes in Java define a code block using methods, attributes, variables, and different data types that work on one single unit of logic. Hence classes are considered as blueprints in Java programming language and hold information to define the behaviour of the objects.
Syntax of a class:
public class ClassName {
// fields
int number;
String name;
// methods
void display() {
System.out.println("Number: " + number + ", Name: " + name);
}
}
18. What is a static class?
Static classes do not have permission to access instance variables and methods of any outer class. Rather, static classes are nested classes which can access the static member of the outer class.
Syntax of a static class:
public class OuterClass {
static class StaticNestedClass {
void display() {
System.out.println("This is a static nested class.");
}
}
}
19. What is an object?
An object can be considered as an instance of a class, which is created from classes, representing different entities that have the behaviour patterns defined by that class. Here each object can have its own set of values for the variables and methods defined in the class.
ClassName obj = new ClassName();
20. Explain different scopes in Java.
In Java, there are four types of scopes:
Local Scope: Variables declared inside a method are in local scope.
Instance Scope: Variables declared inside a class but outside any method, without the static keyword, belong to instance scope.
Static Scope: This can be declared using the ‘static’ keyword and the variables belong to the static scope which can be shared within all instances of the class.
Block Scope: Variables declared inside a block (e.g., if, for, while) are limited to that block.
21. What Is A Collection Module In Java?
One of the important parts of java.util package is the collection module which can provide many different classes and interfaces for manipulation of objects, ArrayList, HashSet, HashMap, LinkedList, etc.
22. What is the difference between Array and ArrayList in Java?
Feature
Array
ArrayList
Size
Fixed-size
Dynamic size (can grow and shrink)
Type
Can hold primitive types and objects
Can hold only objects
Performance
Faster due to fixed size
Slower due to dynamic resizing
Methods
Does not provide built-in methods for manipulation
Provides methods like add(), remove(), get()
Syntax
int[] arr = new int[10];
ArrayList<Integer> list = new ArrayList<>();
23. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[2]);
}
}
Answer:
3
24. What are the key features of the Java Programming language?
Simple: Easy to learn and use.
Object-Oriented: Supports OOP concepts like inheritance, encapsulation, and polymorphism.
Platform-Independent: Write once, and run anywhere due to the JVM.
Secure: Provides a secure environment through bytecode verification and the absence of pointers.
Robustness: Strong memory management, exception handling, and type checking.
Multithreaded: Supports concurrent execution of multiple threads.
High Performance: Just-In-Time (JIT) compiler improves performance.
25. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
String name = "World";
System.out.println(greeting + ", " + name + "!");
}
}
Answer:
Hello, World!
26. Explain JVM, JRE and JDK.
JVM(Java Virtual Machine): The abstract machine that enables Python applications to run on any device or operating system; this reads and interprets Python bytecode instructions
JRE (Java Runtime Environment): JRE can provide many different libraries by executing Python programs, but the compilers and debuggers do not exist as they only support Python interpreters.
JDK (Java Development Kit): JDK is the complete kit for software development that includes JRE, a loader/interpreter (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) and many other different tools.
27. Differences between HashMap and HashTable in Java
Feature
HashMap
HashTable
Synchronisation
Not synchronised (thread-unsafe)
Synchronized (thread-safe)
Null keys/values
Allows one null key and multiple null values
Does not allow null keys or values
Performance
Faster due to lack of synchronisation
Slower due to synchronisation
Iteration
Uses fail-fast iterator
Uses fail-safe iterator
Legacy
Part of Java Collections Framework
Legacy class, part of earlier versions
28. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is not greater than 5");
}
}
}
Answer:
x is greater than 5
29. What are the applications of Java?
Web Applications: Java is used to create web applications with frameworks like Spring and Struts.
Enterprise Applications: Large-scale enterprise applications often use Java for its robustness and scalability.
Mobile Applications: Android apps are primarily developed using Java.
Desktop GUI Applications: Java provides GUI development through frameworks like Swing and JavaFX.
Embedded Systems: Java is used in embedded systems because of its portability and efficiency.
Big Data Technologies: Tools like Hadoop and Apache Spark use Java.
30. What is Memory storage available with JVM?
The JVM divides memory into several distinct areas for efficient management:
Heap: Used for dynamic memory allocation for Java objects and JRE classes. It is shared among all threads.
Stack: Stores method frames, local variables, and partial results. Each thread has its own stack.
Method Area: Stores class structures, such as metadata, the constant pool, and method data.
Program Counter (PC) Register: Contains the address of the JVM instruction currently being executed.
31. What are the different data types supported in Java?
Type
Data Type
Size (bits)
Default Value
Primitive
byte
8
0
short
16
0
int
32
0
long
64
0L
float
32
0.0f
double
64
0.0d
char
16
‘u0000’
boolean
1
false
Non-primitive
String, Arrays, Classes, Interfaces
–
null
32. When to use byte data type?
Byte data is generally used to save memory in data types like large arrays. Also, this can help when you work with different streams of data from a network or I/O file. A byte data represents 8-bit signed integers, ranging from -128 to 127.
33. What is a Class Variable?
A class variable is declared outside any method or constructor and also declared as a static variable using a static keyword. The class variable is shared among all the instances of that class, making it only one copy of the static variable per class. Example:
public class Example {
static int classVariable = 10;
}
34. What is the default value of Local Variables?
Local variables do not have a default value. Local variables can only be explicitly initialised before they can be used.
35. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
}
}
Answer:
0
1
2
36. Can you list the differences between System.out, System.err, and System.in.
Feature
System.out
System.err
System.in
Purpose
Standard output stream
Standard error stream
Standard input stream
Usage
Used to display output to the console
Used to display error messages to the console
Used to read input from the console
Stream Type
PrintStream
PrintStream
InputStream
Buffering
Buffered
Buffered
Buffered
Typical Use
Normal program output
Error messages and diagnostics
Reading user input
37. What do you understand about an IO stream?
To perform the input and output operations in Java, the IO stream library is used because it can represent the input source or the output destination, which can be a disk file, current device or another program.
38. List down operators that are supported in Java.
Java supports a wide range of operators:
Arithmetic Operators: +, -, *, /, %
Unary Operators: +, -, ++, –, !
Assignment Operators: =, +=, -=, *=, /=, %=
Relational Operators: ==, !=, >, <, >=, <=
Logical Operators: &&, ||, !
Bitwise Operators: &, |, ^, ~, <<, >>, >>>
Ternary Operator: ? :
Instanceof Operator: instanceof
39. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
System.out.println(sum);
}
}
Answer:
15
40. What is the difference between >> and >>> operators?
Feature
>> (Signed Right Shift)
>>> (Unsigned Right Shift)
Usage
Shifts bits to the right, preserving the sign bit (sign-extended)
Shifts bits to the right, zero-filling the leftmost bits (zero-filled)
Behaviour with Negative Numbers
Preserves the sign bit (negative numbers remain negative)
Does not preserve the sign bit (negative numbers become positive)
Example
-8 >> 2 results in -2
-8 >>> 2 results in 1073741822
41. What is an array in Java?
Array in Java helps to store, manage, rearrange and sort data elements in a single variable as a list. You can store the same data type elements in one array which will act as a whole one variable, mainly helping in data handling and data manipulating. We do not have to assign each element as a new variable, as it would be a very unprofessional method of pruning errors.
A sequence of characters put together can be represented whole as a string. In Java, the strings are immutable, hence once a String object is created, its value cannot be changed again.
Example:
String message = “Hello, World!”;
43. What are the different ways to add comments in Java?
Java supports two types of comments:
Single-line Comments: Used by inserting // at the beginning of the comment.
Multi-line Comments: Enclose the code block with /* and */ to make it a comment.
44. How do you copy an array in Java?
There are several ways to copy an array in Java:
Using a Loop:
Using System.arraycopy():
Using Arrays.copyOf():
Using clone() Method:
45. Why Is Java Not a Purely Object-Oriented Language?
Hare, Java cannot be called a purely object-oriented language because it supports primitive data types such as int, char, and byte which cannot be called class objects. Everything must be treated as an object in any purely object-oriented learning language.
46. Explain how different types of constructors are used in Java.
Constructors are special methods used to initialise objects. There are two main types of constructors in Java:
Constructor Type
Description
Syntax Example
Default Constructor
No arguments are provided by the compiler if no other constructors are defined.
public Example() {}
parameterised Constructor
Takes arguments to initialise fields with specific values.
public Example(int value) { this.value = value; }
47. What is the use of a default constructor?
If no other constructors are created by us, a default constructor is created by the compiler automatically in Java, which helps to provide a default initialisation to an object. Default constructors do not require any parameters and automatically set the fields to their default values.
48. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String str = "Java";
System.out.println(str.length());
}
}
Answer:
4
49. What is the difference between Array and Collection in Java?
Feature
Array
Collection
Type
Fixed-size holds elements of a single type
It can be dynamically resized and can hold different types
Data Structures
Only linear data structures
Includes List, Set, Queue, Map
Methods
Limited methods for manipulation
Rich API for manipulation (add, remove, iterate)
Syntax
int[] arr = new int[10];
Collection<Integer> collection = new ArrayList<>();
50. What is a super keyword in Java?
The super keyword in Java is used to refer to the immediate parent class object. It is commonly used to:
Call the superclass constructor.
Access superclass methods.
Access superclass fields.
51. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String str = "Hello";
char ch = str.charAt(1);
System.out.println(ch);
}
}
Answer:
e
52. What makes a HashSet different from a TreeSet?
Feature
HashSet
TreeSet
Order
Does not guarantee any order of elements
Maintains elements in ascending order
Performance
Offers constant time performance for basic operations like add, remove, and contains
Offers log(n) time performance for basic operations
Null Elements
Allows one null element
Does not allow null elements
Backed By
Backed by a HashMap
Backed by a TreeMap
Usage
Use it when you don’t need a sorted order
Use when you need elements in sorted order
53. Define a Java program to reverse a string.
Program:
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = reverseString(original);
System.out.println("Reversed: " + reversed);
}
public static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
}
54. What is the final keyword in Java?
The final keyword in Java is used to restrict the modification of variables, methods, and classes. It can be applied in three contexts:
Final Variables: Prevents reassignment. Once a final variable is assigned, it cannot be changed.
Final Methods: Prevents method overriding. A final method cannot be overridden by subclasses.
Final Classes: Prevents inheritance. A final class cannot be subclassed.
55. Explain the difference between break and continue statements.
Feature
break
continue
Usage
Exits the loop or switch statement immediately
Skips the current iteration and proceeds to the next iteration
Control Flow
Transfers control outside the loop
Transfers control to the beginning of the loop
Use Case
Use to terminate a loop or switch statement early
Use to skip certain iterations within a loop
56. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int a = 5;
int b = 2;
System.out.println(a / b);
}
}
Answer:
2
57. Explain the difference between static and non-static methods in Java.
Feature
Static Methods
Non-static Methods
Access
It can be called without creating an instance
Requires an instance of the class to be called
Usage
Used for operations that don’t require data from an instance
Used for operations that work on the instance data
Memory Allocation
Allocated memory only once when the class is loaded
Allocated memory every time an instance is created
Access to Members
Can access static variables and other static methods directly
Can access all variables and methods (including static)
58. What are the advantages of Packages in Java?
Packages in Java provide several advantages:
Namespace Management: Packages help avoid name conflicts by grouping related classes and interfaces into namespaces.
Access Control: Packages allow you to define classes and methods with package-level access, which is not accessible outside the package.
Reusability: By organising classes into packages, it becomes easier to reuse code.
Maintenance: The packages help manage and maintain different large codebases by grouping them into their related functionality altogether.
Modularity: By encapsulating related classes and interfaces modularity can be achieved by Packages, which helps to make the code more manageable and scalable.
59. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
double a = 5.0;
double b = 2.0;
System.out.println(a / b);
}
}
Answer:
2.5
60. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String text = "Java Programming";
System.out.println(text.substring(5, 16));
}
}
Answer:
Programming
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Java Interview Coding Questions For Intermediate
61. What are the differences between C++ and Java?
Feature
C++
Java
Platform Dependency
Platform-dependent (compiled to machine code)
Platform-independent (compiled to bytecode)
Memory Management
Manual (using pointers)
Automatic (using garbage collection)
Multiple Inheritance
Supported (using classes)
Not supported (achieved using interfaces)
Operator Overloading
Supported
Not supported
Pointers
Supported
Not supported
Global Variables
Supported
Not supported
Templates/Generics
Templates
Generics
62. What is a ClassLoader?
A ClassLoader in Java is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. It is a subsystem used to load class files. Java provides three built-in class loaders:
Bootstrap ClassLoader
Extension ClassLoader
System/Application ClassLoade
63. What are the differences between Heap and Stack Memory in Java?
Feature
Heap Memory
Stack Memory
Storage
Stores objects and instance variables
Stores method frames and local variables
Memory Management
Managed by the Garbage Collector
Managed by the Java Virtual Machine (JVM)
Lifespan
Exists as long as the application runs
Exists only for the duration of a method call
Memory Allocation
Dynamic (size can grow or shrink)
Static (fixed size)
Access Speed
Slower access
Faster access
64. What are the Memory Allocations available in Java?
Java has several types of memory allocations:
Stack
Heap
Program Counter (PC) Register
Native Method Stack
65. Differentiate the constructors and Destructors.
Feature
Constructors
Destructors
Purpose
Initialise new objects
Clean up resources before an object is destroyed (not present in Java)
Invocation
Called automatically when an object is created
Called when an object is destroyed (not applicable in Java)
Parameters
Can have parameters (parameterised Constructors)
N/A (Java uses finalize() for cleanup, but it is not recommended)
Overloading
Can be overloaded (multiple constructors)
N/A
Example Language
Java, C++
C++ (Java does not have destructors)
66. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
}
}
Answer:
true
false
true
67. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 0;
try {
int z = x / y;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("This is the finally block");
}
}
}
Answer:
Cannot divide by zero
This is the finally block
68. What will be the output of the following code?
Program:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
for (int i = 0; i < list.size(); i++) {
list.remove(i);
}
System.out.println(list);
}
}
Answer:
[2]
69. List differences between the Set and List interface.
Feature
Set
List
Order
Does not maintain any order
Maintains the insertion order
Duplicates
Does not allow duplicate elements
Allows duplicate elements
Access Methods
No methods to access elements by index
Allows access to elements by index
Common Implementations
HashSet, TreeSet, LinkedHashSet
ArrayList, LinkedList
Usage
Ideal for unique elements
Ideal for an ordered collection of elements
70. Can you explain what happens if you don’t use the static modifier with the main method?
If you do not use the static modifier with the main method, the Java Virtual Machine (JVM) will not be able to invoke it as the entry point for the program. When you are using the main method, it must be public, static, and void for the JVM to start the execution of the program. Without using the static keyword, the main method would require an instance of the class to be created before it can be called. This will hinder the purpose of having a standard entry point to start the program execution, resulting in a runtime error.
71. What will be the output of the following code?
public class Main {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Programming";
String s3 = s1.concat(s2);
System.out.println(s3);
}
}
Answer:
JavaProgramming
72. Can we overload the main() method?
Yes, we can overload the main() method in Java. However, as the entry point of the program will be the public static void main(String[] args), the JVM will only call this main method with this exact signature. Any other overloaded versions of the main can be called from within the program using any other method but it will not be called by JVM.
73. What are the differences between Python and Java?
Feature
Python
Java
Typing
Dynamically typed
Statically typed
Syntax
Easier and more concise
More verbose
Memory Management
Automatic (Garbage Collection)
Automatic (Garbage Collection)
Use Cases
Web development, scripting, data science
Enterprise applications, Android development
Inheritance
Supports multiple inheritance directly
Supports multiple inheritance via interfaces
74. What are Packages in Java?
Packages can be defined as a set of different but related classes and interfaces that can provide any access protection in Java. It can also handle namespace management, making it an overall way to manage large codebases and their internal conflicting names.
75. How many types of packages are available in Java?
Built-in Packages: They are provided by the Java API, such as java.util, java.io, etc.
User-defined Packages: Created by programmers to bundle related classes and interfaces together.
76. What will be the output of the following code?
Program:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("A", 3);
System.out.println(map.size());
System.out.println(map.get("A"));
}
}
Answer:
2
3
77. What is the Wrapper class in Java?
The Wrapper class in Java provides a way to use primitive data types (int, char, etc.) as objects. Each primitive type has a corresponding wrapper class:
int -> Integer
char -> Character
boolean -> Boolean
Wrapper classes are used in collections, where only objects are allowed, and to utilise utility methods provided by these classes.
78. How many ways can you take input from the console?
There are several ways to take input from the console in Java:
Using Scanner class
Using BufferedReader and InputStreamReader
Using Console class
79. How are print, println, and printf different from each other?
81. Explain the differences between the constructors and methods.
Feature
Constructors
Methods
Purpose
Initialise new objects
Define the behaviour and operations of objects
Name
Same as the class name
Can have any name
Return Type
No return type
Must have a return type (void or other)
Invocation
Called automatically when an object is created
Called explicitly using the object
Overloading
Can be overloaded
Can be overloaded
82. What is an Interface?
An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. They are used to specify a set of methods that one or more classes must implement, promoting a form of multiple inheritance and providing a way to achieve abstraction.
Example:
public interface Animal {
void eat();
void sleep();
}
83. What is encapsulation in Java?
Wrapping the data or variables and the code that is acting upon the data methods together to form a single unit is called encapsulation in Java. The main advantage of encapsulation is to protect the data from any unauthorised access.
So that no one can modify the data without permission, which is a very important part of the project, it can be achieved through declaring variables as private using private keywords and also providing public getter and setter methods to access and update the values of those variables.
84. What do you mean by aggregation?
This can be understood as a form of association where there is a class reference to any other class, but both classes can exist without depending on each other. It represents a “has-a” relationship. For example, a Library has Books, but Books can exist independently of the Library.
85. Explain the differences between StringBuffer and StringBuilder.
Feature
StringBuffer
StringBuilder
Synchronisation
Synchronized (thread-safe)
Not synchronised (not thread-safe)
Performance
Slower due to synchronisation overhead
Faster due to lack of synchronisation
Use Case
Used in multi-threaded environments
Used in single-threaded environments
Availability
Available since JDK 1.0
Available since JDK 1.5
86. Explain the ‘IS-A‘ relationship in OOPs Java.
The ‘IS-A’ relationship in Java refers to inheritance or implementation. It signifies that a subclass is a type of the superclass. This relationship is implemented using the extends keyword for class inheritance or the implements keyword for interface implementation. For example, if Dog extends Animal, Dog IS-A Animal.
87. Does Java support multiple inheritance?
No, Java does not support multiple inheritance with classes to avoid complexity and simplify the design. However, for the betterment of multiple inheritance, Java allows a class to implement multiple interfaces.
88. How is inheritance in C++ different from Java?
Feature
C++
Java
Multiple Inheritance
Supports multiple inheritance with classes
Does not support multiple inheritance with classes, only with interfaces
Access Specifiers
Supports public, protected, and private inheritance
Only public and protected inheritance
Virtual Keyword
Requires virtual keyword for virtual inheritance
Not applicable (uses interfaces for multiple inheritance)
89. Explain method overriding in Java with examples.
Method overriding refers to the situation where a subclass provides a specific implementation for a method which is already defined in its superclass. In method overloading, the method in the subclass must have the same return type, name and parameters as of the method in its superclass.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
90. Explain method overloading in Java with examples.
Method overloading in Java allows a class to have more than one method with the same name, but different parameters (different type or number of parameters). It is a compile-time polymorphism.
Example:
class MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
91. What is the difference between ArrayList and LinkedList?
Feature
ArrayList
LinkedList
Data Structure
Dynamic array
Doubly linked list
Access Time
Faster access time (O(1) for get)
Slower access time (O(n) for get)
Insertion/Deletion
Slower for insertion and deletion (O(n))
Faster for insertion and deletion (O(1))
Memory Usage
Less memory overhead
More memory overhead due to node storage
Iteration Performance
Faster iteration
Slower iteration
Use Case
Best for read-heavy operations
Best for write-heavy operations
92. Can you override the static method in Java?
No, static methods cannot be overridden in Java. They are associated with the class, not instances of the class. If a subclass defines a static method with the same signature as a static method in the superclass, it hides the superclass method rather than overriding it.
93. Can you override the private methods in Java?
No, private methods cannot be overridden in Java. Any private method cannot be visible to subclasses. If a subclass defines a method with the same name and parameters as a private method in the superclass, it will be treated as a new method in the subclass, and not considered an override.
94. Can you explain the difference between int array[] and int[] array?
Feature
int array[]
int[] array
Syntax
An older style, often seen in C/C++
The preferred and modern style in Java
Readability
Less readable, especially for complex types
More readable and clearer intent
95. What is the LinkedList class in Java?
The LinkedList class in Java is a part of the Java Collections Framework. It implements the List and Deque interfaces, providing a doubly-linked list data structure. Elements in a LinkedList are not stored in contiguous memory locations; instead, each element is a node that contains a reference to the next and previous node. This allows for efficient insertions and deletions at both ends of the list.
Example:
LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.add("C");
System.out.println(list); // Output: [A, B, C]
96. What is an Iterator?
Iterator in Java helps to iterate over a collection of objects like sets, lists, maps, etc. The iterator allows the traversal of the collection and removal of elements during iteration. The key methods in the Iterator interface are hasNext(), next(), and remove().
97. What is the difference between a Collection and a Collections?
Feature
Collection
Collections
Definition
Interface in the Java Collections Framework
Utility class in the Java Collections Framework
Purpose
Provides standard methods to manipulate a group of objects
Provides static methods to operate on or return collections
Exceptions in Java are handled using a combination of try, catch, finally, and throw keywords:
try: Block of code that might throw an exception.
catch: Block of code that handles the exception.
finally: a Block of code that executes regardless of whether an exception was thrown or not.
throw: Used to explicitly throw an exception.
99. What is the final block in Java?
Important operations such as cleanup operations, and cleaning resources like files, databases, etc. can be done using the final block, whether an exception is thrown or not.
100. Explain the difference between Iterator and Enumeration.
Feature
Iterator
Enumeration
Interface
Part of the java.util package
Part of java.util package
Methods
hasNext(), next(), remove()
hasMoreElements(), nextElement()
Removal of Elements
Can remove elements during iteration
Cannot remove elements
Fail-fast
Yes
No
Use Case
Preferred for modern collections
Legacy interface, mainly for older classes like Vector and Hashtable
101. What is Java String Pool?
A special area in Java heap memory where String literals are stored is the Java String Pool. When a String is created using double quotes, the JVM checks the String Pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If not, a new string object is created and placed in the pool.
102. Why are Java Strings immutable in nature?
Java Strings are immutable for several reasons:
Security: Prevents the string value from being changed, ensuring safe and secure usage in key classes like String, Integer, etc.
Performance: Allows the JVM to cache strings, saving memory and improving performance.
Thread Safety: Those strings which are immutable are inherently thread-safe, avoiding any synchronisation issues.
103. What are the different types of inheritance in Java?
There are four types of inheritance in Java:
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
104. How many types of exceptions can occur in a Java program?
There are two main types of exceptions in Java:
Checked Exceptions: Exceptions which are checked during the compile-time and either caught or declared in the method signature. Examples: IOException, SQLException.
Unchecked Exceptions: Exceptions that are checked at runtime. They do not need to be declared or caught. Examples: ArrayIndexOutOfBoundsException, NullPointerException.
105. Explain the difference between Comparable and Comparator.
Feature
Comparable
Comparator
Interface
Part of java.lang
Part of java.util
Method
compareTo(Object o)
compare(Object o1, Object o2)
Implementation
Must be implemented by the class to be sorted
Can be implemented in separate classes
Sorting Logic
Defines natural ordering
Defines custom ordering
Use Case
A single way of sorting
Multiple ways of sorting
106. Explain the use of the volatile keyword in Java.
To mark any variable as “stored in main memory”, a volatile keyword is used. Hence every read and write operation on a volatile variable will be directly performed within the main memory and also ensure the visibility of changes across threads.
107. What is a lambda expression in Java?
A lambda expression allows for the functional interfaces implementation i.e. those interfaces with a single abstract method in a concise way. The lambda expression is a part of Java 8 and next updates, helps primarily in representing a single-method interface.
108. Explain the difference between final, final, and finalize in Java.
final: Constants can be declared using the final keyword, which does not allow method overriding and inheritance.
finally: Finally is used in exception handling with the help of try and catch blocks, used just after that and to execute complete code, regardless of whether an exception occurs or not.
finalize(): It is used by the garbage collector to perform memory cleanup before an object is destroyed.
109. What is the difference between ArrayList and Vector in Java?
Feature
ArrayList
Vector
Synchronisation
Not synchronised (not thread-safe)
Synchronized (thread-safe)
Performance
Faster due to no synchronisation overhead
Slower due to synchronisation overhead
Growth Rate
Increases its size by 50% if it runs out of space
Doubles its size when it needs more space
Legacy
Part of the Java Collections Framework
Considered a legacy class
110. Explain the concept of autoboxing and unboxing in Java.
Autoboxing is the process of automatic conversion of primitive data types to their corresponding wrapper class. For example, changing int to Integer. Unboxing is the reverse process, converting wrapper class objects to their corresponding primitive types.
111. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int num = 5;
switch (num) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Other");
}
}
}
Answer:
Other
Java Interview Questions for Experienced
112. Why are pointers not used in Java?
Pointers are not used in Java to maintain simplicity and security. One of the primary reasons for this is that most of the time, pointers can lead to complex code which is difficult for error handling. Situations like memory leaks and pointer arithmetic errors can occur due to pointers. Hence by eliminating pointers, Java provides a safer programming environment.
113. What will be the output of the following code?
Program:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.replaceAll(e -> e * 2);
System.out.println(list);
}
}
Answer:
[2, 4, 6]
114. What is Synchronisation?
This is the mechanism which has shared control access according to resources to better manage the permission. It allows only one thread to access a synchronised block of code or any synchronised method block while executing a program, providing mutual exclusion.
115. What is multithreading in Java?
Multi-threading in Java is a feature that allows concurrent execution of two or more threads for maximum utilisation of the CPU. Each thread runs parallel to others, enabling multiple tasks to be performed simultaneously within a single program. Multi-threading is commonly used in applications where tasks are independent and can run simultaneously, such as web servers, GUI applications, and real-time systems.
116. What are the pros and cons of synchronisation?
Feature
Pros
Cons
Thread Safety
Ensures data consistency and prevents corruption
This can lead to contention, reducing performance
Predictability
Provides controlled access to shared resources
Increases complexity in code
Consistency
Guarantees that critical sections are executed in a controlled manner
It can cause deadlocks if not handled properly
Simplified Access
Simplifies reasoning about concurrent code
Can reduce scalability in highly concurrent systems
117. What will be the output of the following code?
Program:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
Arrays.parallelPrefix(array, Integer::sum);
System.out.println(Arrays.toString(array));
}
}
Answer:
[1, 3, 6, 10, 15]
118. What is the covariant return type?
The covariant return type allows a method in a subclass to override a method in its superclass and return a type that is a subclass of the return type declared in the superclass method. This enhances flexibility and reusability in method overriding.
Example:
class Animal {
Animal get() {
return this;
}
}
class Dog extends Animal {
@Override
Dog get() {
return this;
}
}
119. What is the transient keyword?
To showcase if the field should not be serialised, the transient keyword is used. When any object is serialised, transient fields are skipped and then they will not be a part of the object’s persistent state. This is useful for fields that contain sensitive information or are not needed after deserialization.
Example:
class User implements Serializable {
private String username;
private transient String password; // This field will not be serialised
}
120. What are the differences between the methods of sleep() and wait()?
Feature
sleep()
wait()
Class
Thread class
Object class
Purpose
Pauses the current thread for a specified time
Causes the current thread to wait until another thread invokes notify() or notifyAll()
Synchronisation
Do not release the lock
Releases the lock on the object
Usage
Thread.sleep(milliseconds)
object.wait()
Exception
Throws InterruptedException
Throws InterruptedException
121. What is an association?
Association in Java is a relationship between two classes that enables one class to use functionalities provided by another class. It represents a “uses-a” relationship. Association can be one-to-one, one-to-many, many-to-one, or many-to-many. It describes how objects of different classes interact with each other.
122. What will be the output of the following code?
Program:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("abc", "bcd", "cde");
List<String> result = list.stream()
.filter(s -> s.startsWith("b"))
.collect(Collectors.toList());
System.out.println(result);
}
}
Answer:
[bcd]
123. What is Polymorphism, and how can we achieve it?
Polymorphism refers to the ability of object-oriented programming to represent any object in many forms. It allows one interface to be used for a general class of actions and its types are:
Compile-time Polymorphism (Method Overloading): This can be achieved by defining multiple methods using different parameters but with the same name within the same class.
Runtime Polymorphism (Method Overriding): This refers to defining a method that has the same name and signature in the subclass just as the method in its superclass.
124. Explain the difference between Composition and Aggregation.
Feature
Composition
Aggregation
Relationship Type
Strong ownership and lifecycle dependency
Weak ownership and an independent life cycle
Lifespan
The contained object’s lifespan depends on the container object
Contained objects can exist independently
Example
A Car has an Engine (composition)
A Library has Books (aggregation)
Implementation
Contained object created within the container
Contained object passed to the container
Use Case
Use when contained objects should not exist independently
Use when contained objects can exist independently
125. What are the different interfaces of the Collection framework?
The main interfaces of the Java Collection framework are:
Collection: The root interface for most of the collection classes.
List: Ordered collection (also known as a sequence) that allows positional access and insertion.
Set: Collection that cannot contain duplicate elements.
Queue: Collection used to hold multiple elements prior to processing.
Deque: Double-ended queue that allows insertion and removal at both ends.
Map: This maps keys to values without allowing any duplicate keys.
126. What will be the output of the following code?
Program:
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Stream.of("apple", "banana", "cherry")
.filter(s -> s.contains("a"))
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Answer:
APPLE
BANANA
127. What is a Vector in Java?
A vector can be a dynamic array that does not have any fixed size, i.e. it can grow or shrink in size according to the data input. Vectors are generally synchronised and thread-safe, hence they can be applied safely in multi-threaded environments. However one of the drawbacks of this is slow performance speed because of synchronisation.
Features of Vector:
Automatically resizes itself when elements are added or removed.
Allows duplicate elements.
Maintains insertion order.
Provides methods to add, remove, and access elements.
128. How to make Java ArrayList Read-Only?
Here you should use the Collections.unmodifiableList to make a Java ArrayList read-only. This method helps prevent any unnecessary modifications by returning an unmodified view of the specified list.
Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
List<String> readOnlyList = Collections.unmodifiableList(list);
System.out.println(readOnlyList); // Output: [A, B, C]
// The following line will throw UnsupportedOperationException
// readOnlyList.add("D");
}
}
129. What is a priority queue in Java?
This is a type of queue where you can put each element with a certain order or criteria, natural ordering or also by a comparator ordering at the time of queue construction. In the queue, the last element will be the head according to the specified ordering and elements are dequeued in the same order.
Features of PriorityQueue:
Does not permit null elements.
Unbounded, but has an initial capacity.
Not thread-safe (use PriorityBlockingQueue for thread safety).
Elements are ordered either according to their natural ordering or by a comparator.
130. What is the difference between Iterator and ListIterator?
The Stack class in Java represents a last-in, first-out (LIFO) stack of objects. It extends Vector and provides methods to push, pop, peek, and check if the stack is empty.
Features of Stack:
push(E item): Pushes an item onto the top of the stack.
pop(): Removes and returns the top item of the stack.
peek(): Returns the top item without removing it.
empty(): Checks if the stack is empty.
search(Object o): Returns the 1-based position of an item in the stack.
132. Explain the LinkedHashSet in Java Collections Framework.
LinkedHashSet is a subclass of HashSet that can maintain a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion order).
Features of LinkedHashSet:
Maintains insertion order.
Does not allow duplicate elements.
Provides constant-time performance for basic operations like add, remove, contains.
Uses a hash table and a linked list for storage.
133. Explain the Map interface in Java.
The Map represents a combination of key-value pair collections and each key will be a unique one. It is not a subtype of the Collection interface. Common implementations include HashMap, TreeMap, and LinkedHashMap.
Features of Map:
Keys must be unique.
Values can be duplicated.
Allows null values and a single null key (except in Hashtable).
134. What is EnumSet in Java?
EnumSet is a specialised Set implementation for use with enum types. All elements in an EnumSet must come from a single enum type specified when the set is created. EnumSet is very efficient and faster than other Set implementations because it uses bit vectors to represent the elements.
Features of EnumSet:
All elements must be of a single enum type.
Null elements are not permitted.
Provides all basic set operations.
Performance vise, It is very efficient.
135. What will be the output of the following code?
Program:
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
AtomicInteger atomicInt = new AtomicInteger(0);
atomicInt.incrementAndGet();
atomicInt.compareAndSet(1, 2);
System.out.println(atomicInt.get());
}
}
Answer: 2
136. What is a marker interface?
A marker interface in Java is an interface with no methods or fields. It is used to mark or tag a class that possesses certain properties. The most common examples of marker interfaces are Serializable, Cloneable, and Remote. The marker interface allows Java to provide additional metadata to the objects at runtime.
Example:
public class MyClass implements Serializable {
// This class is marked as Serializable
}
137. What is a copy constructor in Java?
Unlike C++, Java does not support any built-in copy constructor, but you can create your own copy constructor in Java to initialise any object using another provided object in the same class. Hence a copy constructor will reference an object of the same class and copy all its values.
Example:
public class MyClass {
int value;
// Copy constructor
public MyClass(MyClass other) {
this.value = other.value;
}
}
138. What is a JDBC Driver?
A software component which can enable any type of Java application to interact and link with a database. It converts Java calls to database-specific calls.
139. What are the differences between abstract class and interface?
Feature
Abstract Class
Interface
Methods
Can have both abstract and concrete methods
Can only have abstract methods (until Java 8, which introduced default and static methods)
Fields
Can have instance variables
Can only have constants (static final variables)
Multiple Inheritance
Does not support multiple inheritance
Supports multiple inheritance
Access Modifiers
Can have various access modifiers
Methods are public by default
Use Case
Used when classes share common behaviour
Used to define a contract for classes
140. What are the JDBC API components?
The JDBC API components include:
DriverManager: Manages a list of database drivers and establishes a connection to a database.
Connection: Represents a connection to a specific database.
Statement: Used to execute SQL queries against the database.
PreparedStatement: This helps to extend different statements to execute SQL queries with the parameters which are precompiled.
ResultSet: Represents ResultSet helps in representing the result set of a query and also allows navigation throughout the dataset.
CallableStatement: It is used to perform stored procedures in the database.
141. What is Spring Framework in Java?
It is one of the open-source frameworks which helps in developing Java applications and its comprehensive infrastructure support. It provides features like dependency injection, aspect-oriented programming, transaction management, and more and simplifies enterprise application development.
Key features of Spring Framework:
Dependency Injection (DI): It manages all the dependencies and the object creation automatically.
Aspect-Oriented Programming (AOP): Separates cross-cutting concerns from business logic.
Transaction Management: Simplifies transaction handling.
MVC Framework: Provides a framework for building web applications.
Integration: Integrates with various other frameworks and technologies.
142. What are Runtime Exceptions?
Unchecked exceptions that can occur during compilation are the runtime exceptions in Java. They are not checked at compile-time, and thus, do not require explicit handling. These exceptions usually indicate programming errors, such as logic mistakes or improper use of APIs.
143. What is the use of the ‘throw’ Keyword?
Throw keyword allows the programmer to create and explicitly throw any type of custom exceptions based on specific conditions in the code.
144. Differentiate between process and thread?
Feature
Process
Thread
Definition
Using its own memory space, this is an independent program.
Like a process, a thread is a smaller unit of a process sharing the same memory space.
Memory
Each process has its own memory space.
Threads share the memory space of the process they belong to.
Communication
Inter-process communication (IPC) is complex and slower.
Communication between threads is easier and faster.
Overhead
Higher overhead due to memory allocation and management.
Lower overhead, more lightweight.
Isolation
Processes are isolated from each other.
Threads are not isolated and can interfere with each other.
Example
Running a web server and a database server simultaneously.
Multiple threads handling client requests in a web server.
145. What are the states in the lifecycle of a Thread?
Runnable: The thread is ready to run and waiting for CPU time.
Blocked: The thread is waiting for a monitor lock to enter or re-enter a synchronised block/method.
Waiting: The thread is waiting indefinitely for another thread to perform a specific action.
Timed Waiting: During this, the thread is going to wait for a specific amount of time because of another running thread to perform a specific action.
Terminated: The thread has completed execution or has been terminated.
146. What is the use of the join() method?
For the execution of the current thread until the specified thread has finished executing, the join() method is used. Using this, we often check if one thread waits for the completion of another thread before any proceeding.
147. Explain the differences between String and StringBuffer.
Feature
String
StringBuffer
Mutability
Immutable
Mutable
Thread Safety
Not thread-safe
Thread-safe
Performance
Faster for read-only operations
Slower due to synchronisation overhead
Methods
Many methods for string manipulation
Fewer methods for string manipulation
Usage
Used for constant strings
Used for strings that require modifications
148. What is the Atomic action in Concurrency in Java?
An atomic action in Java concurrency is an operation that is performed completely independently of any other operations and cannot be interrupted or observed in an incomplete state. Atomic actions ensure that a particular set of operations execute without interference from other threads, thereby avoiding inconsistencies.
Examples of atomic operations:
Reading and writing of variables of primitive data types (except long and double without volatile keywords).
Operations on atomic classes from java.util.concurrent.atomic package like AtomicInteger, AtomicBoolean, etc.
149. Define the FutureTask class in Java.
The FutureTask class in Java is a concrete implementation of the Future interface. It represents a cancellable asynchronous computation. A FutureTask can be used to wrap a Callable or Runnable object. Hence it provides methods for starting and cancelling the computation, checking if the result is retrieved or not.
Key features of FutureTask:
Can be used to wrap Callable and Runnable objects.
Provides methods to check for completion, cancel the task, and retrieve the result.
Useful in scenarios where you need to execute a task asynchronously and retrieve the result at a later point.
150. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 10;
x = x ^ y;
y = x ^ y;
x = x ^ y;
System.out.println("x = " + x + ", y = " + y);
}
}
Answer:
x = 10, y = 5
Conclusion
In conclusion, exercising these concepts is very essential for you to prepare for a Java interview. Starting from all the basic concepts like data types, and loops and taking it further to more advanced topics such as concurrency, stream API collections, etc. are very crucial for your preparation for the Java developer role.
Hope this extensive post for providing different Java interview questions helped you prepare for your next Java interview. Keep practising and stay updated regarding new technologies and advancements in Java like new tools or frameworks, updates in Java version and focus on clean code writing which is efficient.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.