Java Programming
Interview Questions with Answers
Explore Our Courses
1. What are the main features of Java?
Answer:
Java is a high-level, object-oriented, platform-independent programming language. Its main features include:
- Simple: Easy to learn and use, similar to C/C++ but without complexities like pointers.
- Object-Oriented: Everything is treated as an object, supporting inheritance, encapsulation, polymorphism, and abstraction.
- Platform Independent: Write Once, Run Anywhere (WORA) – Java programs run on any device with JVM.
- Robust: Strong memory management, exception handling, and type checking.
- Secure: Offers features like bytecode verification, security manager, and restricted access to system resources.
- Multithreaded: Supports concurrent execution using threads.
- Portable: Java code can be moved and executed on different systems without changes.
- Distributed: Designed for distributed computing using tools like RMI and EJB.
- High Performance: Just-In-Time (JIT) compiler improves performance.
- Dynamic: Can load classes dynamically during runtime.
Lorem Ispum
2. Explain the Java program structure.
Answer: A basic Java program structure includes:// Class definition
public class HelloWorld {
// Main method – entry point of the program
public static void main(String[] args) {
// Statement
System.out.println("Hello, World!");
}
}
Key components:
- Class Declaration: Every Java program must have at least one class.
- Main Method: public static void main(String[] args) is the starting point.
- Statements: Code inside methods (e.g., System.out.println) performs actions.
- Packages: Used to group related classes.
- Comments: Single-line (//) or multi-line (/* … */) for documentation.
3. What is the difference between JDK, JRE, and JVM?
Answer:| Component | Full Form | Description |
| JDK | Java Development Kit | A software development kit with tools to develop, compile, debug, and run Java programs. Includes JRE + development tools like javac, javadoc. |
| JRE | Java Runtime Environment | A set of tools to run Java applications. Includes JVM + runtime libraries. Doesn’t include development tools. |
| JVM | Java Virtual Machine | A virtual machine that executes Java bytecode. It’s platform-dependent but ensures platform-independent execution of code. |
4. What is bytecode in Java?
Answer: Bytecode is the intermediate code generated by the Java compiler (javac). It is:- A .class file that is platform-independent.
- Executed by the Java Virtual Machine (JVM).
- Makes Java portable, as the same bytecode can run on any platform with a compatible JVM.
5. What is the role of the main() method in Java?
Answer: The main() method is the entry point of any Java application: public static void main(String[] args)- public: Access modifier so JVM can access it from anywhere.
- static: No need to create an object to call this method.
- void: Returns nothing.
- main: Standard method name recognized by JVM.
- String[] args: Accepts command-line arguments.
6. What is the difference between == and .equals() in Java?
Answer:| Operator | Purpose | Used For | Compares |
| == | Comparison operator | Primitive types & object references | Memory location |
| .equals() | Method | Objects (Strings, custom classes) | Actual content or value |
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b); // false → compares references
System.out.println(a.equals(b)); // true → compares values
7. What is a data type? List primitive and non-primitive types in Java.
Answer: A data type defines the type of data a variable can hold. Primitive Data Types- Integer Types (byte, short, int, long)
- Floating Point (float, double)
- Character (char)
- Boolean (boolean)
- String
- Arrays
- Classes
- Interfaces
- Enums
- Collections (List, Set, Map, etc.)
8. What are variables and how are they declared in Java?
Answer: A variable is a container that holds data which can be changed during program execution. Syntax<type> <variableName> = <value>;Examples
int age = 25; String name = "Aman"; float salary; salary = 45200.75f;Types of Variables
- Local – inside methods
- Instance (non-static) – for each object
- Static – shared across all objects of the class
9. What is type casting in Java?
Answer: Type casting is the process of converting one data type into another. Two Types:- Implicit Casting (Widening): Small → Big (No data loss)
- Explicit Casting (Narrowing): Big → Small (May lose data)
10. What are wrapper classes in Java?
Answer: Wrapper classes convert primitive types into objects.
They are part of java.lang package.
Example
| Primitive | Wrapper Class |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
int a = 10; Integer obj = Integer.valueOf(a); // Boxing int b = obj.intValue(); // UnboxingThey are useful in collections (like ArrayList) which work only with objects, not primitives.
11. What are different types of operators in Java?
Answer: Java supports several types of operators used to perform operations on variables and values. Types of Operators- Arithmetic Operators ( +, -, *, /, % )
- Relational (Comparison) Operators ( ==, !=, >, <, >=, <= )
- Logical Operators ( &&, ||, ! )
- Assignment Operators ( =, +=, -=, *=, /=, %= )
- Unary Operators ( +, -, ++, –, ! )
- Bitwise Operators ( &, |, ^, ~, <<, >>, >>> )
- Ternary Operator ( ? : (conditional expression) )
- Instanceof Operator ( Checks if an object is an instance of a class )
- Shift Operators ( <<, >>, >>> (bit-level shifting) )
int a = 10, b = 5; System.out.println(a + b); // Arithmeti System.out.println(a > b); // Relational System.out.println(a == 10 && b == 5); // Logical
12. Explain operator precedence in Java.
Answer: Operator precedence determines the order in which operators are evaluated in an expression. High to Low Precedence (Left to Right)| Precedence | Operators |
| 1 | () (parentheses) |
| 2 | ++, –, + (unary), -, ! |
| 3 | *, /, % |
| 4 | +, – |
| 5 | <<, >>, >>> |
| 6 | <, <=, >, >= |
| 7 | ==, != |
| 8 | & |
| 9 | ^ |
| 10 | ` |
| 11 | && |
| 12 | ` |
| 13 | ?: (ternary) |
| 14 | =, +=, -= (assignment) |
13. What are decision-making statements in Java?
Answer: Decision-making statements allow Java programs to take different paths based on conditions. Types of Decision-Making Statements- if statement
- if-else statement
- if-else-if ladder
- switch statement
int marks = 75;
if (marks >= 33) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
14. What is the difference between if-else and switch statement?
Answer:| Feature | if-else Statement | switch Statement |
| Data Type | Works with int, char, boolean, etc. | Works with int, char, String, enum |
| Conditions | Can handle complex conditions | Only compares equality (==) |
| Use Case | For range checks or complex logic | For multiple exact-match values |
| Performance | Slightly slower for many conditions | Faster with many fixed values |
// if-else
if (choice == 1) {
// do something
} else if (choice == 2) {
// do something else
}
// switch
switch (choice) {
case 1: /* do */ break;
case 2: /* do */ break;
}
15. What is a loop? List and explain loop types in Java.
Answer: A loop is a control structure used to execute a block of code repeatedly. Types of Loops in Java- for loop: When number of iterations is known.
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
- while loop: When the condition is checked before every iteration.
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
- do-while loop: Executes the block at least once, then checks condition.
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
16. What is the difference between while and do-while loop?
Answer:| Feature | while Loop | do-while Loop |
| Condition Check | Before the loop starts | After the first iteration |
| Minimum Execution | May not execute even once | Executes at least once |
| Syntax | while (condition) {} | do { } while (condition); |
// while loop – may skip
int x = 10;
while (x < 5) {
System.out.println(x); // won't print
}
// do-while – runs once
int y = 10;
do {
System.out.println(y); // prints 10
} while (y < 5);
17. How does the for loop work in Java?
Answer: The for loop is used when the number of iterations is known beforehand. Syntaxfor (initialization; condition; update) {
// loop body
}
Example
for (int i = 1; i <= 5; i++) {
System.out.println("Hello " + i);
}
- Initialization: Runs once at the start.
- Condition: Checked before each iteration.
- Update: Executed after each iteration.
18. What is a nested loop and give an example?
Answer: A nested loop is a loop inside another loop. It is used for multidimensional data structures or patterns. Example: Printing a 3×3 matrixfor (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(j + " ");
}
System.out.println(); // move to next line
}
Output
1 2 3 1 2 3 1 2 3
19. What is the use of break and continue statements?
Answer:- break: Exits the loop or switch block immediately.
- continue: Skips the current iteration and moves to the next one.
for (int i = 1; i <= 5; i++) {
if (i == 3) break; // loop exits when i == 3
System.out.println(i);
}
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // skips i == 3
System.out.println(i);
}
20. Can we use a return statement inside a loop? What happens?
Answer: Yes, we can use a return statement inside a loop.- It immediately exits from the current method, not just the loop.
- Any remaining code (in the loop or method) is skipped.
public static void checkEven(int[] arr) {
for (int num : arr) {
if (num % 2 == 0) {
System.out.println("Even found: " + num);
return; // exits the method
}
}
System.out.println("No even number");
} Lorem Ispum
21. What is a method in Java?
Answer: A method in Java is a block of code that performs a specific task. It allows code reuse, improves readability, and supports modular programming.- Methods are defined inside classes.
- They can take parameters and may return a value.
public void greet() {
System.out.println("Hello, Java!");
}
22. How do you define and call a method in Java?
Answer: Defining a method:return_type method_name(parameter_list) {
// method body
}
Example
public int add(int a, int b) {
return a + b;
}
Calling a method:
int result = add(5, 3);
System.out.println("Sum = " + result);
- If it’s a non-static method, use an object to call it.
- If it’s a static method, you can call it directly from the class.
23. What is method overloading?
Answer: Method overloading means defining multiple methods in the same class with the same name but different parameters (type, number, or order). It is a form of compile-time polymorphism. Examplepublic void show(String name) {
System.out.println("Name: " + name);
}
public void show(int age) {
System.out.println("Age: " + age);
}
24. What is the difference between method overloading and overriding?
Answer:| Feature | Method Overloading | Method Overriding |
| Definition | Same method name, different parameters | Same method name, parameters, and return type |
| Class | Happens in the same class | Happens in child (subclass) |
| Polymorphism | Compile-time polymorphism | Runtime polymorphism |
| Annotation | Not required | Uses @Override annotation |
class Parent {
void display() {
System.out.println("Parent");
}
}
class Child extends Parent {
@Override
void display() {
System.out.println("Child");
}
}
25. What is the use of return statement in a method?
Answer: The **return** statement is used to:- Exit from the method.
- Send back a value to the calling method (if the method is not void).
public int square(int x) {
return x * x;
}
If a method returns nothing, use return; or omit it in void methods.
26. What are method parameters and arguments?
Answer:| Term | Meaning |
| Parameter | Variable defined in method declaration (placeholder) |
| Argument | Actual value passed to the method when calling it |
// Parameter
public void greet(String name) {
System.out.println("Hello, " + name);
}
// Argument
greet("Aman");
27. What is the difference between call by value and call by reference in Java?
Answer:
Java uses call by value only, even for objects.
Example
| Feature | Call by Value (used in Java) | Call by Reference (not used in Java) |
| What is passed? | A copy of the variable | Actual reference or address |
| Effect on original | Changes don’t affect the original variable | Changes reflect in original variable |
void modify(int a) {
a = a + 5;
}
Even after calling modify(x), the original x remains unchanged.
For objects, the reference copy is passed, so object fields can be changed, but the reference itself can’t be reassigned.
28. What are default, static, and final methods?
Answer: Default Method:- Introduced in Java 8, used inside interfaces.
- Can have a method body in an interface.
interface A {
default void show() {
System.out.println("Default method");
}
}
Static Method:
- Belongs to the class, not the object.
- Can be called using the class name.
class Test {
static void display() {
System.out.println("Static method");
}
}
Test.display();
Final Method
- Cannot be overridden in subclasses.
class A {
final void show() {
System.out.println("Final method");
}
}
29. Can main() method be overloaded?
Answer: Yes, the main() method can be overloaded with different parameter lists. Only the standard version is used by JVM as the entry point:public static void main(String[] args)But you can create additional main() methods:
public static void main(String arg) {
System.out.println("Overloaded main: " + arg);
}
You must call the overloaded version manually.
30. Can a method return multiple values in Java?
Answer: No, a method in Java cannot return multiple primitive values directly. But we can simulate returning multiple values using:- Array
public int[] getCoordinates() {
return new int[]{10, 20};
}
2. Object (Best Practice)
class Result {
int total;
double average;
}
public Result calculate(int[] marks) {
Result r = new Result();
r.total = …;
r.average = …;
return r;
}
3. Collections
public Map<String, Object> getData() {
Map<String, Object> map = new HashMap<>();
map.put("name", "Aman");
map.put("marks", 90);
return map;
}
31. What is Object-Oriented Programming (OOP)?
Answer: Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data (fields) and methods (functions). Key Principles of OOP:- Encapsulation – Wrapping data and methods into a single unit (class).
- Inheritance – Acquiring properties from another class.
- Polymorphism – One interface, many implementations.
- Abstraction – Hiding internal details and showing only necessary features.
32. What is a class and object in Java?
Answer: Class: A class is a blueprint/template for creating objects. It defines the data members and methods.class Student {
String name;
int age;
void display() {
System.out.println(name + " is " + age + " years old.");
}
}
Object: An object is an instance of a class. It represents a real-world entity.
Student s1 = new Student(); // s1 is an object s1.name = "Aman"; s1.age = 21; s1.display();
33. What is encapsulation in Java?
Answer: Encapsulation is the process of binding data (variables) and code (methods) together in a single unit (class), and restricting access using access modifiers like private, public, etc. Benefits:- Data hiding
- Increased security
- Easier maintainability
class Employee {
private int salary;
public void setSalary(int s) {
salary = s;
}
public int getSalary() {
return salary;
}
}
34. What is inheritance? Types of inheritance supported in Java?
Answer: Inheritance allows a class (child) to acquire properties and behaviors from another class (parent). Syntaxclass Parent {
void show() { }
}
class Child extends Parent {
void display() { }
}
Types of Inheritance in Java:
- Single – One subclass inherits one superclass.
- Multilevel – A class inherits from a class that itself inherits another class.
- Hierarchical – Multiple subclasses inherit a single superclass.
- Multiple inheritance using classes is not supported (to avoid ambiguity) but can be achieved using interfaces.
35. What is the difference between super and this keyword?
Answer:- this, Refers to the current class object
- super, Refers to the parent class object
class A {
int x;
A(int x) {
this.x = x; // distinguish between local and instance variable
}
}
super usage, Example
class B extends A {
B() {
super(10); // call parent constructor
}
}
36. What is constructor? What are its types?
Answer: A constructor is a special method that is automatically called when an object is created. Its name is same as the class and it has no return type. Types of Constructors- Default Constructor – No parameters.
- Parameterized Constructor – Takes arguments.
- Copy Constructor (not built-in, but can be defined manually).
37. What is constructor overloading?
Answer: Constructor overloading means having multiple constructors in the same class with different parameters. Exampleclass Book {
String title;
int price;
// Constructor 1
Book() {
title = “Unknown”;
price = 0;
}
// Constructor 2
Book(String t, int p) {
title = t;
price = p;
}
}
Java chooses the constructor based on the arguments provided.
38.What is a static block?
Answer: A static block is a block of code inside a class that is executed only once, when the class is loaded into memory. Usage:- Initialize static variables
- Load drivers/libraries
class App {
static {
System.out.println("Static block executed");
}
public static void main(String[] args) {
System.out.println("Main method");
}
}
Output
Static block executed Main method
39. What is polymorphism in Java?
Answer: Polymorphism means “many forms”. It allows objects to be treated as instances of their parent class rather than their actual class. Types:- Compile-time Polymorphism (Method Overloading)
- Runtime Polymorphism (Method Overriding)
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
Animal obj = new Dog();
obj.sound(); // Output: Dog barks
40. What is the difference between abstraction and encapsulation?
Answer:| Feature | Abstraction | Encapsulation |
| Definition | Hiding implementation details | Binding data and code into one unit |
| Goal | Focus on what an object does | Focus on how data is protected |
| Access | Achieved using abstract classes or interfaces | Achieved using access modifiers |
| Example | abstract void draw(); | private int salary; public getSalary() |
- Abstraction hides unnecessary info:
- ATM: You just press buttons (you don’t know internal code).
- Encapsulation hides data from outside:
- Salary can’t be accessed directly – only via getSalary().
Lorem Ispum
41. What are access modifiers in Java?
Answer: Access Modifiers in Java are keywords used to define the scope (visibility) of classes, variables, methods, and constructors. Types of Access Modifiers- **public** – Accessible from anywhere.
- **private** – Accessible only within the same class.
- **protected** – Accessible within the same package and in subclasses (even outside the package).
- Default (no modifier) – Accessible only within the same package.
42. What is the difference between public, private, protected, and default access?
Answer:| Modifier | Class | Same Package | Subclass (other package) | Other Packages |
| public | ✔ | ✔ | ✔ | ✔ |
| protected | ✔ | ✔ | ✔ | ✖ |
| default | ✔ | ✔ | ✖ | ✖ |
| private | ✔ | ✖ | ✖ | ✖ |
public class A {
public int x;
private int y;
protected int z;
int w; // default
}
43. What is the final keyword? Where can it be used?
Answer: The final keyword is used to restrict modification. It can be applied to:- Variable – Value cannot be changed.
final int x = 10; // cannot reassign x2.Method – Cannot be overridden.
final void show() {}
3. Class – Cannot be inherited.
final class Vehicle {}
44. What is the static keyword?
Answer: The static keyword is used to define class-level members that are shared by all instances of the class. Use cases:- Static Variable – shared by all objects.
- Static Method – can be called without creating an object.
- Static Block – executes once when class is loaded.
- Static Class – for nested classes.
class Test {
static int count = 0;
static void show() {
System.out.println("Count = " + count);
}
}
45. What is the difference between static and instance variables?
Answer:| Feature | Static Variable | Instance Variable |
| Defined Using | static keyword | Without static |
| Memory Allocation | Class-level (once per class) | Object-level (per object) |
| Shared | Yes, among all objects | No, unique to each object |
| Accessed Using | Class name or object | Only through object |
46. What is a transient variable?
Answer: A transient variable is a variable that is not serialized when the object is saved to a file or transferred over a network. Use Case: Used in classes implementing Serializable interface to exclude sensitive or temporary data. Exampleclass User implements Serializable {
String username;
transient String password; // will not be serialized
}
47. What is the volatile keyword in Java?
Answer: The volatile keyword ensures that changes to a variable are visible to all threads.- Prevents thread-local caching.
- Ensures read/write operations go directly to main memory.
volatile boolean running = true;Used in multithreading to ensure visibility and consistency of variables.
48. What is the difference between abstract class and interface?
Answer:| Feature | Abstract Class | Interface |
| Keyword | abstract | interface |
| Methods | Can have abstract and concrete methods | All methods are abstract (Java 7) Can have default/static methods (Java 8+) |
| Constructor | Can have constructor | Cannot have constructor |
| Multiple Inheritance | Not supported | Supported via multiple interfaces |
| Use Case | “Is-a” relationship | “Can-do” capability or contract |
abstract class Shape {
abstract void draw();
}
interface Printable {
void print();
}
49. What is the native keyword in Java?
Answer: The native keyword is used to declare a method that is implemented in another language like C or C++, not in Java.- Used when Java interacts with OS-level or hardware-level operations.
- Part of Java Native Interface (JNI).
public native void printData();Requires a native implementation file (.dll or .so).
50. Can we override private or static methods in Java?
Answer: No, we cannot override:- private methods – They are not inherited.
- static methods – They are class-level, not object-level.
- Static methods can be hidden, not overridden.
- Private methods are accessible only within the class.
class A {
static void show() {
System.out.println("Static in A");
}
private void test() {
System.out.println("Private in A");
}
}
class B extends A {
static void show() {
System.out.println(“Static in B”); // hides, not overrides
}
// Can’t override test() – it’s private
}
51. What is exception handling in Java?
Answer: Exception Handling in Java is a mechanism to handle runtime errors so the normal flow of the program is not interrupted. Purpose:- Avoid program crashes
- Provide alternate logic when errors occur
- Maintain code robustness
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
52. What is the difference between checked and unchecked exceptions?
Answer:| Feature | Checked Exception | Unchecked Exception |
| Checked At | Compile-time | Runtime |
| Handled Using | Must be caught or declared with throws | Optional handling |
| Examples | IOException, SQLException | NullPointerException, ArithmeticException |
// Checked
FileReader fr = new FileReader("file.txt"); // Must handle IOException
// Unchecked
int x = 10 / 0; // ArithmeticException (no need to handle)
53. What is the difference between throw and throws?
Answer:| Feature | throw | throws |
| Purpose | Used to explicitly throw an exception | Used to declare an exception |
| Location | Inside method body | In method signature |
| Followed By | Instance of Throwable (e.g., new Exception()) | Exception class name(s) |
// throw
throw new ArithmeticException("Invalid calculation");
// throws
public void readFile() throws IOException {
// file reading code
}
54. What are try, catch, finally, and try-with-resources blocks?
Answer:- try: Block where you place code that may cause an exception.
- catch: Handles the exception.
- finally: Executes always, regardless of exception (used for cleanup).
- try-with-resources: Auto-closes resources (like files) that implement AutoCloseable.
try (FileReader fr = new FileReader("data.txt")) {
// read file
} catch (IOException e) {
System.out.println("File not found");
} finally {
System.out.println("Cleanup done");
}
55. What is an array in Java? How is it declared and initialized?
Answer: An array is a container object that holds fixed-size elements of the same type. Declarationint[] nums; // or int nums[];Initialization:
nums = new int[5]; // default values: 0// or direct initialization
int[] nums = {10, 20, 30, 40};
56. How do you find the length of an array?
Answer: In Java, arrays have a built-in property called length. Exampleint[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers.length); // Output: 5
Note: This is different from length() used in Strings.
57. What is the difference between single-dimensional and multi-dimensional arrays?
Answer:| Feature | Single-Dimensional Array | Multi-Dimensional Array |
| Structure | Linear (like a list) | Matrix-like (rows and columns) |
| Declaration | int[] arr = new int[5]; | int[][] arr = new int[3][3]; |
| Usage | arr[0] | arr[1][2] |
int[] single = {1, 2, 3};
int[][] multi = {
{1, 2},
{3, 4}
};
System.out.println(multi[1][0]); // Output: 3
58. What is a thread in Java?
Answer: A thread is a lightweight unit of a process that executes independently.- Java supports multithreading, where multiple threads run concurrently.
- Every Java program has at least one thread: the main thread.
- New
- Runnable
- Running
- Blocked/Waiting
- Terminated
- Better CPU utilization
- Efficient multitasking
59. What is the difference between Thread class and Runnable interface?
Answer:| Feature | Thread Class | Runnable Interface |
| Inheritance | Extends Thread (single inheritance) | Implements Runnable (flexible) |
| Structure | Override run() in subclass | Implement run() method |
| Usage | new ThreadSubclass().start() | new Thread(new MyRunnable()).start() |
class MyThread extends Thread {
public void run() {
System.out.println("Thread using Thread class");
}
}
Runnable Example
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread using Runnable");
}
}
60. How do you read/write files using File, FileReader, and FileWriter in Java?
Answer: Reading with FileReader:import java.io.*;FileReader fr = new FileReader(“input.txt”); int ch; while ((ch = fr.read()) != -1) { System.out.print((char) ch); } fr.close(); Writing with FileWriter:
FileWriter fw = new FileWriter("output.txt");
fw.write("Hello Java File Writing");
fw.close();
Using File class:
File file = new File("input.txt");
if (file.exists()) {
System.out.println("File exists");
System.out.println("File name: " + file.getName());
}
Use BufferedReader or Scanner for efficient line-by-line reading.
Note: The interview questions and answers provided on this page have been thoughtfully compiled by our academic team. However, as the content is manually created, there may be occasional errors or omissions. If you have any questions or identify any inaccuracies, please contact us at
team@learn2earnlabs.com. We appreciate your feedback and strive for continuous improvement.
