Java · 56 topics
What is Java?
Java is a high-level object-oriented, platform-independent programming language.
It uses the JVM to execute bytecode.
Why is Java platform-independent?
Java source code is compiled into bytecode (
.classfiles).The JVM executes that bytecode on different operating systems, allowing the same compiled program to run across platforms.
What is the difference between JDK, JRE and JVM?
Term | Meaning |
|---|---|
JDK | JDK is a full development kit for building Java apps |
JRE | JRE provides the runtime environment and libraries to run them |
JVM | JVM is the engine that executes Java bytecode |
Why is Java not purely object-oriented?
Java is not purely object-oriented because it supports primitive data types (
int,char,boolean,floatanddouble) and allows operations without creating objects.
What is bytecode?
Bytecode is the intermediate code generated by the Java compiler. The JVM executes it.
What is the difference between compiler and interpreter?
A compiler translates an entire program into machine code before it runs.
An interpreter translates and executes code line by line while the program runs.
What are primitive data types in Java?
Primitive data types are basic and predefined value types
Integer:
byte,short,int,longDecimal:
float,doubleCharacter:
charBoolean:
boolean
What is type casting?
Type casting in Java is the process of converting a variable or value from one data type into another.
For primitive data types, Java handles this in two ways: widening (automatic) and narrowing (manual).
Widening converts a smaller data type into a larger data type. Java does this automatically because there is no risk of losing information. Conversion order:
byte→short→char→int→long→float→doubleNarrowing converts a larger data type into a smaller data type. Because data can be truncated or overflow, Java forces you to do this manually by placing the target type in parentheses
()before the value.Conversion order:
double→float→long→int→char→short→byte
int a = 10;
double b = a; // Widening
double x = 10.5;
int y = (int) x; // NarrowingDifference between == and .equals()?
==checks whether two variables store the same primitive value or point to the exact same object in memory..equals()checks whether two objects contain the same data.
What is the static keyword?
statickeyword is a modifier used to specify that a member belongs to the class rather than to a specific object instance.Memory for static members is allocated only once when the class is loaded, and you can access them directly using the class name without creating an instance.
Where
staticCan Be UsedStatic Variables (Class Variables)
Static Methods.
Static Blocks.
class Student {
static String college = "KIET";
}What is the final keyword?
finalkeyword is used to restrict modification, ensuring that a variable cannot be reassigned, a method cannot be overridden, or a class cannot be inherited.
What is a constructor?
A constructor initializes an object.
It has the same name as the class and no return type.
class Student {
Student() {
System.out.println("Object created");
}
}Constructor vs method?
Constructor | Method |
|---|---|
Initializes objects | Performs operations |
Same name as class | Any valid method name |
No return type | Can have a return type |
Called during object creation | Called explicitly |
What is the difference between break and continue?
breakterminates the loop.continueskips the current iteration.
What is a wrapper class?
A wrapper class is a built-in class in the java.lang package that wraps a primitive data type into an object.
Every one of Java's eight primitive types has a matching wrapper class.
Examples:
Integer,Double,Character,Boolean.
What are autoboxing and unboxing?
Autoboxing and unboxing are automatic conversions performed by the Java compiler between primitive data types and their corresponding wrapper classes.
Introduced in Java 5, these features eliminate manual conversion boilerplate so primitives can seamlessly interact with object-based APIs and collections.
Feature | Autoboxing | Unboxing |
|---|---|---|
Direction | Primitive → Wrapper Object (e.g., | Wrapper Object → Primitive (e.g., |
int a = 10;
Integer obj = a; // Autoboxing
Integer x = 20;
int b = x; // UnboxingWhat are the four pillars of OOP?
Encapsulation
Inheritance
Polymorphism
Abstraction
What is encapsulation?
Encapsulation means wrapping data and methods into a single unit and restricting direct access to data using access modifiers.
Key benefits: It protects internal state from invalid changes, decouples code and makes systems easier to maintain.
Ex: A Car's Driving Controls
Private Data: The engine, fuel injection and transmission gears are enclosed under the hood.
Public Methods: As a driver, you only use public controls - the steering wheel, accelerator, and brake pedals which safely manage the engine's internal state without letting you accidentally break the mechanics.
class Student {
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}What is inheritance?
Inheritance allows one class to acquire the properties and methods of another class using
extends.It establishes an IS-A relationship, letting you reuse common code instead of rewriting it from scratch.
Type | Structure | Example |
|---|---|---|
Single | One child class extends one parent class. |
|
Multilevel | A chain of inheritance of more than 2 classes. |
|
Hierarchical | Multiple child classes inherit from the same parent class. |
|
Multiple (Interfaces) | Java does not support multiple inheritance, but it supports multiple inheritance through interfaces. |
|
Hybrid (Interfaces) | A mix of class inheritance and multiple interfaces. |
|
Ex: Family Traits (Biological Inheritance)
Parent -> Child: Just as a child naturally inherits traits like eye color or height from their parents while developing their own distinct personality and skills, a Java subclass inherits existing attributes and behaviors from its superclass while adding its own methods.
# Parent class (Superclass)
class Vehicle {
String brand = "Tata";
void startEngine() {
System.out.println("Engine started.");
}
}
# Child class (Subclass) inherits from Vehicle
class Car extends Vehicle {
int doors = 4;
void honk() {
System.out.println(brand + " car honks: Beep beep!");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.startEngine(); # Inherited from Vehicle
myCar.honk(); # Defined in Car
System.out.println("Doors: " + myCar.doors);
}
}
What is polymorphism?
Polymorphism means one interface or method name can have multiple forms of behaviour.
Two types:
Compile-time polymorphism: Method overloading.
Runtime polymorphism: Method overriding.
What is method overloading?
Multiple methods have the same name but different parameter lists.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}What is method overriding?
A child class provides its own implementation of a method inherited from its parent class.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}Overloading vs overriding?
Overloading | Overriding |
|---|---|
Same method name | Same method signature |
Different parameters | Same parameters |
Usually same class | Parent-child relationship |
Compile-time polymorphism | Runtime polymorphism |
What is abstraction?
Abstraction hides implementation details and exposes essential functionality.
It is achieved using abstract classes and interfaces.
Abstract class | Interface |
|---|---|
Uses | Uses |
Can have constructors | Cannot have constructors |
Can have instance variables | Fields are implicitly public static final |
Can have abstract and concrete methods | Can have abstract, default, static and private methods (depending on Java version) |
A class extends one class | A class can implement multiple interfaces |
What is an abstract method?
An abstract method is a method declared using the
abstractkeyword and without a body (no curly braces {} or implementation code), ending with a semicolon instead.
abstract class Animal {
abstract void sound();
}What is the this keyword?
thisrefers to the current object.Main Uses of
thisResolve Variable Shadowing. When a constructor or setter parameter has the exact same name as an instance variable,
this.variabletells Java you mean the object's field rather than the local parameter.Constructor Chaining (
this()). You can call one overloaded constructor from another inside the same class usingthis(...)to avoid duplicating initialization code.Pass the Current Object as an Argument.
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println("ID: " + this.id);
System.out.println("Name: " + this.name);
}
public static void main(String[] args) {
Student s = new Student(101, "Geeks");
s.display();
}
}What is the super keyword?
superrefers to the immediate parent class and is used to access parent constructors, methods and fields.
class Person {
String name = "Geeks";
}
class Student extends Person {
String name = "Student";
void display() {
System.out.println("Child Name: " + this.name);
System.out.println("Parent Name: " + super.name);
}
public static void main(String[] args) {
Student s = new Student();
s.display();
}
}What is a package in Java?
A package groups related classes and interfaces to organize code and avoid naming conflicts.
What are access modifiers?
Modifier | Accessibility |
|---|---|
private | Same class |
default | Same package |
protected | Same package + subclasses |
public | Everywhere accessible |
Can we override a static method?
No. Static methods are hidden, not overridden, because they belong to the class.
Can constructors be inherited or overridden?
No. Constructors are not inherited and cannot be overridden. However, constructors can be overloaded.
Constructors can be overloaded by defining multiple constructors within the same class that share the class name and have no return type, but differ in their parameter lists.
What is the diamond problem?
The diamond problem is an ambiguity in object-oriented programming (OOP) that happens when a class inherits from two parent classes that both share the same grandparent class.
When mapped out, this four-class hierarchy forms a diamond shape
What is a String in Java?
A String is an object representing a sequence of characters. Strings are immutable in Java.
String s = "Hello";
s.concat(" World");
System.out.println(s); # Hello. The original String does not change.Why are Strings immutable?
Improves security.
Makes String objects thread-safe. "Makes String objects thread-safe" means multiple threads can read and use the same
Stringobject simultaneously without corrupting its data or causing errors.
Makes hashing predictable, useful for HashMap keys.
Difference between String, StringBuilder and StringBuffer?
Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
Mutable | No | Yes | Yes |
Thread-safe | Immutable | No | Yes, synchronized methods |
Performance for repeated changes | Poor | Fast | Slower than StringBuilder |
What is the difference between new String() and String literals?
Feature |
|
|
|---|---|---|
Memory Location | Stored in the String Constant Pool. | Stored directly in Heap memory, outside the pool. |
Object Creation | Reuses an existing object if the exact text is already in the pool. | Always forces Java to create a brand-new object in memory. |
Performance | Faster and saves memory by avoiding duplicate objects. | Slower and uses extra memory. |
| Two identical literals return | Returns |
String a = "Java";
String b = new String("Java");
System.out.println(a == b); # false
System.out.println(a.equals(b)); # trueHow do you reverse a String in Java?
The cleanest and fastest way to reverse a
Stringin Java is to use the built-inreverse()method from theStringBuilderclass.Because
Stringobjects are immutable, Java does not include a.reverse()method directly onString
String s = "hello";
String reversed = new StringBuilder(s).reverse().toString();
System.out.println(reversed); # ollehHow do you check whether a String is a palindrome?
public class Main {
public static void main(String[] args) {
String s = "madam";
int left = 0, right = s.length() - 1;
boolean palindrome = true;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
palindrome = false;
break;
}
left++;
right--;
}
System.out.println(palindrome);
}
}What is the difference between equals() and equalsIgnoreCase()?
equals()performs a case-sensitive comparison of two strings.equalsIgnoreCase()compares their text without caring about uppercase or lowercase letters.
String s1 = "Hello";
String s2 = "hello";
String s3 = "Hello "; # Has a trailing space
System.out.println(s1.equals(s2)); # false (H vs. h)
System.out.println(s1.equalsIgnoreCase(s2)); # true (ignores capitalization)
System.out.println(s1.equalsIgnoreCase(s3)); # false (extra space still counts)
What is the difference between substring() and subSequence()?
Both extract a portion of a character sequence.
substring()returns a String, whilesubSequence()returns aCharSequence.
String text = "Hello World";
# 1. Returns a String
String sub1 = text.substring(0, 5); # "Hello"
System.out.println(sub1.toUpperCase()); # Works directly -> "HELLO"
# 2. Returns a CharSequence
CharSequence sub2 = text.subSequence(0, 5); // "Hello"
sub2.toUpperCase(); # Compile error! CharSequence does not have toUpperCase()
System.out.println(sub2.toString().toUpperCase()); # Works after converting -> "HELLO"
What is String tokenization?
String tokenization is the process of breaking a large string into smaller, meaningful pieces called "tokens" using a delimiter.
A delimiter is one or more characters used to mark the boundary between separate pieces of data in a string, file, or data stream. Think of it as a "divider" that tells a program where one piece of information ends and the next begins.
String date = "2026-11-21";
String[] parts = date.split("-"); # "-" is the delimiter
# Result: ["2026", "11", "21"]What is the Java Collections Framework?
It is a collection of interfaces and classes in the
java.utilpackage for storing, organizing and manipulating objectsMain interfaces:
List
Set
Queue
Deque
Map
Difference between List, Set and Map?
List | Set | Map |
|---|---|---|
Allows duplicates | No duplicate elements | Unique keys |
Maintains order depending on implementation | Depends on implementation | Stores key-value pairs |
Index-based access | No index-based access | Key-based access |
ArrayList vs LinkedList?
ArrayList | LinkedList |
|---|---|
|
|
Fast random access | Slow random access |
Insertions in the middle can require shifting | Insertion in the middle is efficient. |
Access by Index: Fast - O(1) | Access by Index: Slow - O(n) |
HashSet vs TreeSet?
HashSet: Stores unique elements without guaranteeing iteration order.
TreeSet: Stores unique elements in sorted order.
HashMap vs Hashtable?
HashMap | Hashtable |
|---|---|
|
|
Allows one | Does not allows |
Not synchronized | Synchronized (thread-safe; locks the entire map on every method call). |
Generally faster | Generally slower |
How does HashMap work internally?
HashMap stores data in key-value pairs.
It calculates the hash code of the key.
It uses the hash to identify a bucket.
It stores the entry in that bucket.
If collisions occur, multiple entries share the bucket.
In modern Java implementations, heavily collided buckets can be converted into balanced trees under suitable conditions.
What is a Hash Collision?
When two different keys generate the same bucket index, a collision occurs.
What is the difference between HashMap and TreeMap?
HashMap does not guarantee sorted order.
TreeMap stores keys in sorted order.
HashMap generally provides average O(1) operations.
TreeMap generally provides O(log n) operations.
Difference between Collection and Collections?
Collectionis an interface.Collectionsis a utility class containing methods such assort(),reverse()andshuffle().
What is an Iterator?
An Iterator is used to traverse elements in a collection.
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}What is Comparable vs Comparator?
Comparable defines the natural ordering of objects using
compareTo().Comparator defines custom ordering using
compare().
What is a Queue?
A
Queueis a linear data structure and an interface injava.utilpackage that follows the First-In, First-Out (FIFO) principle.New items are added to the back (tail) of the queue, and items are removed from the front (head).
Common implementations include
LinkedListandPriorityQueue.
What is PriorityQueue?
A PriorityQueue processes elements according to priority. By default, Java's PriorityQueue places the smallest element at the head.
Think of it like a hospital emergency room: patients are treated based on the severity of their condition, not who walked through the door first.
What is an exception?
An exception is an event that disrupts the normal execution of instructions.
Instead of letting the entire program crash abruptly, Java wraps the error details (such as the error name, description, and program state) into an exception object.
What is the difference between Error and Exception?
Errors are severe, system-level failures that an application cannot recover from. Exceptions are application-level issues that disrupts the normal execution of instructions.
Checked exceptions | Unchecked exceptions |
|---|---|
Checked at compile time | Not checked at compile time |
Must be caught or declared | Catching or declaring is optional |
IOException, SQLException | NullPointerException, ArithmeticException |
Difference between throw and throws?
throwexplicitly throws an exception. Immediately halts current execution and transfers control to acatchblock. Can throw only one exception at a time.throwsdeclares that a method might produce an exception. Does not execute anything. Can declare multiple exceptions separated by commas.
public void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18.");
}
}
void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Not eligible");
}
}What is try-catch?
try,catchandfinallyare three code blocks used together to handle runtime exceptions safely so your program does not crash unexpectedly.try(The risky code): You wrap code that might cause an exception inside this block. If an error occurs, execution stops immediately and jumps to thecatchblock.catch(The safety net): This block runs only if a specific exception occurs in thetryblock. It lets you log the error, show a user-friendly message, or recover smoothly.finally(The cleanup crew): This block always runs after thetryandcatchblocks finish whether an exception was thrown or not. Developers use it to release resources like closing open files or database connections.
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}Q65. What is finally?
The finally block generally executes whether an exception occurs or not. It is commonly used for cleanup.
Q66. Can we have multiple catch blocks?
Yes. We can handle different exception types using multiple catch blocks. More specific exceptions must appear before broader exceptions.
Q67. What is a custom exception?
An exception created by the programmer according to application requirements.
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}Q68. Difference between final, finally and finalize?
Keyword | Meaning |
|---|---|
final | Restricts reassignment, overriding or inheritance |
finally | Exception-handling cleanup block |
finalize() | Deprecated finalization mechanism; not reliable for resource cleanup |
6. Multithreading
Q69. What is a thread?
A thread is a lightweight unit of execution within a process. Multiple threads can execute concurrently.
Q70. How can you create a thread in Java?
Two common approaches:
Extend the Thread class.
Implement the Runnable interface.
class MyTask implements Runnable {
public void run() {
System.out.println("Thread running");
}
}
class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyTask());
t.start();
}
}Q71. Difference between start() and run()?
start()starts a new thread and eventually invokesrun()on that thread.run()called directly executes like an ordinary method on the current thread.
Q72. What is synchronization?
Synchronization controls access to shared resources so that multiple threads do not cause inconsistent results.
synchronized void increment() {
count++;
}Q73. What is a deadlock?
A deadlock occurs when two or more threads wait indefinitely for resources held by one another.
Q74. What is the difference between process and thread?
Process | Thread |
|---|---|
Independent executing program | Execution unit within a process |
Has its own memory space | Shares process memory |
More resource-intensive | Usually lighter |
Communication can be more expensive | Shared-memory communication is easier |
Q75. What is the volatile keyword?
It ensures visibility of changes to a variable across threads. It does not make compound operations like count++ atomic.
Q76. What is the difference between sleep() and wait()?
sleep() | wait() |
|---|---|
Defined in Thread | Defined in Object |
Does not release held monitors | Releases the monitor while waiting |
Used for timed pauses | Used for inter-thread coordination |
Does not require synchronized context | Must own the object's monitor |
Q77. What are the thread lifecycle states?
NEW
RUNNABLE
BLOCKED
WAITING
TIMED_WAITING
TERMINATED
7. Java 8 features
Q78. What are the major features introduced in Java 8?
Lambda expressions
Functional interfaces
Stream API
Default methods in interfaces
Static interface methods
Optional class
Method references
New Date and Time API
Q79. What is a Lambda expression?
A lambda expression is a concise way of implementing a functional interface.
(a, b) -> a + bQ80. What is a Functional Interface?
An interface containing exactly one abstract method. It can have default and static methods.
@FunctionalInterface
interface MyInterface {
void display();
}Q81. What is the Stream API?
Stream API is used to process collections of data in a functional style.
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
nums.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);Output: 2 4
Q82. Difference between map() and filter()?
map()transforms elements.filter()selects elements based on a condition.
Q84. What is a method reference?
A shorter way of referring to an existing method using ::.
nums.forEach(System.out::println);Q85. What is a default method in an interface?
A method with an implementation inside an interface, declared using the default keyword.
8. JVM, Memory Management and Garbage Collection
Q86. What is JVM architecture?
The major components include:
Class Loader
Runtime Data Areas
Execution Engine
Garbage Collector
JNI (Java Native Interface)
Q87. What is the difference between Stack and Heap memory?
Stack | Heap |
|---|---|
Stores method frames and local variables/references | Stores objects and arrays |
Each thread has its own stack | Shared across threads |
Automatically managed as methods enter/return | Managed by garbage collection |
Generally faster allocation | Used for dynamic object allocation |
Q88. What is Garbage Collection?
Garbage Collection automatically reclaims heap memory occupied by objects that are no longer reachable.
Q89. Can we force Garbage Collection?
No. We can request it using System.gc(), but JVM is not guaranteed to execute it immediately.
Q90. What is ClassLoader?
A ClassLoader loads Java class files into JVM memory when required.
Q91. What is JIT Compiler?
JIT stands for Just-In-Time compiler. It compiles frequently executed bytecode into native machine code to improve performance.
Q92. What is OutOfMemoryError?
It occurs when the JVM cannot allocate more memory for an object because sufficient memory is unavailable.
Q93. What is StackOverflowError?
It generally occurs when a thread's stack becomes exhausted, commonly due to excessive or infinite recursion.