Core Java Interview Questions & Answers: OOPs, Data Structures & Algorithms
This extensive guide provides comprehensive answers to 300+ frequently asked Core Java interview questions, focusing on fundamental concepts and object-oriented programming (OOPs). We cover Java basics, including the JVM, JDK, JRE, and key features like platform independence and multithreading. This resource includes detailed explanations and Java code examples for common programming tasks such as calculating sums, powers, and finding prime factors. We also delve into OOP principles (inheritance, polymorphism, encapsulation, abstraction), constructors, and the differences between abstract classes and interfaces. Prepare for in-depth Java interviews with this invaluable resource.
300 Core Java Interview Questions (Set 1): Fundamentals
This section covers frequently asked Core Java interview questions, categorized for easier understanding. Answers are concise and to the point.
Core Java Basics
What is Java?
Java is a versatile, object-oriented programming language known for its platform independence ("write once, run anywhere"), robustness, security, and multithreading capabilities. Developed by James Gosling at Sun Microsystems (now owned by Oracle), Java is used to build a wide range of applications, from desktop software to mobile apps and large-scale enterprise systems.
C++ vs. Java: Key Differences
Feature | C++ | Java |
---|---|---|
Platform Independence | Platform-dependent | Platform-independent (write once, run anywhere) |
Primary Use | Systems and application programming | Application programming (desktop, web, mobile, enterprise) |
Pointers | Direct pointer support | Limited/no direct pointer support |
Multiple Inheritance (Classes) | Supported | Not supported directly (achieved through interfaces) |
Operator Overloading | Supported | Not supported |
goto Statement | Supported | Not supported |
Memory Management | Manual memory management | Automatic garbage collection |
Thread Support | Requires libraries. | Built-in thread support. |
Key Features of Java
- Simple: Relatively easy to learn and use.
- Object-Oriented: Organizes code around objects (data and methods).
- Portable: "Write once, run anywhere" due to the JVM.
- Platform Independent: Runs on any platform with a JVM.
- Secure: Features like exception handling and memory management enhance security.
- Robust: Strong memory management and exception handling minimize errors.
- Architecture Neutral: Code runs on different architectures without modification.
- Interpreted: Bytecode is executed by the JVM.
- High-Performance: Uses JIT (Just-In-Time) compilation for improved performance.
- Multithreaded: Supports concurrent execution of multiple threads.
- Distributed: Facilitates distributed applications.
- Dynamic: Supports runtime class loading and other dynamic features.
Java Virtual Machine (JVM)
The JVM (Java Virtual Machine) is a runtime environment that executes Java bytecode. It's platform-specific; different JVMs exist for different operating systems and hardware architectures. The JVM provides platform independence for Java applications.
JDK, JRE, and JVM
JDK (Java Development Kit) | JRE (Java Runtime Environment) | JVM (Java Virtual Machine) |
---|---|---|
Includes tools for developing Java applications (compiler, debugger, etc.) and the JRE. | Includes the JVM and necessary libraries for running Java applications. | The runtime engine that executes Java bytecode; it's a specification, not a physical entity. |
JVM Memory Areas
- Method Area: Stores per-class structures.
- Heap: Allocates memory for objects.
- Stack: Stores method call frames (local variables, partial results).
- Program Counter Register: Tracks currently executing instruction.
- Native Method Stack: For native methods.
Just-In-Time (JIT) Compiler
The JIT compiler improves Java's performance by compiling frequently used bytecode into native machine code at runtime.
What is a Platform?
In computing, a platform refers to the hardware or software environment on which a program runs. Java's platform independence means that Java programs can run on any system with a compatible JVM.
Core Java Basics
Java Platforms
A platform is the environment where software runs. Java's platform independence comes from its use of the Java Virtual Machine (JVM). Other platforms might be hardware-based.
Java Platform vs. Other Platforms
Java Platform | Other Platforms |
---|---|
Software-based; runs on top of other platforms. | Can be hardware or software-based. |
Java's "Write Once, Run Anywhere"
Java achieves platform independence through bytecode. The Java compiler translates source code (.java
files) into bytecode (.class
files), an intermediate representation that runs on the JVM (Java Virtual Machine), regardless of the underlying operating system.
ClassLoaders in Java
Classloaders are essential for loading class files into the JVM. Java has three built-in classloaders:
- Bootstrap ClassLoader: Loads core Java classes.
- Extension ClassLoader: Loads extensions from the
$JAVA_HOME/jre/lib/ext
directory. - System/Application ClassLoader: Loads classes from the classpath.
Valid Java File Names
A .java
file can have a name that only contains the class name; this is a valid file name.
Reserved Keywords in Java
delete
, next
, main
, exit
, and null
are not reserved keywords in Java.
Default Values for Local Variables
Local variables in Java are not automatically initialized to default values. You must explicitly assign values before using them.
Java Access Specifiers
Access Specifier | Accessibility |
---|---|
public |
Accessible from anywhere. |
protected |
Accessible within the same package or by subclasses. |
(default/package-private) | Accessible only within the same package. |
private |
Accessible only within the same class. |
Purpose of Static Methods and Variables
static
methods and variables belong to the class itself, not to specific objects of the class. They are shared among all instances of the class.
Advantages of Packages in Java
- Avoid naming conflicts (different classes can have the same name in different packages).
- Improved access control (packages can restrict access to their internal members).
- Better organization of code (related classes are grouped together).
String Concatenation in Java
In Java, the +
operator performs string concatenation. When used with numbers and strings, the numbers are implicitly converted to strings.
Example
System.out.println(10 + 20 + "Javatpoint"); // Output: 30Javatpoint
System.out.println("Javatpoint" + 10 + 20); // Output: Javatpoint1020
System.out.println("Javatpoint" + (10 + 20)); // Output: Javatpoint30
Object-Oriented Programming (OOP) Principles
Object-Oriented Paradigm
OOP organizes code around objects that encapsulate data (state) and methods (behavior). Key benefits include modularity, reusability, and maintainability.
What is an Object?
An object is an instance of a class. It represents a real-world or abstract entity.
Object-Oriented vs. Object-Based Programming
Object-Oriented Programming (OOP) | Object-Based Programming |
---|---|
Uses all OOP principles (inheritance, polymorphism, etc.). | May use objects but not necessarily all OOP principles. |
Examples: Java, C++ | Examples: JavaScript |
Default Value of Object References
Object references in Java are initialized to null
by default.
Constructors in Java
Constructors initialize objects when they are created. They share the name of the class and have no return type.
Types of Constructors in Java
- Default Constructor: No arguments; initializes variables to default values.
- Parameterized Constructor: Accepts arguments to initialize variables.
Purpose of Default Constructor
The default constructor initializes an object's instance variables to their default values. If no constructor is explicitly defined, the compiler provides a default constructor.
Constructors in Java
Default Constructor
A default constructor is a constructor with no arguments. The Java compiler automatically provides a default constructor if you don't define one explicitly. It initializes instance variables to their default values (0 for numbers, false
for booleans, null
for objects).
Example
class Student3 {
int id;
String name;
void display() {
System.out.println(id + " " + name);
}
public static void main(String args[]) {
Student3 s1 = new Student3();
Student3 s2 = new Student3();
s1.display();
s2.display();
}
}
Output
0 null
0 null
Constructor Return Value
A constructor implicitly returns the newly created object (you cannot explicitly specify a return type for a constructor).
Constructor Inheritance
Constructors are not inherited. A subclass does not inherit its superclass's constructors. When a subclass object is created, the subclass's constructor is called, and it may explicitly call the superclass's constructor using super()
.
Making Constructors Final
You cannot declare a constructor as final
in Java.
Constructor Overloading
Constructor overloading allows a class to have multiple constructors with different parameter lists. The compiler determines which constructor to call based on the arguments provided when creating an object.
Example: Constructor Overloading
class Test {
int i;
public Test(int k) { i = k; }
public Test(int k, int m) { i = Math.max(k, m); }
}
public class Main {
public static void main(String args[]) {
Test test1 = new Test(10);
Test test2 = new Test(12, 15);
System.out.println(test1.i); // Output: 10
System.out.println(test2.i); // Output: 15
}
}
Copy Constructor in Java
Java doesn't have a copy constructor in the same way as C++. However, you can copy the values of one object to another using several techniques:
- Using a constructor that takes another object as an argument.
- Directly assigning values from one object to another.
- Using the
clone()
method of theObject
class (creates a shallow copy).
Example: Copying Objects using Constructor
class Student6 {
int id;
String name;
Student6(int i, String n) { id = i; name = n; }
Student6(Student6 s) { id = s.id; name = s.name; }
void display() { System.out.println(id + " " + name); }
public static void main(String args[]) {
Student6 s1 = new Student6(111, "Karan");
Student6 s2 = new Student6(s1);
s1.display(); // Output: 111 Karan
s2.display(); // Output: 111 Karan
}
}
Constructor vs. Method in Java
Constructor | Method |
---|---|
Initializes object state. No return type. Implicitly called. | Exposes object behavior. Has a return type. Explicitly called. |
Constructor Overloading Example
Example
public class Test {
Test(int a, int b) {
System.out.println("a = " + a + " b = " + b);
}
Test(int a, float b) {
System.out.println("a = " + a + " b = " + b);
}
public static void main(String args[]) {
byte a = 10;
byte b = 15;
Test test = new Test(a, b); //Output: a = 10 b = 15
}
}
Default Constructor and Implicit Initialization
If a class doesn't have a constructor, the Java compiler creates a default (no-argument) constructor. Instance variables are initialized to their default values (0 for numbers, false
for booleans, null
for objects).
Implicit Constructor Call and Missing Constructor
Example
class Test {
int test_a, test_b;
Test(int a, int b) {
test_a = a;
test_b = b;
}
public static void main(String args[]) {
Test test = new Test(); // Compiler error: constructor Test() not found
System.out.println(test.test_a + " " + test.test_b);
}
}
The `static` Keyword in Java
Static Variables
A static
variable is a class variable, shared among all instances of the class. It only gets allocated once in memory.
Example
class Student8 {
int rollno;
String name;
static String college = "ITS";
// ... rest of the class ...
}
Static Methods
static
methods belong to the class, not to any specific object. They can access only static members of the class and cannot directly access instance variables or call instance methods.
Restrictions on Static Methods
- Cannot directly access instance variables or instance methods.
- Cannot use the
this
orsuper
keywords.
Why main()
is Static
The main()
method is static
because the JVM calls it directly without creating an instance of the class, saving memory.
Overriding Static Methods
Static methods cannot be overridden in subclasses because they belong to the class, not the instance. Method overriding only applies to instance methods.
Static Blocks
A static block is used to initialize static variables. It's executed only once when the class is loaded.
Example
class A2 {
static {
System.out.println("Static block invoked");
}
// ... rest of the class ...
}
Running a Java Program Without main()
Before Java 7, it was possible to execute code using static blocks alone. Since Java 7, a main()
method is required.
Removing Static Modifier from main()
Removing the static
keyword from main()
results in a runtime error (NoSuchMethodError
) because the JVM expects a static main()
method.
Static vs. Instance Methods
Static Method | Instance Method |
---|---|
Belongs to the class; called using the class name. Can only access static members. | Belongs to an object; called on an object instance. Can access both static and instance members. |
Static Constructors
You cannot make constructors static in Java because constructors are called when an object of the class is created.
Static Abstract Methods
You cannot make abstract methods static because abstract methods require implementation in subclasses, but static methods belong to the class itself.
Static Members in Abstract Classes
You can declare static members in an abstract class. They can be accessed using the class name.
The `this` Keyword in Java
The this
keyword refers to the current instance of a class. It's used to access instance variables and methods within the class.
Uses of the `this` Keyword
- To refer to instance variables (when there's a name conflict with a parameter).
- To invoke another constructor within the same class.
- To pass the current object as an argument to another method.
- To return the current object from a method.
The `this` Keyword in Java
The this
keyword is a reference variable that refers to the current instance of a class. It's used to access members (fields and methods) of the current object.
Uses of this
:
- To differentiate between instance variables and method parameters with the same name.
- To call another constructor within the same class (constructor chaining).
- To pass the current object as an argument to a method.
- To return the current object from a method.
Assigning a Value to `this`
You cannot assign a value to the this
keyword. It is implicitly assigned and is a final reference variable in Java.
Example (Compiler Error)
public class Test {
public Test() {
this = null; // Compiler error: cannot assign a value to final variable this
System.out.println("Test class constructor called");
}
// ...
}
Using `this` to Refer to Static Members
While technically possible, it's generally not recommended to use this
to access static members because static members belong to the class itself, not to a specific instance.
Example
public class Test {
static int i = 10;
public Test() {
System.out.println(this.i); // Output: 10
}
// ...
}
Constructor Chaining with `this`
Constructor chaining allows you to call one constructor from another within the same class, using the this()
keyword. This simplifies code by avoiding redundant initialization logic.
Example: Constructor Chaining
public class Employee {
int id, age;
String name, address;
public Employee(int age) { this.age = age; }
public Employee(int id, int age) { this(age); this.id = id; }
public Employee(int id, int age, String name, String address) {
this(id, age);
this.name = name;
this.address = address;
}
// ...
}
Advantages of Passing `this` to a Method
Passing this
to a method instead of the object itself offers advantages:
this
is a final reference; it cannot be reassigned.this
can be used within synchronized blocks for thread safety.
Inheritance in Java
Inheritance is a mechanism that allows a class (subclass or derived class) to inherit the properties (fields) and methods of another class (superclass or base class). It's a key feature of OOP promoting code reuse and establishing relationships between classes.
Types of Inheritance in Java
- Single inheritance
- Multi-level inheritance
- Hierarchical inheritance
- Multiple inheritance (through interfaces, not classes)
- Hybrid inheritance (a combination of multiple and multi-level)
Benefits of Using Inheritance
- Code Reusability
- Runtime Polymorphism
- Data Hiding
- Method Overriding
Superclass of All Classes in Java
The java.lang.Object
class is the root of the inheritance hierarchy in Java; all classes implicitly inherit from it.
Why Java Doesn't Support Multiple Inheritance (of Classes)
Multiple inheritance (inheriting from multiple classes) can lead to ambiguity (if multiple parent classes have methods with the same name). Java avoids this complexity by only allowing a class to extend one other class but allowing it to implement multiple interfaces.
Aggregation
Aggregation represents a "has-a" relationship between classes. One class contains a reference to another class, but the contained object can exist independently of the containing object.
Example (Java)
public class Emp {
int id;
String name;
Address address;
// ...
}
Composition
Composition is a stronger form of aggregation where the contained object cannot exist independently of the containing object. It represents a "part-of" relationship.
Aggregation vs. Composition
Aggregation | Composition |
---|---|
"Has-a" relationship; contained object can exist independently. | "Part-of" relationship; contained object cannot exist independently. |
Why Java Doesn't Use Pointers
Pointers are avoided in Java to improve security and simplify memory management. They can be dangerous if misused, leading to memory leaks or segmentation faults.
The `super` Keyword in Java
The super
keyword is used to refer to the parent class (superclass). It's used to access members of the superclass that are hidden by members in the subclass.
Example
class Animal {
Animal() { System.out.println("Animal created"); }
}
class Dog extends Animal {
Dog() {
super(); // Calls the Animal constructor
System.out.println("Dog created");
}
}
Uses of the `super` Keyword
- To access hidden superclass members.
- To call a superclass constructor.
- To call a superclass method (method overriding).
`this` vs. `super` Keywords
this |
super |
---|---|
Refers to the current object. | Refers to the parent class object. |
Constructor Chaining with `super`
Constructor chaining using super()
allows you to call the superclass constructor from the subclass constructor, initializing the superclass's members.
Example
class Person {
// ...
public Person(int age, String name, String address) {
// ...
}
}
class Employee extends Person {
float salary;
public Employee(int age, String name, String address, float salary) {
super(age, name, address); // Calls the Person constructor
this.salary = salary;
}
}
Why Multiple Inheritance of Classes is Not Supported in Java
Multiple inheritance (inheriting from more than one class) can lead to ambiguity if the parent classes have methods with the same name. To avoid this issue, Java only allows single inheritance but supports multiple inheritance through interfaces.
More on the `this` Keyword
Using `this()` for Constructor Chaining
The this()
keyword calls another constructor within the same class. It must be the first statement in the constructor.
Example (Compiler Error)
public class Test {
Test() {
super(); //Calls the parent class constructor (if there is one)
this(); // Compiler error: this() must be first statement
System.out.println("Test constructor called");
}
// ...
}
Using `this` and `super()` in Constructors
You can use only one of this()
or super()
as the first statement in a constructor. Using super()
calls the parent class constructor, while this()
calls another constructor in the current class.
Example
class Person {
public Person() {
System.out.println("Person class constructor called");
}
}
public class Employee extends Person {
public Employee() {
System.out.println("Employee class constructor called");
}
public static void main(String args[]) {
Employee e = new Employee(); //Output: Person class constructor called, Employee class constructor called
}
}
Object Cloning in Java
Object cloning creates a copy of an object. Java's clone()
method (in the Object
class) creates a shallow copy. The class must implement the Cloneable
interface to avoid a CloneNotSupportedException
. Deep cloning (copying nested objects) often requires custom implementation.
Method Overloading
What is Method Overloading?
Method overloading allows multiple methods with the same name but different parameter lists (different number or types of parameters) within the same class. The compiler chooses the correct method based on the arguments passed during the method call. This enhances code readability and reduces the need for creating methods with different names that perform similar operations on different data types.
Method Overloading Restrictions
Method overloading cannot be done by only changing the return type of a method. The compiler cannot distinguish between overloaded methods with only different return types, leading to ambiguity.
Example (Compiler Error)
class Adder {
static int add(int a, int b) { return a + b; }
static double add(int a, int b) { return a + b; } // Compiler error
}
Overloading Static Methods
You cannot overload methods solely by using the static
keyword; the parameter list must also be different to distinguish the methods.
Overloading the main()
Method
Yes, you can overload the main()
method in Java. However, only the method with the signature public static void main(String[] args)
is executed when you run the application from the command line.
Method Overloading with Type Promotion
Type promotion in method overloading occurs when an argument of one type is implicitly converted to another type to match a method signature. Java's type promotion rules determine the matching method.
Example
class OverloadingCalculation1 {
void sum(int a, long b) { System.out.println("int, long"); }
void sum(long a, int b) { System.out.println("long, int"); }
public static void main(String args[]) {
OverloadingCalculation1 obj = new OverloadingCalculation1();
obj.sum(20, 20); // Calls sum(int, long) - int is promoted to long
}
}
Method Overriding
What is Method Overriding?
Method overriding provides a specific implementation for a method that is already defined in its superclass. It's a form of runtime polymorphism. Method overriding is only possible for instance methods (not static methods).
Overriding Static Methods
Static methods cannot be overridden because they are bound to the class, not the object instance.
Overriding Overloaded Methods
Yes, you can override overloaded methods. The overridden method in the subclass must have the same name and parameter list as the method being overridden in the superclass. The return type must also be a subtype or the same type.
Changing the Scope of an Overridden Method
When overriding a method, you can modify its access modifier (visibility), but you cannot reduce its accessibility (e.g., you can change private
to public
, but not public
to private
).
Modifying the throws
Clause in Overridden Methods
When overriding a method, you can modify the throws
clause (the list of checked exceptions a method can throw). However, the overridden method cannot throw checked exceptions that aren't declared in the superclass method.
Method Overriding Example
Example
class Base {
public void baseMethod() { System.out.println("BaseMethod called..."); }
}
class Derived extends Base {
@Override
public void baseMethod() { System.out.println("Derived method called..."); }
}
public class Test {
public static void main(String args[]) {
Base b = new Derived();
b.baseMethod(); // Output: Derived method called...
}
}
Virtual Functions in Java
In Java, all methods (except private
and static
methods) are virtual by default. This means that method overriding is allowed.
Covariant Return Types
Since Java 5, you can override a method and change its return type, provided the return type of the overriding method is a subtype of the return type of the overridden method.
Example
class A { A get() { return this; } }
class B1 extends A { B1 get() { return this; } public static void main(String args[]) { new B1().get(); } }
The `final` Keyword in Java
Final Variables
A final
variable cannot be reassigned a value after its initial assignment. This creates an immutable variable. If a final variable is not initialized at the time of declaration, it must be initialized in the constructor (for instance variables) or in a static block (for static variables).
Example (Compiler Error)
class Bike9 {
final int speedlimit = 90; // final variable
void run() {
speedlimit = 400; // Compiler error: cannot assign a value to final variable speedlimit
}
// ...
}
Final Methods
A final
method cannot be overridden in a subclass. This prevents modification of the method's behavior in derived classes.
Example (Compiler Error)
class Bike {
final void run() { System.out.println("running"); }
}
class Honda extends Bike {
void run() { // Compiler error: cannot override final method run()
System.out.println("running safely with 100kmph");
}
// ...
}
Final Classes
A final
class cannot be subclassed. This prevents inheritance and ensures that the class's behavior cannot be altered by subclasses.
Final Blank Variables
A final blank variable is a final
variable that's not initialized during declaration. It must be initialized in a constructor or a static block.
Initializing Final Blank Variables
Final blank variables must be initialized exactly once, either during declaration or within the constructor (instance variables) or a static block (static variables).
Declaring main()
as Final
Yes, you can declare the main()
method as final
. This prevents overriding the main()
method in subclasses, although this is typically not done.
Example: Final Variable Initialization
Example
class Main {
public static void main(String args[]) {
final int i;
i = 20;
System.out.println(i); // Output: 20
}
}
Overriding a Final Method
A final
method cannot be overridden. Attempting to do so results in a compiler error.
Declaring Constructors and Interfaces as Final
It's generally not useful to declare constructors as final
(because they are not inherited), and you cannot declare interfaces as final
because interfaces are designed to be implemented by classes.
Final Method vs. Abstract Method
Final Method | Abstract Method |
---|---|
Cannot be overridden. Provides a concrete implementation. | Must be overridden in subclasses. Provides no implementation. |
Core Java Multiple Choice Questions
- Which statement(s) about the
final
keyword are correct?- A final method can be overridden.
- A final class can be instantiated multiple times.
- A final variable can be reassigned multiple times.
- A final blank variable can be initialized in an instance initializer block.
Answer:
B (2 and 4)
- Which statement about method overriding is correct?
- A subclass can reduce the visibility of an overridden method.
- A subclass can throw any checked exception in an overridden method.
- A private method can be overridden.
- A static method can be overridden.
Answer:
None of the above are correct.
- Which statement about method overloading is correct?
- Method overloading is achieved by changing only the return type.
- Method overloading is achieved by changing the number of parameters or their types.
- Two methods with the same name, parameter list, and different static modifiers are overloaded.
- Method overloading allows a subclass method to have the same name and parameters as a superclass method.
Answer:
B
- Which statement about
this
andsuper
is true?this
can call the current class's constructor from a method.super
can call the current class's constructor.this
andsuper
are interchangeable.super
calls parent class methods;this
calls current class methods.
Answer:
D
- Which statement about OOP is NOT correct?
- Encapsulation bundles data and methods.
- Inheritance extends superclass properties to subclasses.
- Polymorphism is limited to method overloading.
- Abstraction hides implementation details.
Answer:
C