Top Java Interview Questions and Answers (For Freshers & Experienced)
Java remains one of the most widely adopted programming languages in the world. Known for its security, platform independence, and scalability, Java is the backbone of many enterprise-level applications and continues to be in high demand across the globe.
Whether you are aiming for a role as a Java Developer or J2EE Developer, mastering the frequently asked Java interview questions is essential. This guide serves as a reliable and comprehensive resource for both freshers and experienced professionals preparing for interviews in top tech companies.
✅ Why Java for Your Career?
Java is the preferred choice for enterprise applications due to:
- Strong community support
- Robust security features
- Cross-platform compatibility
- Rich ecosystem (Spring, Hibernate, JPA, etc.)
It also opens up numerous job opportunities both domestically and internationally in top companies.
🔍 What This Guide Offers
If you are preparing for a Java interview—whether as a fresher or an experienced professional—this set of carefully curated questions and answers is the perfect place to start.
- ✅ Covers Core Java, OOPs, Inheritance, Polymorphism, Exception Handling, JDBC, Multithreading, JVM/JDK/JRE, and more.
- ✅ Includes real-world questions asked in interviews at companies like Google, Amazon, Flipkart, Visa, Allianz, and more.
- ✅ Answers are crisp, accurate, and written with the intention of helping developers crack MNC and product company interviews confidently.
- ✅ All questions are based on inputs from expert Java professionals with 10+ years of experience.
💡 Whether you’re applying for a backend development role or preparing for full-stack interviews, this collection of Java interview questions and answers will serve as your go-to preparation material.
Would you like me to generate a complete intro + table of contents + PDF version with all 100 questions next?
Q1) Which of the following main method declarations will fail in compilation?
a. public static void main(String args)
b. public static void Main(String args[])
c. public void main(String args[])
d. public static main(String args[])
Answer: ✅ d
Explanation: Every method in Java must declare a return type. The method public static main(String args[]) is missing the return type (void), hence it will fail compilation.
Q2) Which of the following assignment is incorrect?
a. int a = (int) 10.0;
b. double d = 10;
c. float f = 3.4;
d. int b = (byte) 4;
Answer: ✅ c
Explanation: A float literal must be suffixed with f or explicitly casted to float: float f = 3.4f; or float f = (float) 3.4;.
Q3) What is the difference between == and equals() in Java?
Answer:
==compares object references (addresses).equals()compares object content (actual values), especially overridden in classes likeString.
Q4) What is the output of the below code?
class Test {
public static void main(String args[]) {
String a = "SEO";
String a1 = new String("SEO");
String a2 = "SEO";
System.out.println((a == a1) + "," + (a == a2));
}
}
Output: false,true
Explanation:
a1refers to a new object in the heap.aanda2refer to the same interned string in the string pool.
Q5) Why are primitive data types still used in Java?
Answer:
Primitive types are more performant than wrapper classes as they don’t involve object creation and use less memory.
Q6) What is the output of the below program?
class T {
String t;
public Test(String val) {
t = val;
}
public void print() {
System.out.println(t);
}
public static void main(String args[]) {
T s1 = new T("Test");
s1.print();
T s2 = new T();
s2.t = "Test2";
s2.print();
}
}
Answer: ✅ a (Compilation Error)
Reason: The constructor Test(String val) does not match the class name T, and no default constructor is provided.
Q7) What is the use of this keyword in Java?
Answer:this refers to the current object instance, useful for differentiating instance variables from parameters or calling other constructors.
Q8) Where can final be applied?
a. Variable
b. Method
c. Class
d. Interface
Answer: ✅ a, b, c
Explanation:
finalcannot be used on interfaces directly (interfaces are implicitly abstract).finalprevents changes to variables, method overriding, or class inheritance.
Q9) When is finalize() called?
Answer:
Just before the garbage collector destroys an object, finalize() is invoked (though it’s deprecated in Java 9+).
Q10) What is method overriding?
Answer:
Overriding occurs when a subclass provides a specific implementation of a method already defined in the superclass with the same method signature.
Q11) Which statement about the static keyword is not true?
a. A single copy of static data members exists for all instances.
b. Static methods can be called without creating an object.
c. Static methods can access only static variables.
d. Non-static methods cannot access static variables.
Answer: ✅ d
Explanation: Non-static methods can access static variables.
Q12) The super keyword can be used to access:
- Constructors
- Methods
- Data Members
Answer: ✅ All the above
Explanation: super is used to access parent class constructors, fields, and methods.
Q13) Constructors are called in which order?
a. Superclass to Subclass
b. Subclass to Superclass
Answer: ✅ a
Explanation: Java ensures superclass constructor executes first.
Q14) Can you create objects of abstract classes?
Answer: ✅ False
Explanation: Abstract classes cannot be instantiated directly.
Q15) What is true about the below code?
final class Sample {
int a;
}
a. Objects cannot be created
b. Sample class cannot be inherited
c. Methods cannot be overridden
d. Sample cannot extend another class
Answer: ✅ b
Explanation: final classes cannot be subclassed, but objects can be created and it can extend other non-final classes.
Q16) What is the output?
class Sample {
public static void main(String args[]) {
try {
int a = 5 / 0;
} catch (Exception ex) {
System.out.println("Exception is printed");
} catch (ArithmeticException ex) {
System.out.println("ArithmeticException is printed");
}
}
}
Answer: ✅ a (Compilation Error)
Explanation: ArithmeticException is a subclass of Exception and must appear before it.
Q17) The finally block executes only when an exception occurs.
Answer: ✅ False
Explanation: finally always executes, whether an exception occurs or not.
Q18) Difference between Checked and Unchecked exceptions?
Answer:
- Checked exceptions: Detected at compile time (e.g.,
IOException) - Unchecked exceptions: Detected at runtime (e.g.,
NullPointerException)
Q19) Can a subclass override a method and throw a new Checked Exception not declared in the superclass method?
Answer: ✅ False
Explanation: Overridden methods cannot declare broader checked exceptions than the superclass method.
✅ Rule:
Overridden methods in a subclass cannot throw broader (i.e., new or more general) checked exceptions than the method in the superclass.
❓ Why?
This rule ensures exception safety and backward compatibility when you use polymorphism.
If a superclass method doesn’t declare any checked exception, the subclass version cannot declare a new checked exception — because it would break existing code that only knows the superclass.
✔️ Example – Allowed Case (Same or narrower exception)
class Parent {
void readFile() throws IOException {
System.out.println("Reading file in Parent");
}
}
class Child extends Parent {
@Override
void readFile() throws FileNotFoundException { // ✅ Allowed: Subclass of IOException
System.out.println("Reading file in Child");
}
}
✅ This compiles fine, because FileNotFoundException is a subclass of IOException.
❌ Example – Illegal Case (Broader or new checked exception)
class Parent {
void process() throws IOException {
System.out.println("Processing in Parent");
}
}
class Child extends Parent {
@Override
void process() throws Exception { // ❌ Compilation error
System.out.println("Processing in Child");
}
}
❌ Exception is a broader exception than IOException, so it is not allowed.
Q20) Are synchronized methods thread-safe?
Answer: ✅ True
Explanation: Synchronized methods allow only one thread to access the method at a time.
✅ Types of synchronized usage:
- Synchronized Instance Method
public synchronized void increment() {
count++;
}
Locks on the current object (this)
- Only one thread per object can execute it at a time.
2. Synchronized Static Method
public static synchronized void log(String msg) {
System.out.println(msg);
}
- Locks on the Class object
- Only one thread for all instances can access it at a time.
3. Synchronized Block
synchronized (lockObject) {
// critical section
}
- Fine-grained control by locking only specific blocks instead of the whole method.
Q21) What does the following code do?
Thread t1 = new Thread();
t1.start();
Answer: ✅ b (Invokes run method)
Explanation: start() causes the JVM to call the thread’s run() method.
Q22) What Java concept is demonstrated?
int i = 5;
Integer i1 = i;
Answer: ✅ Autoboxing
Explanation: Autoboxing is the automatic conversion of primitive types to their wrapper classes.
Q23) What is out in System.out.println()?
Answer: ✅ a (Static member of System class)
Explanation: out is a static PrintStream object in the System class used to print output.
Q24) In which class are print() and println() defined?
Answer: ✅ PrintStream
Explanation: System.out is of type PrintStream which contains print() and println() methods.
Q25) Which type of class can operate on different types of data?
Answer: ✅ Generic class
Explanation: Generics allow classes to work with any data type using type parameters.
Q26) What is the difference between StringBuffer and StringBuilder?
Answer:
StringBufferis thread-safe because all of its methods are synchronized.StringBuilderis not thread-safe, but it is faster in single-threaded environments due to the absence of synchronization.
Q27) Which of the following does not allow duplicate values?
a. ArrayList
b. LinkedList
c. HashSet
d. Stack
Answer: c. HashSet
Explanation: HashSet implements the Set interface, which by definition does not allow duplicate elements.
Q28) Which of the following is not an interface in Java?
a. Collection
b. List
c. Set
d. Vector
Answer: d. Vector
Explanation: Vector is a concrete class, not an interface.
Q29) Which of the following data structures in Java is used to store key-value pairs?
a. List
b. Set
c. Map
d. Stack
Answer: c. Map
Q30) Which of the following is sorted by default?
a. ArrayList
b. LinkedList
c. TreeSet
d. HashSet
Answer: c. TreeSet
Reason: TreeSet implements the SortedSet interface and stores elements in their natural sorted order.
Q31) Which interface is required to achieve cloning?
Answer: b. Cloneable
Q32) What are the methods used to serialize and deserialize objects?
Answer: writeObject() for serialization and readObject() for deserialization.
Q33) Which among the following is a character stream class?
a. FileInputStream
b. FileReader
c. FileOutputStream
d. InputStreamReader
Answer: b. FileReader
Reason: It reads data as characters.
Q34) Which of the following is not a marker interface?
a. Serializable
b. Cloneable
c. Remote
d. ActionListener
Answer: d. ActionListener
Explanation: Marker interfaces do not contain any methods. ActionListener has methods.
Q35) Which package is imported automatically by JVM?
a. util
b. lang
c. io
d. awt
Answer: b. lang
Q36) The Date class belongs to which package?
Answer: a. java.util
Q37) What is the superclass of all Java classes?
Answer: a. Object
Q38) Which of the following is not a lightweight component?
a. JButton
b. JLabel
c. JTextField
d. TextField
Answer: d. TextField
Explanation: TextField is an AWT component (heavyweight), while the others are Swing components (lightweight).
Q39) Which of the following is not a Listener interface?
a. ActionListener
b. ComponentListener
c. ItemListener
d. MouseListener
Answer: b. ComponentListener
(Note: Actually, all four are valid listener interfaces. The correct answer here seems incorrect.)
✅ Corrected Answer: None of the above
Explanation: All four are listener interfaces in Java.
Q40) What is the use of Adapter classes in Java?
Answer:
Adapter classes in Java are helper classes that provide default (empty) implementations of all the methods in a listener interface. They are mainly used when you want to listen to only a few events from a listener interface without implementing all of its methods.
🔍 Why use Adapter classes?
Some interfaces like MouseListener, KeyListener, or WindowListener have multiple methods. If you implement these interfaces directly, you’re forced to provide an implementation for every method, even if you need only one.
🧠 Common Adapter Classes:
MouseAdapter– forMouseListenerKeyAdapter– forKeyListenerWindowAdapter– forWindowListenerFocusAdapter– forFocusListener
Q41) Predict the output:
class Sample {
public static void main(String args[]) {
int count = 0;
for(int i = 0; i < 5; i++) {
if(i == 3) {
continue;
}
count++;
}
System.out.println(count);
}
}
Answer: 4
Explanation: The continue skips incrementing the count when i == 3.
Q42) Predict the output:
class Sample {
public static void main(String args[]) {
int count = 0;
for(int i = 0; i < 5; i++) {
if(i == 3) {
break;
}
count++;
}
System.out.println(count);
}
}
Answer: 3
Explanation: The break exits the loop when i == 3.
Q43) All methods declared in an interface are implicitly…
Answer: c. Abstract
Q44) All data members declared in an interface are implicitly…
Answer: a. Final
Q45) Which interface is used for multiple sorting?
Answer: b. Comparator
Q46) Which interface has the compareTo() method?
Answer: a. Comparable
Explanation: Comparator uses compare() method; Comparable uses compareTo().
✅ Difference Between Comparator and Comparable in Java
Java provides two interfaces to allow sorting of objects:
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Purpose | Used to define natural ordering of a class | Used to define custom ordering of a class |
| Method to implement | compareTo(Object o) | compare(Object o1, Object o2) |
| Modifies class? | Yes – the class must implement Comparable | No – separate class can implement Comparator |
| Single / Multiple sorting | Only one compareTo method – supports single sorting sequence | Can create multiple Comparator implementations |
| Example Use Case | Sorting by ID or Name inside the class | Sorting by salary, date, etc. externally |
✅ Comparable Example:
import java.util.*;
class Student implements Comparable<Student> {
int rollNo;
String name;
Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
// Define natural ordering (by rollNo)
public int compareTo(Student s) {
return this.rollNo - s.rollNo;
}
public String toString() {
return rollNo + " - " + name;
}
}
public class TestComparable {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(102, "Ram"));
list.add(new Student(101, "Shyam"));
list.add(new Student(103, "Aman"));
Collections.sort(list); // Uses compareTo method
for (Student s : list)
System.out.println(s);
}
}
✅ Comparator Example:
import java.util.*;
class Student {
int rollNo;
String name;
Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
public String toString() {
return rollNo + " - " + name;
}
}
// Comparator to sort by name
class NameComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}
}
public class TestComparator {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(102, "Ram"));
list.add(new Student(101, "Shyam"));
list.add(new Student(103, "Aman"));
Collections.sort(list, new NameComparator());
for (Student s : list)
System.out.println(s);
}
}
✅ Summary:
| If You Want To… | Use |
|---|---|
| Sort using class’s natural/default logic | Comparable |
| Sort using external or multiple sorting criteria | Comparator |
Q47) Predict the output:
class Sample {
public static void main(String args[]) {
double d = 5.0 / 0.0;
System.out.println(d);
}
}
Answer: Infinity
Reason: Dividing a double by zero results in Infinity, not an exception.
🧠 Explanation:
- In Java, dividing a floating-point number (
floatordouble) by zero does not throw an exception. - Instead, it follows the IEEE 754 standard for floating-point arithmetic:
positive number / 0.0→Infinitynegative number / 0.0→-Infinity0.0 / 0.0→NaN(Not a Number)
- int i = 5 / 0; // ❌ ArithmeticException: / by zero
Q48) Which of the following is not a type of access modifier in Java?
a. Public
b. Private
c. Default
d. Protected
e. None of the above
Answer: e. None of the above
🧠 Explanation:
Java has four types of access modifiers:
- public – Accessible from anywhere.
- private – Accessible only within the class.
- protected – Accessible within the same package and in subclasses (even in different packages).
- default (no modifier) – Accessible only within the same package. It’s called package-private, and it’s not a keyword, but when no modifier is specified, it acts as default access.
Q49) Which of the following is not part of the java.net package?
a. Socket
b. ServerSocket
c. URL
d. Serialize
Answer: d. Serialize
Q50) Which of the following creates immutable Strings?
Answer: a. String
Explanation: String is immutable; StringBuffer and StringBuilder are mutable.
Q51) What will be the output if you execute the below code snippet?
public class Sample {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put(1, "a");
hm.put(2, "b");
hm.put(3, "c");
hm.put(1, "d");
System.out.println(hm.toString());
}
}
a) {1=d, 2=b, 3=c}
b) {1=d, 2=b, 1=a}
c) {1=a, 2=b, 3=c, 1=d}
d) {1=a, 2=b, 3=c}
✅ Answer: a
📝 Explanation: Key 1 is overwritten by "d".
Q52) What will be the output if you execute the below code snippet?
public class Sample {
public static void main(String args[]) {
int i = 2;
switch (i) {
case 1: System.out.println("1"); break;
case 2: System.out.println("2"); break;
case 3: System.out.println("3"); break;
case 4: System.out.println("4"); break;
case 2: System.out.println(" "); break;
default: System.out.println("Default");
}
}
a) The code will show compile-time errors
b) The code runs successfully and displays nothing
c) The code runs successfully and displays 2
d) The code will show runtime errors
✅ Answer: a
📝 Explanation: Duplicate case 2 causes a compile-time error.
Q53) What will be the output if you execute the below code snippet?
class Square {
public int calculateArea(int a) {
return a * a;
}
}
public class Cube extends Square {
public int calculateArea(int a) {
return a * a * a;
}
public static void main(String[] args) {
Square b = new Cube();
System.out.println(b.calculateArea(3));
}
}
a) The output 27 is displayed
b) The output 9 is displayed
c) The code shows runtime error
d) The code shows compile time error
✅ Answer: a
📝 Explanation: Method is overridden; Cube‘s version is called at runtime.
b is a reference of type Square, but it points to a Cube object.At runtime, Java resolves method calls based on the actual object type, not the reference type (dynamic method dispatch).
Q54) Which of the following is true?
a) Static methods can be overloaded and overridden.
b) Static methods can be overloaded but cannot be overridden.
c) Static methods can be overridden but cannot be overloaded.
d) Static methods can neither be overloaded nor be overridden.
✅ Answer: b
📝 Explanation: Static methods can be overloaded, but not overridden.
🔁 Overloading vs Overriding
| Feature | Overloading | Overriding |
|---|---|---|
| Applies To | Static and Instance Methods | Only Instance Methods |
| Signature | Method name same, different parameters | Method name & parameters must be same |
| Resolution Time | Compile-time | Runtime |
📌 Example:
class Parent {
static void display() {
System.out.println("Static method in Parent");
}
}
class Child extends Parent {
static void display() {
System.out.println("Static method in Child");
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.display(); // Output: Static method in Parent
}
}
🔍 Explanation:
- Even though
objis aChildobject, the methoddisplay()is resolved based on the reference type (Parent), not the object type. - So this is method hiding, not overriding.
🔄 Example of Static Method Overloading:
class Example {
static void print(int a) {
System.out.println("int: " + a);
}
static void print(String a) {
System.out.println("String: " + a);
}
public static void main(String[] args) {
print(10); // int: 10
print("Hello"); // String: Hello
}
}
Q55) Will the below code compile successfully?
class Base {
int foo(int a) {
return a;
}
}
public class Derived extends Base {
protected int foo(int a) {
return a + a;
}
public static void main(String[] args) {
Base b = new Derived();
}
}
a) True
b) False
✅ Answer: a
📝 Explanation: protected is more accessible than package-private (default), so it compiles.
Q56) Can a constructor be static and final?
a) True
b) False
✅ Answer: b
📝 Explanation: Constructors cannot be static or final.
Q57) All fields in an interface are:
a) public
b) static, final, public
c) abstract
d) public and final
✅ Answer: b
📝 Explanation: Fields in interfaces are implicitly public, static, and final.
✅ Explanation:
In Java, all fields (variables) declared in an interface are implicitly:
publicstaticfinal
Even if you don’t specify these modifiers explicitly, the compiler automatically treats them this way
📌 Example:
interface MyInterface {
int VALUE = 10; // implicitly public static final
}
This is equivalent to:
interface MyInterface {
public static final int VALUE = 10;
}
Q58) Which of the following is correct about StringBuffer and StringBuilder?
a) StringBuilder is thread safe and StringBuffer is not thread safe.
b) Both are thread safe.
c) Both are mutable. StringBuilder is not thread safe but StringBuffer is thread safe.
d) StringBuilder is immutable and not thread safe.
✅ Answer: c
📝 Explanation: StringBuffer is synchronized; StringBuilder is not.
Q59) Which is NOT a method of the String class?
a) append(String s)
b) replace(char oldChar, char newChar)
c) charAt(int index)
d) matches(String regex)
✅ Answer: a
📝 Explanation: append() is from StringBuilder, not String.
Q60) What is the best relation between Car and Engine?
a) Aggregation
b) Composition
c) Inheritance
d) Association
✅ Answer: b
📝 Explanation: Engine is tightly bound to Car → composition.
Q61) What is the output of the following code?
public class Sample {
static void replaceString(String s) {
s = s.replace("A", "Z");
System.out.println(s);
}
public static void main(String[] args) {
String s1 = "A";
replaceString(s1);
System.out.println(s1);
}
}
a) A A
b) A Z
c) Z A
d) Z Z
✅ Answer: c
📝 Explanation: String is immutable, original string remains unchanged in main.
Q62) Which collection maintains insertion order and stores unique elements?
a) LinkedHashSet
b) HashSet
c) HashMap
d) TreeMap
✅ Answer: a
Q63) What happens when this code is executed?
public class Sample2 {
public static void main(String args[]) {
try {
throw new InterruptedException();
} catch(Exception e) {
System.out.println(e);
}
}
}
a) InterruptedException is caught
b) Exception is caught
c) Exception is not caught
d) Compilation error
✅ Answer: d
📝 Explanation: InterruptedException is a checked exception and must be declared or handled directly.
Q64) What types of inheritance are supported in Java?
a) Multilevel, Multiple, Single, Hierarchical
b) Multilevel, Multiple, Single, Hybrid
c) Multilevel, Multiple, Single, Hierarchical, Hybrid
d) Multilevel, Single, Hierarchical, Hybrid
✅ Answer: d
Q65) What will the following code print?
class Animal {}
public class Dog extends Animal {
public static void findInstance(Animal a) {
if (a instanceof Dog) {
System.out.println("This is Dog instance");
} else if (a instanceof Animal) {
System.out.println("This is Animal instance!");
}
}
public static void main(String args[]) {
Animal a = new Dog();
findInstance(a);
}
}
a) This is Dog instance
b) This is Animal instance!
c) ClassCastException is thrown
d) Runtime Error occurs
✅ Answer: a
Q66) What will this code print?
String s1 = new String("string");
String s2 = "string";
System.out.println(s1 == s2 + " " + s1.equals(s2));
a) true true
b) false true
c) true false
d) false false
✅ Answer: b
Q67) Which of the following can’t be used alone to overload a method?
a) Type of arguments
b) Order of arguments
c) Number, type, and order of arguments
d) Return type of method
✅ Answer: d
Q68) What will this code output?
static void m1(byte b) {
System.out.println(++b);
}
public static void main(String[] args) {
m1(1);
}
a) 2
b) 1
c) Runtime Exception
d) Compile-time error
✅ Answer: a
📝 Explanation: 1 is promoted to byte automatically.
Q69) Can a try block be empty?
a) True
b) False
✅ Answer: b false
📝 Explanation: Try block can’t be empty; at least one statement is required.
Q70) Which of the following is true about local variables?
a) Local variables can be final but cannot be static or transient.
b) Local variables can be final or static but cannot be transient.
c) Local variables can be final, static, and transient.
d) Local variables cannot be final, static, transient.
✅ Answer: a
💡 Explanation:
- Local variables are variables declared inside methods, constructors, or blocks.
- They:
- Can be declared
final: This means the variable’s value cannot be changed once assigned. - Cannot be
static: Becausestaticbelongs to class level, while local variables live on the stack and are method-scoped. - Cannot be
transient: This keyword is used for serialization (and applies to instance variables, not local variables).
- Can be declared
In Java, variables can be classified into four main types, based on where and how they are declared. Each type has specific scope, lifetime, storage, and default values.
1. Local Variables
- Declared inside a method, constructor, or block.
- Scope: Only within the block/method in which they are declared.
- Default value: ❌ No default value (must be initialized before use).
- Modifiers allowed: Only
final. - Cannot be:
static,transient, orvolatile.
public void display() {
int localVar = 5; // Local variable
System.out.println(localVar);
}
2. Instance Variables (Non-static Fields)
- Declared in a class, but outside any method, and without the static keyword.
- Each object of the class gets its own copy.
- Scope: Accessible by all non-static methods of the class.
- Default value: ✅ Automatically initialized (e.g.,
0,null,false). - Can use modifiers:
private,public,protected,final,transient,volatile.
public class Person {
private String name; // Instance variable
public int age; // Instance variable
}
3. Static Variables (Class Variables)
- Declared with the
statickeyword inside a class but outside any method. - Shared among all instances of the class.
- Scope: Class-level, can be accessed using the class name.
- Default value: ✅ Automatically initialized.
- Modifiers allowed:
private,public,protected,final.
public class Counter {
static int count = 0; // Static variable shared by all objects
}
4. Parameters
- Variables passed to methods or constructors.
- Behave like local variables.
- Modifiers allowed: Only
final. - Cannot be
static,transient, etc.
public void greet(String name) { // 'name' is a parameter
System.out.println("Hello, " + name);
}
Q71) What will this code output?
public static void dec(double d) {
d = d - 3;
}
public static void main(String args[]) {
double d = 13; //primitive , passed by value
dec(d);
System.out.println(d);
}
a) 13
b) 0
c) 10
d) 0.0
✅ Answer: a
Q72) What will this code print?
public class Sample {
public static void main(String[] args) {
byte b = 2;
int n = 100;
long l = n;
Double d = (double) Integer.valueOf(n);
System.out.println(b);
System.out.println(n);
System.out.println(n);
System.out.println(d);
}
}
a) ClassCastException
b) Compile-time error
c) 2 100 100 100.0
d) 2 100 100L 100.0D
✅ Answer: c
Integer.valueOf(n) returns an Integer object wrapping 100.
It is then unboxed to int, and then cast to double.
Result: d = 100.0.
Q73) What will this code do?
boolean b = false;
do {
System.out.println("inside do while loop");
b = true;
} while (!b);
a) Nothing is printed
b) Infinite loop
c) Prints “inside do while loop”
d) Runtime Exception
✅ Answer: c
Q74) Is use of this() or super() allowed inside static methods?
a) True
b) False
✅ Answer: b
Q75) What changes are required for below code to compile?
interface A {
public int display();
}
abstract class B implements A {}
public class Example extends B {
public int display() {
return 0;
}
}
a) Implement the display method in class B
b) Overload the display method in class Example
c) Remove class B
d) No changes needed
✅ Answer: d
✅ Explanation:
Let’s break down the code:
interface A {
public int display();
}
- Interface
Adeclares an abstract methoddisplay().
abstract class B implements A {}
- Class
Bimplements interfaceA, but it’s abstract, so it’s not required to implement thedisplay()method. - This is valid Java — abstract classes can choose to defer the implementation to a subclass.
public class Example extends B {
public int display() {
return 0;
}
}
Exampleis a concrete class (not abstract), and it implements the requireddisplay()method.- Thus,
Examplecompletes the contract of interfaceA
Q76) How to send a cookie in the response?
a) HttpServletResponse.addCookie(Cookie)
b) HttpServletResponse.setCookie(Cookie)
c) HttpServletResponse.sendCookie(Cookie)
d) setCookie(HttpServletResponse response)
Answer: a
Explanation: addCookie(Cookie cookie) is the standard method in HttpServletResponse to send cookies to the client.
Q77) In a class, can a local variable be static?
a) Yes
b) No
Answer: No
Explanation: Local variables cannot be declared static because they belong to the method, not the class.
Q78) Which method is used to forward control to another servlet?
a) sendRedirect()
b) forward()
c) send()
d) redirect()
Answer: b
Explanation: RequestDispatcher.forward() forwards the request internally on the server.
Q79) What is the output of this JSP snippet?
<%! int a = 10; %>
<% int a = 5; %>
<% int b = 2; %>
Result is <%= a * b %>
a) Displays 20
b) You cannot redeclare a
c) Displays 10
d) Error is displayed
Answer: c
Explanation: Scriptlet variable a=5 shadows the declaration a=10. Output = 5 * 2 = 10.
Q80) What manages the servlet lifecycle?
a) Application server
b) Web container
c) Application container
d) Web server
Answer: b. Webcontainer (like tomcat)
🔁 Servlet Lifecycle Phases:
- Loading and Instantiation
- The servlet class is loaded by the Servlet Container (like Tomcat).
- A single instance of the servlet is created.
- Initialization (
init()method)- Called once after the servlet is instantiated.Used for one-time setup like opening DB connections, reading config.
public void init(ServletConfig config) throws ServletException { } - Request Handling (
service()method)- Called every time a request is made to the servlet.Delegates to
doGet(),doPost(), etc., based on HTTP method.
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { } - Called every time a request is made to the servlet.Delegates to
- Destruction (
destroy()method)- Called once when the servlet is taken out of service.Used for cleanup (e.g., closing DB connections).
public void destroy() { }
Lifecycle Flow:
Loading → init() → service() (multiple times) → destroy()
Q81) With Java 7, what is supported in switch statements?
a) Enum
b) Character
c) String
d) Constant
Answer: c
Explanation: Java 7 introduced support for String in switch statements.
Q82) Which code gives the minimum value from a list?
a)
list.stream().mapToInt(v -> v).findMin();
b)
list.stream().mapToInt(v -> v).min().orElse(Integer.MAX_VALUE);
c)
list.stream().min(Comparator.naturalOrder()).get();
d)
List.stream(list).mapToInt(v -> v).min();
Answer: b
Explanation: .min().orElse(Integer.MAX_VALUE) ensures a valid value is returned even if the stream is empty.
Q83) What is the type of a lambda expression?
a) Object
b) Functional Interface
c) Interface
d) Object variable
Answer: b
🔹 Explanation:
In Java, lambda expressions are not standalone objects. They are treated as instances of functional interfaces—interfaces that have exactly one abstract method.
@FunctionalInterface
interface MyFunction {
void apply();
}
public class Test {
public static void main(String[] args) {
MyFunction f = () -> System.out.println("Hello Lambda!");
f.apply();
}
}
Here:
() -> System.out.println("Hello Lambda!")is a lambda expression.- Its type is
MyFunctionbecauseMyFunctionis a functional interface.
Q84) Which is not a method of Optional class?
a) isPresent()
b) ofNullable(T val)
c) orElse(T t)
d) isPresentOrNull()
Answer: d
🔍 Explanation:
The Optional class (introduced in Java 8) provides a container that may or may not contain a non-null value. It helps in avoiding NullPointerException.
Valid methods of Optional include:
isPresent()
→ Returnstrueif a value is present, otherwisefalse.ofNullable(T value)
→ Returns anOptionaldescribing the specified value, or an emptyOptionalif the value isnull.orElse(T other)
→ Returns the value if present; otherwise, returnsother.
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
// Create Optional using ofNullable() - this handles null safely
String name = null;
Optional<String> optionalName = Optional.ofNullable(name);
// Check if value is present
if (optionalName.isPresent()) {
System.out.println("Name is: " + optionalName.get());
} else {
System.out.println("Name is not present");
}
// Use orElse to provide default value
String finalName = optionalName.orElse("Default Name");
System.out.println("Final Name: " + finalName);
// Using Optional with non-null value
Optional<String> anotherName = Optional.of("John");
System.out.println("Another Name: " + anotherName.orElse("Default Name"));
}
}
Q85) Output of the following code:
String myString = "123s4";
int foo = Integer.parseInt(myString);
System.out.println(foo);
a) ClassCastException is thrown
b) Compile time Exception is thrown
c) NumberFormatException is thrown
d) Code displays “123s4”
Answer: c
Explanation: "123s4" is not a valid integer, so NumberFormatException is thrown.
Q86) Which of the following is not a built-in Java annotation?
a) @Override
b) @SuppressWarnings
c) @Deprecated
d) @Inherit
Answer: d
Explanation: The correct annotation is @Inherited. @Inherit does not exist.
Q87) Why does the following code not compile?
class Super {
void show() { System.out.println("super"); }
}
public class Sub extends Super {
void show() throws IOException {
System.out.println("sub");
}
}
a) CheckedException cannot be used with throws keyword
b) Sub class overridden method cannot throw CheckedException
c) CheckedException should be handled with try-catch
d) The code is correct
Answer: b
Explanation: Overridden methods cannot throw new or broader checked exceptions than the superclass method.
Q88) Which of the following is not true about lambda expressions?
a) They replace anonymous classes
b) They help in implementing functional interfaces
c) Their scope is not limited to the enclosing class
d) They use target typing to infer argument types
Answer: c
Explanation: Lambdas are tightly scoped within the context they’re defined.
Q89) Choose the correct relationship for:
“House has a room which is luxurious”
a) class Room extends House { luxury(); }
b) class House { private LuxuryType room; }
c) class Room { private House house; }
d) class Room { private Luxury house; }
Answer: b
Explanation: Composition is modeled by House having a Room as a field.
Q90) Correct way to implement a NavigableSet:
a)
javaCopyEditNavigableSet al = new NavigableSet();
b)
NavigableSet al = new TreeSet();
c)
Set al = new NavigableSet();
d)
TreeSet al = new NavigableSet();
Answer: b
Explanation: NavigableSet is an interface, TreeSet is a concrete class that implements it.
Q91) Which method causes a thread to pause until another thread completes?
a) join()
b) wait()
c) wait(int num)
d) resume()
Answer: a
Explanation: join() makes the current thread wait until the other thread terminates.
Q92) Where can synchronized be used?
a) Methods, variables, block
b) Methods, blocks, static blocks
c) Variables, methods
d) Methods and blocks
Answer: d) Methods and blocks
📘 Explanation:
In Java, the synchronized keyword can be used to prevent concurrent access to critical sections of code by multiple threads.
You can use synchronized in two ways:
- Synchronized Method
public synchronized void myMethod() { // thread-safe logic } - Synchronized Block
public void myMethod() { synchronized(this) { // thread-safe logic } }
❌ Why Other Options Are Incorrect:
X variables can’t be synchronized.
X Static blocks can’t be declared synchronized.
Q93) Which tag is used to load a servlet at server startup?
a) <load-on-startup>
b) <init-on-load>
c) <load-when-ready>
d) <startup>
Answer: a
Explanation: <load-on-startup> ensures the servlet is instantiated during server startup.
Q94) Which is true about ServletContext?
a) One per web application
b) One per session
c) One per context path
d) One per web config
Answer: a
Explanation: ServletContext is shared across the entire web application.
Q95) Which of these is not a valid HTTP method?
a) GET
b) REPLACE
c) PUT
d) HEAD
Answer: b
Explanation: REPLACE is not an HTTP method.
Q96) Which is not a class in Java Collections hierarchy?
a) SortedSet
b) TreeSet
c) LinkedHashSet
d) HashSet
Answer: a
Explanation: SortedSet is an interface, not a class.
Q97) Which JDBC driver uses middleware?
a) JDBC-ODBC bridge driver
b) Native-API driver
c) Network Protocol driver
d) Thin driver
Answer: c
Explanation: The Network Protocol driver (Type 3) uses a middleware server.
Q98) How to split a String s = "Hi I am Good" into words?
a) s.split("")
b) s.split(",")
c) s.split(" ")
d) s.tokenize()
Answer: c
Explanation: split(" ") splits by spaces.
Q99) Which of these is not a keyword in Java?
a) implements
b) package
c) throws
d) Integer
Answer: d
Explanation: Integer is a class in java.lang, not a keyword.
Q100A) How to find the size of the array arrayNum?
a) arrayNum.size()
b) arrayNum.length()
c) arrayNum.length
d) size(arrayNum)
Answer: c
Explanation: For arrays in Java, use array.length (without parentheses).
✅ Important:
- For arrays →
array.length(no parentheses) - For strings →
string.length()(with parentheses)
Q100B) Why Java is called platform independent?
✅ Answer: Class files generated in Windows OS can run on different machines irrespective of OS such as macOS, Linux, etc.
➡ Explanation: Java code is compiled into bytecode, which runs on JVM, not directly on OS, making it platform-independent.
Q101) Is JVM platform independent or platform dependent?
✅ Answer: Platform dependent
➡ Explanation: JVM is OS-specific and must be implemented for each platform.
Q102) Explain why JVM is platform dependent?
✅ Answer: Different OS has a respective JVM installed which interacts with that OS, making JVM platform dependent.
➡ Explanation: Bytecode is the same, but JVM implementation is OS-specific.
Q103) Where are objects stored in JVM?
✅ Answer: In Heap
➡ Explanation: The heap is the memory area used to store Java objects during runtime.
Q104) How many copies exist when String Object is created?
✅ Answer: Two copies — one in the String Pool and one in the Heap
➡ Explanation: Using new String("value") creates a new object in the heap, while the literal goes into the String pool.
Q105) How would you handle NullPointerException, explain through code.
✅ Answer:
String s1 = "Hello GangBoard!!";
if (s1 != null && !s1.isEmpty()) {
System.out.println("Hello Karthik");
}
➡ Explanation: Always check for null before calling methods to avoid NullPointerException.
Q106) What is an Exception?
✅ Answer: Exception is an object that indicates runtime errors disrupting normal program flow.
➡ Explanation: Java treats errors as objects which can be caught and handled.
Q107) Can main() be overloaded?
✅ Answer: Yes
➡ Explanation: You can define multiple main() methods with different parameters, but JVM only calls the one with String[] args.
Q108) What is a String Literal?
✅ Answer: A string declared like String s = "hello"; is a literal and stored in the String pool.
➡ Explanation: String literals are interned and memory-optimized.
This "Hello" is stored in the String pool—a special memory area inside the heap. ❌ String pool is not in the stack.
Q109) What is the default scope of Spring bean?
✅ Answer: Singleton
➡ Explanation: Spring creates only one instance per container by default.
Q110) What is IoC (Inversion of Control)?
✅ Answer: Spring container controls object creation and lifecycle.
➡ Explanation: This promotes loose coupling and enhances testability.
Q111) What is the output of below?
String s1 = "hi";
String s2 = new String();
s2 = "hi";
if (s1 == s2) {
System.out.println("Hello Karthik");
} else {
System.out.println("Hi GangBoard");
}
✅ Answer: Hello Karthik
🔍 What Happens Internally?
So now both s1 and s2 point to the same object in the pool.
String s1 = "hi";
A string literal "hi" is stored in the String Pool.
s1 points to that memory location in the pool.
String s2 = new String();
Creates a new empty string object in the Heap.
s2 = "hi";
Now s2 is reassigned to point to the string literal "hi" in the String Pool.
Q112) What is the output of below?
String s1 = "hi";
String s2 = new String();
s2 = "hi";
if (s1.equals(s2)) {
System.out.println("Hello Karthik");
} else {
System.out.println("Hi Beasant");
}
✅ Answer: Hello Karthiks1.equals(s2) checks content equality, not memory address.
Since both s1 and s2 point to "hi", the content is the same.
Q113) What is the output of below?
String s1 = "hello GangBoard!!";
String s2 = s1.substring(0, 4);
System.out.println(s2);
✅ Answer: hell
➡ Explanation: substring(0, 4) returns characters from index 0 to 3.
Q114) Which exceptions are required to handle?
✅ Answer: Checked exceptions
➡ Explanation: These are checked at compile-time and must be either caught or declared.
Q115) Example of unchecked exceptions.
✅ Answer: ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException
➡ Explanation: These occur at runtime and are not required to be handled.
✅ Quick Comparison Table:
| Feature | Checked Exception | Unchecked Exception |
|---|---|---|
| Checked at Compile-Time | Yes | No |
| Class Hierarchy | Subclass of Exception | Subclass of RuntimeException |
| Common Use Case | File, DB, Network operations | Logic bugs like null, divide by 0 |
| Try/Catch or throws req? | Yes | No |
| Example | IOException, SQLException, ClassNotFoundException | NullPointerException, ArithmeticException |
Q116) Can a method be invoked without creating an object?
✅ Answer: Yes, if it is static
➡ Explanation: Static methods belong to the class, not to any instance.
Q117) Which methods are loaded into JVM when a program is executed?
✅ Answer: Static methods
➡ Explanation: Static members are loaded during class loading.
Q118) When are ArrayList and LinkedList recommended?
✅ Answer:
- Use ArrayList for frequent read operations.
- Use LinkedList for frequent insert/delete operations.
➡ Explanation: ArrayList offers random access, while LinkedList has efficient node operations.
Q119) Why are generics used?
✅ Answer: To ensure type safety
➡ Explanation: Generics help catch type errors at compile-time.
Q120) Which collection does HashMap internally use?
✅ Answer: Array of LinkedList (or Tree for Java 8+)
➡ Explanation: Initially uses an array of buckets; collisions handled via LinkedList or Tree.
Q121) What is Java?
✅ Answer: Java is a platform-independent, secure, object-oriented language used to build applications.
➡ Explanation: It can be used for desktop, web, and mobile development.
Q122) What is OOPs?
✅ Answer: Object-Oriented Programming System — a paradigm based on objects
➡ Explanation: Java is based on this concept to improve reusability and modularity.
Q123) OOPs concepts in Java?
✅ Answer: Inheritance, Encapsulation, Polymorphism, Abstraction
Q124) Why Encapsulation?
✅ Answer: For data security and modularity
➡ Explanation: Encapsulation hides internal details from the outside world.
Q125) Why Polymorphism?
✅ Answer: To allow multiple behaviors with the same method name
➡ Explanation: Reduces complexity and improves code maintainability.
Q126) Why Inheritance?
Answer: It is used for reusability.
➡ Explanation: Inheritance allows child classes to reuse code from parent classes, promoting code reuse and reducing redundancy
Q127) Why Abstraction?
Answer: It hides implementation details and shows only essential features.
➡ Explanation: Abstraction provides a clear separation between what an object does and how it does it.
Q128) Types of Polymorphism?
Answer:
- Compile-time polymorphism (Method Overloading)
- Runtime polymorphism (Method Overriding)
➡ Explanation: Compile-time polymorphism is resolved by the compiler; runtime polymorphism is determined during program execution.
Q129) Difference between overload and override?
Answer:
- Overload: Same method name, different parameters, within the same class.
- Override: Same method in a subclass with the same signature as in the parent class.
➡ Explanation: Overloading provides flexibility; overriding allows customization of inherited behavior.
Q130) How many types of relationships in Java?
Answer:
- IS-A (Inheritance)
- HAS-A (Aggregation/Composition)
➡ Explanation: IS-A shows inheritance; HAS-A shows object ownership or association.
Q131) What is Inheritance?
Answer: It’s a mechanism for deriving one class from another to reuse code.
➡ Explanation: Helps implement IS-A relationship and code reuse.
Q132) Does Java support multiple inheritance?
Answer: No (for classes), but yes via interfaces.
➡ Explanation: To avoid ambiguity, Java doesn’t support multiple inheritance using classes.
Q133) Why object-oriented programming?
Answer:
- Reduces redundancy through inheritance
- Simplifies maintenance
- Enhances scalability
➡ Explanation: OOP improves modularity, flexibility, and reusability.
Q134) What is a class?
Answer: A class is a blueprint that defines variables and methods for objects.
➡ Explanation: It acts as a template for creating objects.
Q135) How to achieve multiple inheritance in Java?
Answer: By using interfaces
➡ Explanation: Java allows a class to implement multiple interfaces, thus achieving multiple inheritance.
Q136) How to avoid method override in Java?
Answer: Declare the method as final.
➡ Explanation: A final method cannot be overridden in subclasses.
Q137) What is the this keyword in Java?
Answer: It refers to the current object of the class.
➡ Explanation: Useful to distinguish between class variables and method parameters with the same name.
Q138) How to achieve encapsulation in Java?
Answer: By making variables private and accessing them through getters and setters.
➡ Explanation: It restricts direct access and allows controlled interaction.
Q139) What is the use of getter and setter methods in Java?
Answer: To access and modify private variables from outside the class.
➡ Explanation: Provides encapsulated control over class fields.
Q140) What is the use of packages in Java?
Answer: They help in avoiding name conflicts and organizing classes.
➡ Explanation: They also control access levels and provide modularity.
Q141) What is a wrapper class in Java?
Answer: A class that converts primitive types into objects and vice versa.
➡ Explanation: Used in collections and for object-oriented manipulation.
Q142) What is autoboxing?
Answer: Automatic conversion of primitive type to corresponding wrapper class object.
➡ Example: int a = 10; Integer obj = a;
Q143) What is unboxing?
Answer: Automatic conversion of wrapper class object to primitive type.
➡ Example: Integer obj = 10; int a = obj;
Q144) What is a constructor?
Answer: A special method invoked during object creation to initialize fields.
➡ Explanation: Constructors have the same name as the class and no return type.
Q145) Types of constructors in Java?
Answer:
- Default constructor
- Parameterized constructor
➡ Explanation: Default constructor has no parameters; parameterized constructor initializes variables with arguments.
Q146) What are checked exceptions in Java?
Answer: Exceptions that are checked at compile-time.
➡ Examples: IOException, ClassNotFoundException
Q147) What are unchecked exceptions in Java?
Answer: Exceptions that are checked at runtime.
➡ Examples: NullPointerException, ArithmeticException
Q148) Difference between final and finally?
Answer:
final: Modifier used for classes, methods, or variablesfinally: Block that executes aftertry-catch, regardless of exception
➡ Explanation:finalprevents changes;finallyensures clean-up.
Q149) Difference between throw and throws?
Answer:
throw: Used to explicitly throw an exceptionthrows: Declares exceptions a method may throw
➡ Example:throw new IOException();vsvoid read() throws IOException {}
Q150) What is serialization?
Answer: Converting an object into a byte stream to save or transfer over the network.
➡ Explanation: Achieved by implementing the Serializable interface.
In Java, serialization is done on objects, not directly on methods or variables.
However, when an object is serialized:
- Instance variables of that object are serialized (saved to a byte stream).
- Static variables are not serialized (because they belong to the class, not the instance).
- Transient variables are skipped during serialization.
- Methods are never serialized.
class Person implements Serializable {
String name; // will be serialized
transient int age; // will NOT be serialized
static String species = "Human"; // will NOT be serialized
void sayHello() { // method is not serialized
System.out.println("Hi, I’m " + name);
}
}
Q151) What is deserialization?
Answer: Deserialization is the reverse operation of serialization where a byte stream is converted back into a Java object.
Explanation: When data is serialized (converted into a byte stream), deserialization helps recreate the object from that stream, usually to read data from a file or network.
🔧 When do we use deserialization?
- Reading saved objects from files
- Receiving objects over a network (e.g., RMI, HTTP)
- Storing and retrieving object states
- The class must have the same serialVersionUID if used across serialization and deserialization.
//Serialization (writing object to file):
import java.io.*;
class Student implements Serializable {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
// Serialize object
Student s1 = new Student("Ved", 25);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"));
oos.writeObject(s1);
oos.close();
//Deserialization (reading object from file):
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"));
Student s2 = (Student) ois.readObject();
ois.close();
System.out.println(s2.name); // Ved
System.out.println(s2.age); // 25
Q152) Can we remove the objects during iteration?
Answer: Yes, using Iterator or ListIterator.
Explanation:
ListIterator<String> itr = balls.listIterator();
while(itr.hasNext()) {
itr.next();
itr.remove(); // removes current item safely
}
You should not use a regular for-each loop with remove() as it causes ConcurrentModificationException.
Q153) How to sort a collection?
Answer: Use Collections.sort() for List, and implement Comparable or use Comparator.
Explanation:
Collections.sort(list)uses natural ordering or a custom comparator.- Objects in the list must either implement
Comparableor be sorted with aComparator.
Q154) TreeSet is used for what purpose?
Answer: For storing sorted elements with no duplicates.
Explanation: TreeSet uses a Red-Black Tree structure to maintain sorting. It does not allow duplicate values.
Q155) How to make a class immutable?
Answer:
- Declare class as
final - Make all fields
private final - Do not provide setters
Explanation: This ensures once the object is created, its state cannot be changed.
Q156) What is yield() method in Java?
Answer: It hints the thread scheduler to pause the current thread and give chance to other threads of equal priority.
Explanation: It does not guarantee that the thread will stop. It is part of the Thread class.
Q157) Default scope in Spring?
Answer: Singleton
Explanation: By default, Spring beans are created as singletons, meaning one instance per Spring container.
Q158) How to handle exceptions in Spring MVC?
Answer: Using @ExceptionHandler method inside a controller.
Explanation:
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
Q159) What is the use of @Qualifier in Spring?
Answer: It helps Spring distinguish between multiple beans of the same type for autowiring.
Explanation:
@Autowired
@Qualifier("myBean")
private MyService service;
Q160) What is externalization?
Answer: A mechanism similar to serialization, but gives the programmer full control over serialization logic.
Explanation: Implement Externalizable interface and override writeExternal() and readExternal().
Q161) What is transient keyword?
Answer: A variable marked as transient will not be serialized.
Explanation: Useful when you don’t want sensitive or temporary fields to be saved.
Why Use transient?
- To avoid serializing sensitive data (like passwords, credit card numbers).
- To skip non-serializable fields that might cause errors during serialization.
- To prevent storing temporary/cache-related data that doesn’t need persistence.
Q162) Explain OOP concepts with real-life examples?
Answer:
- Encapsulation: Wrapping data and code (e.g., biscuit has ingredients hidden inside).
- Inheritance: Child inherits traits from parent (e.g., child inherits DNA).
- Polymorphism: One name, many forms (e.g., talk method varies across animals).
- Abstraction: Hiding complexity (e.g., phone dialing hides internal processing).
Q163) Difference between overloading and overriding?
Answer:
- Overloading: Same method name, different parameters, in same class.
- Overriding: Same method name/signature in subclass.
Explanation: Used in your project when extending a class and changing behavior.
Q164) Have you used super keyword?
Answer: Yes, super is used to access the superclass method or constructor.
Explanation:
super.methodName(); // Calls parent method
super(); // Calls parent constructor
Q165) Explain memory areas of JVM?
Answer:
- Heap: Stores objects
- Stack: Stores method call frames, local variables
- PC Register: Tracks executing instruction
- Method Area: Stores class structure
- Native Method Stack: For native (non-Java) code
Q166) Does Java support multiple inheritance?
Answer: No, with classes
Explanation: To avoid ambiguity, Java does not support multiple inheritance using classes, but it supports it using interfaces.
Q167) How to achieve multiple inheritance in Java?
Answer: Using interfaces
Explanation: A class can implement multiple interfaces.
Q168) How do you write an interface and use it?
Answer:
interface A {
void show();
}
class B implements A {
public void show() {
System.out.println("Hello");
}
}
Explanation: All methods in interfaces are abstract by default.
Q169) Which collection for vehicle parking system?
Answer: ConcurrentHashMap
Explanation: Thread-safe and fast for concurrent access when multiple vehicles are parked simultaneously.
Q170) What is a singleton class?
Answer: A class that allows only one instance.
Explanation: Useful for logging, configurations, etc.
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
Q171) How to avoid breaking singleton using clone()?
Answer: Override clone() method and throw CloneNotSupportedException.
Explanation:
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
Q172) How is portability achieved in Java?
Answer: Bytecode can run on any OS that has JVM.
Explanation: Java source code → compiled to bytecode → interpreted by JVM.
Q173) Two differences between Java and C++?
Answer:
- Java has no pointers.
- Java doesn’t support multiple inheritance with classes.
Q174) What are the basic data types in Java?
Answer: byte, short, int, long, float, double, char, boolean
1. Primitive Data Types
These are built-in types and not objects. They represent single values.
| Type | Size | Default Value | Description |
|---|---|---|---|
byte | 1 byte | 0 | Small integer: Range from -128 to 127 |
short | 2 bytes | 0 | Small integer: Range from -32,768 to 32,767 |
int | 4 bytes | 0 | Default integer type |
long | 8 bytes | 0L | Large integers |
float | 4 bytes | 0.0f | Single-precision decimal numbers |
double | 8 bytes | 0.0d | Double-precision decimal numbers (default) |
char | 2 bytes | \u0000 | Single 16-bit Unicode character |
boolean | 1 bit | false | Logical value: true or false |
2. Reference/Object Data Types
These store references (addresses) to actual objects in memory.
| Type | Description |
|---|---|
String | A sequence of characters (not a primitive type) |
| Arrays | Group of elements of the same type |
| Classes | Custom object blueprints |
| Interfaces | Contract of methods a class must implement |
✅ Summary:
- Use primitive types for performance and memory efficiency.
- Use reference types for complex data structures and OOP features.
- Java is not 100% object-oriented because it uses primitive types.
Q175) What is boxing/unboxing?
Answer:
- Boxing: Converting primitive to wrapper object (e.g.,
inttoInteger) - Unboxing: Converting wrapper to primitive
Explanation:
Integer i = 10; // Boxing
int j = i; // Unboxing
Q176) Do primitive data types have the same size all over the world?
Answer: Yes
Explanation: Java guarantees the size of its primitive types regardless of the platform to ensure portability.
byte: 8 bitsshort: 16 bitsint: 32 bitslong: 64 bitsfloat: 32 bitsdouble: 64 bitschar: 16 bits (because Java uses Unicode)boolean: JVM-specific, but logically represents true/false
Q177) What is a constructor?
Answer: A constructor is a special method that is called when an object is instantiated.
Explanation: It has the same name as the class and is used to initialize the object’s state. It doesn’t have a return type, not even void.
Q178) Does Java have a destructor?
Answer: No
Explanation: Java does not support destructors like C++. Instead, it uses Garbage Collection (GC) to reclaim memory. The finalize() method was used earlier, but it’s deprecated in modern Java.
🔹 Example: Unreachable Object
public class GCDemo {
public static void main(String[] args) {
GCDemo obj = new GCDemo(); // Object created
obj = null; // No reference → becomes eligible for GC
System.gc(); // Suggest GC to run (not guaranteed)
}
@Override
protected void finalize() throws Throwable {
System.out.println("Object is garbage collected");
}
}
Q179) What is Garbage Collection?
Answer: It is the automatic process of reclaiming unused memory.
Explanation: The JVM uses a garbage collector to delete objects that are no longer referenced to avoid memory leaks.
Q180) What is the use of this keyword?
Answer: this refers to the current object of the class.
Explanation:
- It distinguishes between instance variables and parameters when they have the same name.
- It can be used to invoke another constructor in the same class using
this().
class A {
int x;
A(int x) {
this.x = x; // Refers to instance variable
}
}
Q181) What is super keyword?
Answer: super refers to the parent (superclass) of the current class.
Explanation:
- It is used to access superclass variables, methods, or constructors.
- Must be the first line in a constructor if used.
class Parent {
int x = 10;
}
class Child extends Parent {
void show() {
System.out.println(super.x); // accesses Parent's x
}
}
Q182) What is an Exception?
Answer: Exception is an object that represents a runtime error.
Explanation: It interrupts the normal flow of the program. Java handles exceptions using try, catch, and finally blocks. All exceptions are derived from Throwable.
Q183) What is the difference between Error and Exception?
Answer:
- Error: Serious issues like
OutOfMemoryError, usually not handled by programs. - Exception: Can be caught and handled using exception handling mechanisms.
Explanation: Errors indicate system-level issues; exceptions are for application-level problems.
Q184) What is throws keyword?
Answer: It declares that a method may throw an exception.
Explanation: It is used in method signature to delegate the exception handling responsibility to the caller method.
void readFile() throws IOException {
// code
}
Q185) What is a thread?
Answer: A thread is a lightweight subprocess.
Explanation: Multiple threads can run concurrently, sharing the same memory but executing independently.
Q186) What are the two ways to create a thread in Java?
Answer:
- Extend
Threadclass - Implement
Runnableinterface
Explanation: Both approaches override therun()method to define thread logic.
Q187) When to extend Thread and when to implement Runnable?
Answer:
- Use
Runnablewhen your class needs to extend another class (multiple inheritance workaround). - Use
Threadif you don’t need to extend anything else.
Explanation: ImplementingRunnableis generally preferred for better design flexibility.
Q188) What is an abstract method?
Answer: A method with no body, declared using the abstract keyword.
Explanation: It must be implemented by a subclass. Abstract methods can only be declared in abstract classes or interfaces
Q189) What is the final keyword?
Answer: It is used to declare constants and prevent overriding or inheritance.
Explanation:
- Final variable: cannot be reassigned.
- Final method: cannot be overridden.
- Final class: cannot be subclassed.
Q190) What are the thread states?
Answer:
- New
- Runnable
- Blocked
- Waiting
- Timed Waiting
- Terminated
Explanation: These represent the lifecycle of a thread from creation to end.
Q191) What is the base class of all Java classes?
Answer: java.lang.Object
Explanation: Every class in Java either directly or indirectly inherits from Object.
Q192) Which package is automatically imported in every Java program?
Answer: java.lang
Explanation: This package contains core classes like String, System, Math, etc.
Q193) Difference between InputStream/OutputStream and Reader/Writer?
Answer:
InputStream/OutputStream: For binary data (bytes)Reader/Writer: For character data (text)
Explanation: Reader/Writer are preferred when working with text to support Unicode.
Q194) What is PushbackInputStream / PushbackReader?
Answer: Streams that allow unread of characters or bytes.
Explanation: Using the unread() method, you can “push back” the read data into the stream to be read again.
Q195) What are the main collection interfaces in Java?
Answer:
CollectionListSetSortedSetNavigableSetQueueDeque
Explanation: These are part of the Java Collection Framework used to store and manipulate data.
Q196) What is the purpose of Iterable interface?
Answer: To allow iteration over a collection using enhanced for-each loop.
Explanation: Any class that implements Iterable can be used in for (Type t : collection) syntax.
Q197) Difference between ArrayList and Array?
Answer:
- Array: Fixed size, can hold primitives.
- ArrayList: Dynamic size, holds objects only.
Explanation: ArrayList is part of Java collections and provides more utility methods.
Q198) Two ways to declare arrays in Java?
Answer:
int[] a; // Recommended
int a[]; // Also valid
Q199) Explain public static void main(String[] args)
Answer:
- public: Accessible from anywhere
- static: Can be run without creating an object
- void: Does not return any value
- main: Entry point of the application
- String[] args: Accepts command-line arguments
Q200) What are static members of a class?
Answer: Static members are shared among all instances of the class.
Explanation:
staticvariables belong to the class, not objects.staticmethods can be called using class name directly.- Good for utility or common logic shared across instances.
Q201) What are checked/unchecked exceptions?
Answer:
- Checked exceptions are exceptions that must be either caught or declared in the method signature using
throws. These are checked at compile-time.
Example:IOException,SQLException - Unchecked exceptions are not checked at compile-time and need not be declared.
Example:NullPointerException,ArithmeticException
Q202) What is var-args in a method?
Answer:var-args allows a method to accept zero or more arguments of a specified type.
void print(int... nums) {
for (int n : nums) {
System.out.println(n);
}
}
Q203) What are the restrictions for var-arg parameters?
Answer:
- Var-args must be the last parameter in the method signature.
- Only one var-arg parameter is allowed per method.
Q204) Show how variable length arguments when combined with method overloading might lead to ambiguity.
Answer:
void test(int... a) {}
void test(boolean... b) {}
test(); // Ambiguous, compiler can't decide which method to invoke.
Q205) What is the basic difference between interface and abstract class?
Answer:
- Interfaces support multiple inheritance, abstract classes do not.
- All interface methods are public and abstract by default.
- Abstract class methods can have any access modifier and method bodies.
Q206) Why strings are immutable in Java?
Answer:
- For security (e.g., for ClassLoader paths), thread safety, and performance (e.g., String pooling).
- Once created, string value cannot be changed — any modification returns a new object.
Q207) Is bytecode ever compiled?
Answer:
Yes. JVM uses Just-In-Time (JIT) compiler to compile bytecode to native machine code for better performance during runtime.
Q208) What is the distinguishing feature of Sets?
Answer:
A Set cannot contain duplicate elements.
Q209) What is TreeSet?
Answer:
A TreeSet is a sorted set based on a Red-Black tree.
- Elements are stored in natural ascending order (or using a custom comparator).
- No duplicates allowed.
Q210) What are the methods of Object class?
Answer:
equals()hashCode()toString()wait()notify()notifyAll()getClass()
Q211) Explain toString() method.
Answer:
The toString() method returns a string representation of the object. It is called automatically when an object is printed.
Q212) What is the difference between == and equals() method?
Answer:
==checks reference equality.equals()checks value equality (if overridden properly in the class).
Q213) When are parameters passed by reference and when by value?
Answer:
Java is always pass-by-value.
- For primitives, value is passed.
- For objects, reference value is passed (not reference itself), so original object may be modified.
Q214) Explain “finally” block.
Answer:
The finally block is always executed after try and catch, regardless of whether an exception occurs. It’s used for cleanup activities.
Q215) What is “inner class”?
Answer:
An inner class is a class defined within another class.
- It can access the enclosing class’s members including private ones.
Q216) How can we make garbage collection happen in our code?
Answer:
We can suggest GC using:
System.gc();
Note: It’s a suggestion — not guaranteed to execute immediately
Q217) What are applets?
Answer:
Applets are small Java programs that run in a browser using a Java plugin. Now considered obsolete.
Q218) What is the difference in finally and finalize in Java?
Answer:
Q219) Why is Java platform-independent?
Answer:
Because Java programs compile to bytecode that runs on JVM, which is available on different platforms.
Q220) Which compiler does Java use?
Answer:
Java uses JIT (Just-In-Time) compiler as part of JVM to convert bytecode to native machine code at runtime.
Q221) What is the use of JIT?
Answer:
Improves performance by compiling bytecode to native code only once and caching the result.
Q222) Why is Java secure?
Answer:
- No pointer manipulation.
- Bytecode verification.
- Sandboxed execution model.
- Controlled access via access modifiers and security managers.
Q223) Why is Java not a pure OOP language?
Answer:
Because it supports primitive types like int, float, etc., which are not objects.
Q224) Can we use static public void main()?
Answer:
Yes. Order of static and public doesn’t matter.
Q225) Can we overload the main() method?
Answer:
Yes. You can overload main() method with different parameter lists.
However, the JVM always looks for this signature to start:
public static void main(String[] args)
Q226) What are OOPS concepts?
Answer:
- Encapsulation
- Inheritance
- Abstraction
- Polymorphism
Explanation:
These four core principles of object-oriented programming allow modular, reusable, and secure code.
Q227) What is the use of Encapsulation?
Answer:
Encapsulation hides internal object details from the outside world by using private fields and providing public getter/setter methods.
Explanation:
Like a capsule, data and logic are wrapped inside a class. It improves data security and code maintainability.
Q228) How to stop a class from being inherited?
Answer:
By declaring the class as final.
Explanation:
A final class cannot be subclassed. For example, public final class MyClass {}.
Q229) What is the use of inheritance?
Answer:
Inheritance allows one class (child) to reuse properties and methods from another class (parent).
Explanation:
It supports code reuse and establishes a parent-child relationship between classes.
Q230) How can you achieve polymorphism?
Answer:
- Method Overloading (Compile-time polymorphism)
- Method Overriding (Run-time polymorphism)
Explanation:
Polymorphism allows a method to behave differently based on parameters or object types.
Q231) What is singleton design pattern?
Answer:
It ensures that only one instance of a class exists throughout the application.
Explanation:
Used when a single object needs to coordinate actions across the system (e.g., logging, DB connection).
Q232) What is the use of static variable?
Answer:
A static variable belongs to the class rather than instances and is shared among all objects.
Explanation:
It helps in memory management and maintaining global values.
Q233) What is the class loader?
Answer:
It is a part of JVM that loads class files during runtime.
Explanation:
It loads .class files into memory and assigns the necessary metadata.
Q234) What are exceptions?
Answer:
Exceptions are runtime errors that disrupt the normal flow of execution.
Explanation:
Java handles exceptions through try-catch blocks to ensure graceful failure.
Q235) What are the types of exceptions?
Answer:
- Checked exceptions
- Unchecked exceptions
Explanation:
Checked must be handled or declared, unchecked can be optionally handled.
Q236) What are checked and unchecked exceptions?
Answer:
Checked: Must be handled during compile time (e.g., IOException)
Unchecked: Occur at runtime and are not required to be caught (e.g., NullPointerException)
Q237) What are different checked exceptions?
Answer:
IOException, SQLException, FileNotFoundException
Explanation:
These must be handled explicitly using try-catch or declared using throws.
Q238) How to handle checked exceptions?
Answer:
Using try-catch block or by declaring the exception using throws keyword.
Q239) Can we use try without a catch?
Answer:
Yes, try can be used with finally even without a catch.
Q240) What is the use of finally block?
Answer:
To ensure code is executed after try-catch, whether or not an exception occurred.
Explanation:
Ideal for releasing resources like closing files or DB connections.
Q241) Difference between System.exit() and return?
Answer:
System.exit()stops the JVM immediately.returnexits from the current method but continues program execution (if applicable).
Q242) Can we instantiate an abstract class?
Answer:
No, abstract classes cannot be instantiated.
Q243) Can we extend more than one class?
Answer:
No, Java does not support multiple inheritance with classes.
Q244) Can we implement more than one interface?
Answer:
Yes, a class can implement multiple interfaces.
Q245) Difference between throw and throws?
Answer:
throwis used to explicitly throw an exception.throwsis used in method signatures to declare exceptions that might be thrown.
Q246) What is the superclass for exceptions?
Answer:java.lang.Exception
Q247) What are threads?
Answer:
Threads are independent paths of execution within a program.
Explanation:
They allow multitasking and efficient resource usage.
Q248) Difference between multitasking and multithreading?
Answer:
- Multitasking: Running multiple programs simultaneously.
- Multithreading: Running multiple threads in a single program concurrently.
Q249) How to create threads?
Answer:
- By extending
Threadclass - By implementing
Runnableinterface
Q250) How to start a thread?
Answer:
By calling the start() method of the Thread class.
Q251) What is Java?
Answer:
Java is a high-level, object-oriented, platform-independent, secure, and robust programming language developed by Sun Microsystems.
Q252) What are the major features of Java?
Answer:
- Object-Oriented
- Platform Independent
- Robust
- Secure
- Portable
- Multithreaded
Explanation:
These features make Java versatile, secure, and suitable for a wide range of applications including mobile, web, and enterprise systems.
Q253) What are method overriding and method overloading?
Answer:
- Method Overriding: Occurs when a subclass provides a specific implementation of a method already defined in its parent class. The method signature (name and parameters) must be the same.
- Method Overloading: Occurs within the same class when two or more methods have the same name but different parameter lists (type, number, or order).
Explanation:
- Overriding provides runtime polymorphism.
- Overloading provides compile-time polymorphism.
Q254) What is the difference between Java, C, and C++?
| Feature | C | C++ | Java |
|---|---|---|---|
| Programming Model | Procedural | Object-Oriented | Object-Oriented |
| Inheritance | Not supported | Multiple Inheritance | Interface-based Inheritance |
| Platform Dependency | Platform dependent | Platform dependent | Platform independent (via JVM) |
| Compilation | Compiler | Compiler | Compiler + JVM Interpreter |
| Pointers | Supported | Supported | Not supported |
| Exception Handling | Not available | Supported | Supported |
Explanation:
Java avoids pointers and platform dependency to ensure security and portability.
Q255) What is an abstract class?
Answer:
An abstract class is a class declared using the abstract keyword. It can have both abstract (without body) and concrete methods (with body). It cannot be instantiated.
Explanation:
Used to define a template for subclasses, forcing them to implement the abstract methods.
Q256) What are classes and objects in Java?
Answer:
- Class: A blueprint or template that defines variables and methods.
- Object: A runtime instance of a class.
Explanation:
Objects use class methods and access class variables.
Q257) What is inheritance and how is it done?
Answer:
Inheritance allows a subclass to reuse fields and methods from a superclass.
class Animal {
void sound() { System.out.println("Generic sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}
Explanation:
Promotes code reuse and supports hierarchical classification.
Q258) What are sub classes and inner classes?
Answer:
- Subclass: A class that extends another class.
- Inner Class: A class declared within another class.
Types of inner classes:
- Non-static inner class
- Static nested class
- Local inner class (inside a method)
- Anonymous inner class (no name)
Q259) Differentiate between equals() and == in Java.
Answer:
==: Compares reference (memory address).equals(): Compares the content of objects.
Explanation:
For objects like String, use equals() to compare values. == only checks if they refer to the same memory.
Q260) What are packages in Java?
Answer:
Packages are namespaces that organize classes and interfaces.
Types:
- Built-in:
java.util,java.io, etc. - User-defined: Custom packages created by developers.
Explanation:
Helps avoid naming conflicts and controls access.
Q261) Are there pointers in Java? Why or why not?
Answer:
Java does not support pointers to avoid security risks like illegal memory access and to simplify memory management.
Explanation:
This design choice improves Java’s safety and robustness.
Q262) What are the various access modifiers in Java?
Answer:
| Modifier | Class | Package | Subclass | Everywhere |
|---|---|---|---|---|
| public | ✔ | ✔ | ✔ | ✔ |
| protected | ✔ | ✔ | ✔ | ✘ |
| default | ✔ | ✔ | ✘ | ✘ |
| private | ✔ | ✘ | ✘ | ✘ |
Explanation:
Access modifiers control visibility of classes, methods, and variables.
Q263) What is the difference between local variable and instance variable?
Answer:
- Local variable: Declared inside a method and accessible only within it.
- Instance variable: Declared inside a class, outside methods, and specific to an object.
Explanation:
Local variables are temporary, instance variables persist with the object.
Q264) What are OOPs concepts in Java?
Answer:
- Encapsulation: Data hiding through access modifiers.
- Abstraction: Hiding implementation details using abstract classes/interfaces.
- Inheritance: Reusing code via parent-child relationships.
- Polymorphism: Same method behaving differently in different contexts.
Q265) What are the differences between static and non-static methods in Java?
| Static Method | Non-static Method |
|---|---|
| Belongs to class | Belongs to object |
| Can’t access instance variables | Can access both static and instance vars |
| Doesn’t require object creation | Requires object to invoke |
Q266) Differentiate between StringBuilder and StringBuffer.
| Feature | StringBuilder | StringBuffer |
|---|---|---|
| Thread Safety | Not thread-safe | Thread-safe |
| Synchronization | No | Yes |
| Performance | Faster | Slower |
Explanation:
Use StringBuilder in single-threaded environments and StringBuffer in multi-threaded scenarios.
Q267) Are strings in Java mutable or immutable?
Answer:
Strings in Java are immutable. Once created, their content cannot be changed.
Explanation:
Improves performance and security (especially in multithreaded contexts).
Q268) What is the difference between array and array list?
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Type Support | Primitive & Objects | Objects only |
| Length Retrieval | .length | .size() |
| Add Elements | Use index | Use .add() method |
Q269) What is a copy constructor?
Answer:
A constructor that takes another object of the same class as an argument to copy its data.
class Student {
int age;
Student(Student s) {
this.age = s.age;
}
}
Q270) Differentiate between HashMap and Hashtable in Java.
| Feature | HashMap | Hashtable |
|---|---|---|
| Thread Safety | Not thread-safe | Thread-safe |
| Null Keys/Values | Allows one null key | No null key/value allowed |
| Performance | Faster (non-sync) | Slower (sync) |
| Iterator | Fail-fast | Fail-safe |
Q271) Differentiate between HashSet and TreeSet in Java.
| Feature | HashSet | TreeSet |
|---|---|---|
| Ordering | Unordered | Elements are sorted in natural order |
| Comparison | Uses equals() and hashCode() | Uses compareTo() or Comparator |
| Nulls | Allows one null element | Does not allow null (throws exception) |
| Performance | Faster (constant time operations) | Slower (log(n) time due to tree operations) |
| Implementation | Backed by a HashMap | Backed by a TreeMap |
Q272) What are collections in Java?
Answer: Collections in Java are a framework that provides architecture to store and manipulate a group of objects.
Main interfaces:
ListSetQueueMap
They support operations like searching, sorting, insertion, deletion, etc.
Q273) What are Maps in Java?
Answer: A Map is a key-value pair data structure. It does not allow duplicate keys but allows duplicate values.
Examples:
HashMapTreeMapLinkedHashMap
Q274) What is an exception?
Answer: An exception is an event that disrupts the normal flow of a program. It is an object which is thrown at runtime and can be caught using try-catch
Q275) What are the types of exceptions in Java?
- Checked Exceptions – checked at compile time.
IOException,SQLException,ClassNotFoundException
- Unchecked Exceptions – checked at runtime.
NullPointerException,ArithmeticException,IndexOutOfBoundsException
Q276) What are various exception handling mechanisms?
- try-catch: To catch and handle exceptions.
- finally: Executes code regardless of exception.
- throws: Declares that method may throw exceptions.
- throw: Used to explicitly throw an exception.
Q277) What is a thread in Java?
Answer: A thread is a lightweight subprocess, smallest unit of execution. Java supports multithreading using Thread class or Runnable interface.
Q278) What is synchronization in Java?
Answer: Synchronization ensures that only one thread accesses a resource at a time. Useful in multithreading to avoid data inconsistency.
synchronized void increment() {
count++;
}
Q279) What is serialization in Java?
Answer: Serialization is converting an object into a byte stream for storage or transmission. Deserialization is the reverse process.
Used for saving objects to disk or sending over a network.
Q280) What are final and super keywords?
- final:
- final variable: cannot be reassigned.
- final method: cannot be overridden.
- final class: cannot be extended.
- super:
- Access parent class members/methods/constructors.
Q281) Explain Java and how it enables high performance.
Answer: Java is a platform-independent, object-oriented language. It uses Just-In-Time (JIT) Compiler for converting bytecode to machine code at runtime, which improves performance.
Q282) What is serialization?
Answer: (Duplicate of Q279) Serialization turns an object into byte stream. Helps in saving state or transferring objects.
Q283) What is the Java Virtual Machine (JVM)?
Answer: JVM runs the Java bytecode. It abstracts the underlying platform and provides portability. It handles:
- Memory management
- Security
- Garbage collection
- Multithreading
Q284) Define constructor.
Answer: A constructor initializes an object. It has:
- Same name as class
- No return type
- Can be default or parameterized
Q285) Describe variables and types.
Answer:
- Local variable: Declared inside method/block.
- Instance variable: Belongs to object.
- Static variable: Belongs to class, shared across all instances.
Q286) Define ClassLoader.
Answer: Loads Java classes during runtime.
Types:
- Bootstrap: Loads core classes (
rt.jar) - Extension: Loads from
extdirectory - System/Application: Loads from classpath
Q287) What are Wrapper classes?
Answer: Converts primitive types to objects.
| Primitive | Wrapper |
|---|---|
| int | Integer |
| char | Character |
| double | Double |
Used in collections, autoboxing, etc.
Q288) Define package and its advantages.
Answer: A package groups related classes/interfaces.
Advantages:
- Avoid name conflicts
- Code organization
- Controlled access (via access modifiers)
Q289) Define JIT compiler.
Answer: Just-In-Time compiler compiles bytecode to native code during runtime to improve performance
Q290) What are access modifiers in Java?
Answer: Keywords that restrict visibility.
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| private | ✔ | |||
| default | ✔ | ✔ | ||
| protected | ✔ | ✔ | ✔ | |
| public | ✔ | ✔ | ✔ | ✔ |
Q291) What is garbage collection? Types?
Answer: JVM automatically deletes unreferenced objects.
Collectors:
- Serial
- Parallel
- CMS (Concurrent Mark-Sweep)
- G1 (Garbage First)
Q292) Smallest executable unit in Java?
Answer: A Thread is the smallest unit of execution. JVM starts with the main thread.
Q293) What executes a set of statements always?
Answer: The finally block is always executed, regardless of exception.
Q294) What refers to Multithreading?
Answer: Synchronization ensures safe access to shared resources by multiple threads to avoid race conditions.
Q295) Purpose of final, finally, finalize?
- final: Constant/Prevent override/inherit
- finally: Always executes after try-catch
- finalize(): Called before garbage collection (deprecated in Java 9+)
Q296) Where is different signature used?
Answer: In method overloading, methods have same name but different parameters (signature).
Q297) What is Runtime Polymorphism?
Answer: Achieved via method overriding in inheritance.
class Animal {
void sound() { System.out.println("Generic"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}
Q298) Which method belongs to class?
Answer: A static method belongs to the class, not object.
Q299) Describe object-oriented paradigm.
Answer: A programming style using objects, classes, inheritance, encapsulation, polymorphism, and abstraction.
Q300) What is an object in Java?
Answer: A real-world entity with state (fields) and behavior (methods). It is an instance of a class.
Q301) What is an object-based language?
Answer: Languages that support objects but not full OOP features like inheritance/polymorphism. E.g., JavaScript, VBScript.
Q302) Types of constructors in Java?
- Default Constructor: No arguments.
- Parameterized Constructor: Accepts arguments.
Q303) How to copy object values?
Answer:
- Use constructor
- Use
clone()method (by implementingCloneableinterface)
Q304) What is a Java method?
Answer: A method defines the behavior of an object. It’s invoked to perform an action or return data.
Q305) Describe static variables.
Answer: Belong to the class, not objects. Shared across all instances.
Q306) Define Aggregation.
Answer: A HAS-A relationship between two classes. It represents weak association.
class Engine { }
class Car {
Engine engine; // Aggregation
}
Q307) What is super keyword? Uses?
Answer:
- Access parent class method/variable
- Call parent constructor using
super()
Q308) What is method overriding? Rules and uses.
Rules:
- Same method name/signature
- Parent-child relationship
- Cannot override
finalorprivatemethods
Uses:
- Runtime polymorphism
Q309) What is polymorphism? Types?
Answer: Ability of an object to take multiple forms.
Types:
- Compile-time (Overloading)
- Runtime (Overriding)
Q310) OOPs Concepts in Java
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
- Interface
Q311) What is stored in heap memory?
Answer: All objects and instance variables. String Pool is also part of heap memory.
Q312) How to call one constructor from another?
Answer: Constructor chaining using:
this()– same classsuper()– parent class
Q313) Nature of Java Strings?
Answer: Strings are immutable. Once created, they cannot be changed. Modifying a string creates a new object.
Q314) What is the interface of java.util package? Characteristics?
Answer: Map<K, V> interface in java.util is used to map keys to values.
- No duplicate keys
- One key maps to one value
- Order depends on implementation (
HashMap,TreeMap)
Q315) Describe Java stack memory.
Answer: Stack memory is used for:
- Method calls
- Local variables
- Reference variables
It follows LIFO (Last In First Out). Each thread has its own stack.
Please comment, if you are looking for more Java interview questions and answers.
