0% found this document useful (0 votes)
3 views16 pages

Core Java Interview Q

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Core Java Interview Q

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Core Java Interview Q&A (Expanded, Simple English)

1. What are the features of Java?

 Object-Oriented → everything is based on objects.


 Platform Independent → “write once, run anywhere.”
 Secure → no pointers, automatic memory handling.
 Robust → handles errors with exceptions, garbage collection.
 Multithreaded → can run many tasks at the same time.
 Portable → runs on any system with JVM.

2. What is JDK, JRE, and JVM?

 JDK (Java Development Kit): For writing and compiling Java code.
 JRE (Java Runtime Environment): For running Java programs (JVM +
libraries).
 JVM (Java Virtual Machine): The engine that actually executes Java
bytecode.

👉 Think of it like this:


JDK = tools to build a house,
JRE = house to live in,
JVM = workers who do the job inside.

3. Why is Java platform independent?

Because Java is compiled into bytecode, not machine code. This bytecode can
run on any operating system that has a JVM.

4. Explain OOP concepts in Java.

 Encapsulation: Keeping data and methods together (like a capsule).


 Inheritance: One class can reuse properties of another.
 Polymorphism: One method behaves differently in different cases.
 Abstraction: Show only what’s needed, hide the details.
5. Difference between == and .equals()?

 == → checks if two references point to the same object.


 .equals() → checks if two objects have the same content.

6. What is autoboxing and unboxing?

 Autoboxing: Java automatically converts a primitive to a wrapper.


 Unboxing: Wrapper class automatically converted to primitive.

👉 Example:

Integer a = 5; // autoboxing (int → Integer)


int b = a; // unboxing (Integer → int)

Concept Meaning Example


Primitive → Wrapper Integer i = new
Boxing Integer(5);
(manual)
Primitive → Wrapper Integer i = 5;
Auto-Boxing
(automatic)
Wrapper → Primitive int x = i.intValue();
Unboxing
(manual)
Auto- Wrapper → Primitive int x = i;
Unboxing (automatic)

7. How does Java manage memory?

 Stack: Stores methods and local variables.


 Heap: Stores objects.
 Garbage Collector: Deletes unused objects to free memory.

8. What is the main() method?

It’s the starting point of a Java program. JVM looks for it first.

public static void main(String[] args) { }


9. Constructor vs Method?

 Constructor: Special method to create and initialize an object.


 Method: Performs an action.
 Constructors have no return type and same name as class.

10. Can we overload constructors?

👉 Yes, by changing parameters.

class Student {
Student() { }
Student(String name) { }
}

11. Difference between break, continue, and return?

 break → stops the loop completely.


 continue → skips current step and goes to next.
 return → exits from the method.

12. Enhanced For Loop?

A simpler way to loop over arrays or collections.

for (String s : list) {


System.out.println(s);
}

13. Primitive vs Wrapper classes?

 Primitive: Simple, fast (int, char, boolean).


 Wrapper: Object versions (Integer, Character, Boolean). Used in
collections.
14. What are static variables and methods?

 Static variable: Same value shared by all objects.


 Static method: Belongs to the class, can be called without creating an
object.

15. String vs StringBuilder vs StringBuffer?

 String: Immutable (cannot change once created).


 StringBuilder: Mutable, faster, not thread-safe.
 StringBuffer: Mutable, slower, but thread-safe.

16. Why are Strings immutable?

 Security (used in class loaders).


 Saves memory (String Pool reuse).
 Thread-safe.

17. What is String Pool?

 A special area in heap where Java stores all string literals.


 If two strings are the same, they point to the same pool object.

18. Array vs ArrayList?

 Array: Fixed size, fast.


 ArrayList: Dynamic, can grow/shrink, part of Collections.

19. What are Generics in Java?

Collections in Java
 A Collection is a framework (interfaces + classes) that provides
architecture to store and manipulate groups of objects.
 It is part of java.util package.
 Why? Because arrays in Java are fixed in size → Collections are
dynamic, flexible, and come with built-in methods.

Generics allow you to define classes/methods with a type parameter for type
safety.

List<Integer> numbers = new ArrayList<>();

"Generics provide type safety and eliminate explicit casting, making collections
safer and more readable."

20. Difference between List, Set, and Map?

 List: Ordered, allows duplicates, index-based access..


 Set: No duplicates, unordered, no index.
 Map: Key-value pairs.

21. HashMap vs TreeMap vs LinkedHashMap?

 HashMap: Fast lookup, no order.


 TreeMap: Keys sorted.
 LinkedHashMap: Keeps insertion order.
22. Fail-Fast vs Fail-Safe Iterators?

 Fail-Fast: Throws error if collection is modified while iterating (ArrayList).


 Fail-Safe: Works on a copy, so no error (ConcurrentHashMap).

Collection vs Collections in Java

Feature Collection Collections


Type Interface Utility (Helper) Class
Package java.util.Collection java.util.Collections
Root interface of the
Provides static utility methods to
Collection Framework
Purpose operate on collections (sorting,
(represents a group of
searching, synchronizing, etc.)
objects)
List, Set, Queue extend Collections.sort(list),
Examples
Collection Collections.max(list)
You cannot create an object You cannot create an object of
Instantiation
of Collection directly Collections (all methods are static)
A blueprint (contract) for A toolbox (ready-made methods)
Analogy
data structures for working with collections

🔹 Extra Simple Qs (Common in Interviews)

Q: What is this keyword in Java?


this is a reference to the current object. It is used to resolve naming conflicts,
call other constructors, pass current object as an argument, or return the current
object itself.”

Q: What is super keyword in Java?


 Always refers to the immediate parent class.

 Can be used for:

1. Accessing parent variables.


2. Calling parent methods.
3. Calling parent constructors.

 Constructor call with super(...) must be the first statement inside child
constructor.

Q: What is method overloading vs overriding?

 Overloading: Same method name, different parameters (compile-time


polymorphism).
 Overriding: Child class changes parent’s method (runtime
polymorphism).

Q: Can Java support multiple inheritance?


👉 Not with classes, but possible with interfaces.

Q: Difference between checked and unchecked exceptions?

 Checked: Must be handled at compile time (IOException).


 Unchecked: Runtime errors (NullPointerException).

Q.Instance variable and local variable

Feature Instance Variable Local Variable


Where Inside a class, but outside Inside a method, constructor,
declared methods/constructors or block
Exists only inside the
Scope Belongs to the object (instance) of the class
method/block where defined
Gets a default value (e.g., 0 for int, null for Must be initialized before use
Default value
objects) if not initialized (no default value)
Access Accessed using object reference (obj.var) Accessed directly inside method
Memory Stored in the stack (with
Stored in the heap (with the object)
location method execution)
Lives only while method is
Lifetime Lives as long as the object exists
running

Q.arguments and parameters

“Parameters are variables defined in the method signature, while arguments


are the actual values passed to those parameters when the method is called.”
Q.final keyword in Java

The final keyword is a non-access modifier used to apply restrictions on


variables, methods, and classes.

Use on Effect

Variable Value cannot be changed (constant)

Method Cannot be overridden

Class Cannot be inherited

Q.static keyword

The static keyword in Java means the member belongs to the class rather than
objects.
🔹 static variables are shared across all objects, static methods can be called
without creating an object, and static blocks run once when the class is loaded.

Q🔑 Difference between final, finally, and finalize

Keyword Meaning Example / Use

A modifier used with variables (constant),


final methods (no overriding), and classes (no final int MAX = 100;
inheritance).

A block in exception handling that always try { } catch(Exception


finally
executes (whether exception occurs or not). e) { } finally { }

A method in Object class called by the


protected void finalize()
finalize() Garbage Collector before destroying an
{}
object.

Enum in Java

🔹 Definition:
An enum (enumeration) in Java is a special data type that represents a group
of named constants (fixed set of values).
🔹 Introduced in: Java 5

✅ Key Points

 Declared using the enum keyword.

 Each constant is public, static, and final by default.

 Useful for things that have a fixed set of values (e.g., days, directions,
status codes).

 Can have fields, methods, and constructors.

Object-Oriented Programming (Intermediate)

Q1) What is method overloading and overriding?

 Overloading: Same method name, but different parameters (compile-


time).

 Overriding: Subclass provides its own implementation of a superclass


method (runtime).

👉 Example:

class Parent {

void show(int x) {}

class Child extends Parent {

@Override

void show(int x) {} // overriding

void show(double y) {} // overloading


}

Q2) What is runtime polymorphism?

It’s when the method call is resolved at runtime, not compile-time.


👉 Happens due to method overriding.

Q3) What is the super keyword?

 Refers to parent class members (fields, methods, constructors).

 Used to call parent constructor or overridden methods.

Q4) Difference between this and super?

 this → current class object.

 super → immediate parent class.

Q5) Abstract class vs Interface?

 Abstract class: Can have state (fields), constructors, and both abstract +
concrete methods.

 Interface: Contract with only abstract methods (till Java 7), but from
Java 8 onwards, supports default and static methods.

Q6) Can we have default methods in interfaces? Why?

👉 Yes (Java 8). They allow new methods to be added without breaking old
implementations → backward compatibility.

Q7) What is the diamond problem? How does Java solve it?
 Diamond problem: Ambiguity in multiple inheritance (which parent’s
method to use?).

 Java solution: Classes don’t support multiple inheritance, only


interfaces.
If two interfaces have same default method, you must override and
resolve manually.

✅ Exception Handling

Q8) Checked vs Unchecked Exceptions?

 Checked: Checked at compile time (IOException, SQLException).

 Unchecked: Occur at runtime (NullPointerException,


ArithmeticException).

Q9) What is finally block? When is it not executed?

 Finally: Runs cleanup code (like closing resources).

 Not executed if JVM exits (System.exit()) or fatal error occurs.

Q10) Can try block exist without catch?

👉 Yes, if there is a finally block.

Q11) Difference between throw and throws?

 throw: Used to actually throw an exception.

 throws: Declares which exceptions a method might throw.

✅ Multithreading and Concurrency

Q12) What is a thread?


A lightweight process for multitasking in Java.

Q13) Runnable vs Thread?

 Runnable: Defines a task separately, better for reusability.

 Thread: Extends Thread class, less flexible.

👉 Best practice → use Runnable or ExecutorService.

Q14) Thread states?

 New → Runnable → Running → Waiting/Blocked → Terminated.

Q15) What is a thread-safe class? Is HashMap thread-safe?

 Thread-safe: Can be safely used by multiple threads.

 HashMap is NOT thread-safe. Use ConcurrentHashMap instead.

Q16) How does synchronized work?

 Ensures only one thread at a time can access the block/method.

 Prevents race conditions.

Q17) What is volatile keyword?

 Ensures changes to a variable are visible to all threads immediately.

 Prevents caching issues.

Q18) Difference between wait() and sleep()?

 wait() releases the lock → used for inter-thread communication.


 sleep() just pauses execution, does not release lock.

Q19) Thread starvation vs Deadlock?

 Starvation: Thread waits too long because resources always taken by


others.

 Deadlock: Two or more threads waiting forever on each other’s locks.

Q20) What are Callable and Future?

 Callable: Like Runnable but can return a value.

 Future: Stores result of a Callable for later use.

Q21) What is ExecutorService?

 Manages thread pools and executes tasks asynchronously.

 Better than manually creating threads.

Q22) CompletableFuture?

 Java 8 feature for asynchronous programming with callbacks.

 Example: chain tasks (thenApply, thenAccept).

Q23) ForkJoinPool?

 Special thread pool for divide-and-conquer parallelism.

 Used in parallel streams.

Q24) ReentrantLock vs synchronized?

 ReentrantLock: More flexible (tryLock, fairness policy).


 synchronized: Simpler but less powerful.

Q25) What are atomic variables?

Classes like AtomicInteger allow lock-free thread-safe operations using CAS


(compare-and-swap).

✅ Java 8+ Features

Q26) What is a functional interface?

 An interface with exactly one abstract method (e.g., Runnable).

Q27) What is @FunctionalInterface annotation?

Ensures compiler checks it has only one abstract method.

Q28) Lambda expressions?

 Short syntax for functional interfaces.

Runnable r = () -> System.out.println("Hello");

Q29) Method references?

 Shorthand for lambdas → System.out::println.

Q30) Java Streams?

 API for processing data in a functional style (filter, map, reduce).

Q31) Difference between map() and flatMap()?

 map(): Transform each element.


 flatMap(): Transform + flatten nested collections.

Q32) What is lazy evaluation in Streams?

 Streams don’t execute until a terminal operation (collect, forEach).

Q33) What is Optional?

 A container object to avoid null.

 Use isPresent(), orElse(), map().

Q34) Old Date API vs java.time API?

 Old: mutable, not thread-safe.

 New (Java 8): immutable, thread-safe, better design.

✅ Memory Management & Performance

Q35) Memory areas in JVM?

 Heap → Objects.

 Stack → Method calls, local vars.

 Method Area → Class-level data.

 Code Cache & Metaspace.

Q36) How does Garbage Collection work?

 JVM automatically removes unreachable objects from heap.

Q37) Strong, Weak, Soft, Phantom references?


 Strong: Normal reference (not collected).

 Weak: GC can collect anytime (used in caches).

 Soft: Collected only when memory is low.

 Phantom: Used for cleanup, collected next GC cycle.

Q38) What is a memory leak?

When unused objects are still referenced, so GC cannot clean them.

Q39) How to analyze OutOfMemoryError?

 Take heap dump.

 Use tools like JVisualVM, Eclipse MAT.

 Fix by optimizing data structures.

Q40) Java Profilers?

Tools like:

 JVisualVM (free, bundled with JDK).

 YourKit, JProfiler (commercial).

 Used to track CPU, memory usage, threads.

You might also like