Java
OOP, collections, exceptions, multithreading
Java is a platform-independent, object-oriented programming language known for its 'write once, run anywhere' capability. It powers enterprise applications, Android development, and web services. Understanding Java's core concepts—from OOP principles to advanced features like generics and concurrency—is essential for technical interviews and competitive programming.
Key formulas and rules
Key concepts
Object-Oriented Programming (OOP)
Java follows four OOP pillars:
1. Encapsulation: Bundling data and methods, controlling access via private fields with public getters/setters.
2. Inheritance: Creating new classes from existing ones using 'extends', promoting code reuse.
3. Polymorphism: Same method name, different behaviors—achieved through method overloading (compile-time) and overriding (runtime).
4. Abstraction: Hiding implementation details via abstract classes and interfaces.
Inheritance and Access Modifiers
Java supports single inheritance (one parent class). Access modifiers control visibility:
public: Accessible everywhere
private: Only within the class
protected: Within package and subclasses
default (no modifier): Within package only
The 'super' keyword calls parent class methods/constructors. 'this' refers to current instance.
Exception Handling
Java uses try-catch-finally blocks for error handling:
Checked exceptions: Must be handled (IOException, SQLException)
Unchecked exceptions: Runtime errors (NullPointerException, ArrayIndexOutOfBoundsException)
Syntax: try { riskyCode } catch (ExceptionType e) { handle } finally { always executes }
Custom exceptions extend Exception or RuntimeException.
Collections Framework
Core interfaces and implementations:
List: ArrayList (dynamic array), LinkedList (doubly-linked), Vector (thread-safe)
Set: HashSet (unique elements), TreeSet (sorted), LinkedHashSet (insertion order)
Map: HashMap (key-value), TreeMap (sorted by key), LinkedHashMap
ArrayList offers O(1) get but O(n) insert/delete middle. HashMap provides O(1) average for put/get.
Generics
Generics enable type-safe collections and methods:
Class<T>: Type parameter for generic class
<?>: Unbounded wildcard
<? extends T>: Upper bounded (T or subclasses)
<? super T>: Lower bounded (T or superclasses)
Example: ArrayList<String> list = new ArrayList<>(); prevents adding non-String objects at compile time.
Threads and Concurrency
Java provides multithreading via:
Extending Thread class
Implementing Runnable interface (preferred)
Key methods: start(), run(), sleep(ms), join(), yield()
Synchronization prevents race conditions:
synchronized methods
synchronized blocks
ReentrantLock for finer control
The volatile keyword ensures visibility of changes across threads.
Worked examples
Example 1
What is the output?
class Test {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
Output:
false
true
Explanation:
Step 1: s1 == s2 compares references (memory addresses).
Step 2: new String() creates new objects, so s1 and s2 point to different heap locations.
Step 3: Therefore, == returns false.
Step 4: s1.equals(s2) compares content character by character.
Step 5: Both contain 'hello', so equals() returns true.
Example 2
What is the output?
class A {
int x = 10;
void show() { System.out.println(x); }
}
class B extends A {
int x = 20;
void display() { System.out.println(super.x + " " + x); }
public static void main(String[] args) {
B obj = new B();
obj.display();
}
}
Output:
10 20
Explanation:
Step 1: Class B inherits from class A, so B has access to A's members.
Step 2: Both classes declare variable 'x'--this is variable hiding, not overriding.
Step 3: super.x accesses the parent class's x (10).
Step 4: x (or this.x) accesses B's x (20).
Step 5: Therefore, output is '10 20'.
Example 3
What is the output?
public class Test {
public static void main(String[] args) {
try {
int a = 5, b = 0;
int c = a / b;
System.out.println(c);
} catch (ArithmeticException e) {
System.out.println("Division by zero");
} finally {
System.out.println("Finally block");
}
}
}
Output:
Division by zero
Finally block
Explanation:
Step 1: Division a/b where b=0 throws ArithmeticException.
Step 2: try block executes until exception occurs.
Step 3: Control jumps to catch (ArithmeticException e) block.
Step 4: 'Division by zero' is printed.
Step 5: finally block always executes, printing 'Finally block'.
Example 4
What is the output?
import java.util.*;
public class Test {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
set.add(5);
set.add(3);
set.add(5);
set.add(1);
System.out.println(set);
}
}
Output:
[1, 3, 5] (order may vary)
Explanation:
Step 1: HashSet stores unique elements only.
Step 2: set.add(5) adds 5.
Step 3: set.add(3) adds 3.
Step 4: set.add(5) is ignored—duplicate not added.
Step 5: set.add(1) adds 1.
Step 6: HashSet does not maintain insertion order, so output order depends on hash codes.
Step 7: Contains {1, 3, 5} regardless of display order.
Representative solved questions
See the kind of question in this topic before opening the full practice set.
Question 1
What is the output of:
System.out.println(5 + 3 + "Hello");
8Hello
53Hello
Hello8
Compilation error
Answer: A. 8Hello
ExplanationStep 1: 5 + 3 = 8 (integer addition)
Step 2: 8 + "Hello" triggers string concatenation
Step 3: Result is "8Hello"
Output: 8Hello
Sources and review notes
This is an AISEA-authored practice question.
Review status: accepted · Reviewed 2026-08-13 · structure and answer-key checks, editorial quality checks, duplicate screening
Question 2
Which keyword is used to inherit a class in Java?
implements
extends
inherits
super
Answer: B. extends
ExplanationStep 1: 'extends' is used for class inheritance
Step 2: 'implements' is for interfaces
Step 3: 'super' refers to parent class
Answer: extends
Sources and review notes
This is an AISEA-authored practice question.
Review status: accepted · Reviewed 2026-08-13 · structure and answer-key checks, editorial quality checks, duplicate screening
Question 3
What is the default value of an int variable in a class?
0
null
undefined
-1
Answer: A. 0
ExplanationStep 1: Instance variables get default values
Step 2: int defaults to 0
Step 3: Objects default to null
Answer: 0
Sources and review notes
This is an AISEA-authored practice question.
Review status: accepted · Reviewed 2026-08-13 · structure and answer-key checks, editorial quality checks, duplicate screening
Common mistakes and useful habits
- Use .equals() for String content comparison, never == (except String literals).
- Prefer ArrayList over Vector unless thread safety is required—Vector methods are synchronized and slower.
- String is immutable; use StringBuilder for string concatenation in loops to avoid creating many objects.
- Always handle checked exceptions or declare with throws; unchecked exceptions don't require handling.
- For thread safety, consider ConcurrentHashMap over synchronized HashMap for better performance.
- The finally block executes even if return statement is in try/catch—use for cleanup code.
Ready to test your understanding?
Work through 100 questions with explanations after each answer.