JAVA MOCK INTERVIEW QUESTIONS ANSWERS
1) What is a Programming Language?
A programming language is a way to communicate with computers to give instructions and solve problems.
2) Flavors of Java
Java SE (Standard Edition) → Core Java (desktop apps).
Java EE (Enterprise Edition) → Web & enterprise apps.
Java ME (Micro Edition) → Mobile & embedded devices.
Who developed Java and when?
Java was developed by James Gosling at Sun Microsystems in 1995.
First name was Oak, later renamed Java.
Features of Java
Simple (easy syntax),
Object-Oriented,
Platform Independent (WORA),
Robust,
Secure,
Multithreaded,
Portable,
High Performance (JIT).
What is JDK, JRE, JVM, JIT?
JDK: Java Development Kit → tools to develop + run Java programs.
JDK (Java Development Kit):
The JDK is the complete software development kit for Java. It includes the compiler (javac), tools like debugger,
and the JRE. Developers use the JDK to write, compile, and run Java programs. Without JDK, you cannot
develop Java applications.
JRE: Java Runtime Environment → only for running Java programs.
JRE (Java Runtime Environment):
The JRE is designed for running Java applications. It contains the JVM and Java class libraries, but it does not
include the compiler. If someone only wants to execute Java programs (not develop), installing the JRE is
enough.
JVM: Java Virtual Machine → executes bytecode.
JVM (Java Virtual Machine):
The JVM is the engine that actually executes Java bytecode. It takes the compiled .class files and translates
them into machine code for the underlying operating system. JVM also handles memory management, garbage
collection, and security. Importantly, JVM is what makes Java platform-independent, because the same
bytecode can run on any OS that has a JVM.
JIT: Just-In-Time Compiler → improves speed at runtime.
JIT (Just-In-Time Compiler):
The JIT is part of the JVM. Normally, the JVM interprets bytecode line by line, which can be slower. The JIT
improves performance by compiling frequently used parts of the bytecode into native machine code at runtime.
Once compiled, the native code runs directly on the CPU, which makes execution much faster.
“In short, the JDK is for developing and running programs, the JRE is only for running programs, the JVM
executes the bytecode, and the JIT compiler boosts performance by converting bytecode into native machine
code at runtime.”
What is Platform Independence in Java?
Java code is compiled into bytecode.
Bytecode runs on JVM available for all operating systems.
Hence → “Write Once, Run Anywhere”.
Difference between Compiler and Interpreter
Compiler → Translates whole program → Fast execution (C, C++).
Interpreter → Translates line by line → Slower (Python).
Java uses both → Compiler (to bytecode), JVM Interpreter/JIT (to machine code).
What is a Token in Java?
Smallest unit in Java program. Types:
Keywords (class, if, static)
Identifiers (variable names)
Literals (10, 3.14, true, "Hello")
Punctuators/Separators (; , () {})
Operators (+, -, *, ==, &&)
Explain main method
public static void main(String[] args)
public → Accessible everywhere.
static → Runs without object.
void → No return value.
String[] args → Command line arguments.
Types of Literals in Java
Integral → 10, -25, 0xA, 010, 0b101
Floating-point → 3.14, -2.5, 1.2e3
Char → 'a', '1', '@'
Boolean → true, false
String → "Hello", "Java123"
null → String s = null;
Operators?
a) Arithmetic Operators
Used to perform basic math operations on numbers.
Operators: + (add), - (subtract), * (multiply), / (divide), % (modulus → remainder).
b) Unary Operators
Operates on only one operand.
Types:
Increment (++) → increases value by 1
Pre: ++a → increase first, then use
Post: a++ → use first, then increase
Decrement (--) → decreases value by 1
Unary plus (+) → keeps number positive (rarely used)
Unary minus (-) → changes sign
c) Assignment Operator
Used to assign values to variables.
Basic: = (assign value).
Compound Assignment: +=, -=, *=, /=, %=
d) Relational Operators
Used to compare two values.
Result → boolean (true/false).
Operators: ==, !=, <, >, <=, >=
e) Logical Operators
Used to combine boolean conditions.
Operators:
&& → Logical AND
|| → Logical OR
! → Logical NOT
f) Boolean Operators
Java treats boolean values as true/false only (no 0 or 1 like C).
Operators → same as logical: &&, ||, !.
g) Bitwise Operators
Works on bits (binary form).
Operators:
& (AND), | (OR), ^ (XOR), ~ (NOT), << (Left shift), >> (Right shift), >>> (Unsigned Right shift).
h) Ternary Operator
Short form of if-else.
Syntax:
condition ? value_if_true : value_if_false
i) Member Operator (.)
Used to access members of a class (methods/variables).
j) new Operator
Used to create objects.
Example:
Student st = new Student()
k) instanceof Operator
Checks whether an object is of a particular type/class.
Example:
String s = "Hello";
[Link](s instanceof String); // true
Programs on Method Parameter & Return Type?
No parameter, no return
void greet() { [Link]("Hello"); }
With parameter, no return
void square(int n) { [Link](n*n); }
No parameter, with return
int getNumber() { return 10; }
With parameter, with return
int add(int a, int b) { return a+b; }
Introduction to OOP (Object Oriented Programming)?
a) OOP Features & Advantages
Features: Abstraction, Encapsulation, Inheritance, Polymorphism.
Advantages: Reusability, Modularity, Maintainability, Security.
b. Class & Object
Class: A class is a blueprint/template that defines properties (variables) and behaviors (methods).
Object: An object is a real instance of a class
Class = Blueprint of a car.
Object = Actual car made from blueprint.
2. Abstraction
Definition: Hiding internal implementation and showing only essential details.
Done in Java using abstract classes or interfaces.
✅ Analogy: When you drive a car, you just press accelerator, you don’t care how fuel injection works internally.
3. Encapsulation
Definition: Wrapping data (variables) and code (methods) together in a single unit (class).
Achieved by making variables private and providing public getters/setters.
✅ Analogy: Medicine capsule → hides powder inside, only provides controlled way to use it.
4. Inheritance
Definition: Process where one class (child) acquires properties & methods of another (parent).
Achieved using extends keyword.
✅ Analogy: Son inherits qualities from father.
5. Polymorphism
Definition: “Many forms” → A single action behaves differently based on context.
Two types in Java:
Compile-time (Method Overloading) → Same method name, different parameters.
class MathUtil {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
Runtime (Method Overriding) → Child class provides its own implementation of a parent method.
class Animal {
void sound() { [Link]("Animal makes sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Dog barks"); }
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog(); // upcasting
[Link](); // Dog barks (runtime decision)
}
}
✅ Analogy: Word "bank" has multiple meanings → river bank, financial bank → depends on context.
c) Default Constructor added by Compiler?
If we don’t define a constructor, Java compiler automatically adds a no-arg constructor.
d) Why Compiler adds Default Constructor?
So that object creation is always possible even when no constructor is explicitly defined.
e) Types of Variables
Primitive variables → Store actual values (int, double, char, etc).
Reference variables → Store address/reference to an object.
f) Instance, Static, Parameter, Local Variables
Instance variable → Belongs to object. Declared inside class, outside methods.
Static variable → Belongs to class, shared among all objects.
Parameter variable → Passed to methods/constructors.
Local variable → Declared inside method/constructor, exists only during method execution.
g) User Defined Values for Instance Variable
Use constructors or setters to assign custom values.
class Student {
int id;
Student(int i) { id = i; }
}
h) this keyword?
Refers to the current object.
Used to access instance variables, methods, or constructors.
i) Role of Instance Variable while Creating Object?
Each object gets its own copy of instance variables.
j) Working with Static Variable while Creating Object
Static variables are shared across all objects of a class.
Changing value from one object affects all.
k) When to declare Variable as Instance or Static?
Instance → If value is unique per object (e.g., studentName).
Static → If value is common for all objects (e.g., collegeName).
l) Data Hiding?
Achieved using private variables + public getters/setters.
Prevents unauthorized access.
m) Abstraction?
Hiding implementation details, showing only essential info.
Achieved using abstract classes and interfaces.
n) toString()?
Method from Object class.
Returns string representation of object.
Can be overridden.
public String toString() { return id + " " + name; }
o) How to Print Object Properties Value
By default → [Link](obj); calls toString().
If we override toString(), we can print instance variable values directly.
class Student {
int id; String name;
public String toString() {
return id + " " + name;
}
}
p) Setter and Getter?
In Java, getter and setter methods are used to access and update the values of private instance variables.
This is a principle of Encapsulation, where data is kept private and accessed through public methods.
// Setter
public void setName(String name) {
[Link] = name;
}
// Getter
public String getName() {
return name;
}
“Getter is used to retrieve the value of a private variable, and setter is used to modify the value. This ensures
data security and validation.”
10. Constructor
a) Advantage of Constructor
A constructor is a special method that is automatically called when an object is created.
Its main advantage is that it initializes the object at the time of creation, so we don’t have to call methods
manually.
b) Types of Constructor
Default Constructor – Provided by the compiler if no constructor is defined.
No-Argument Constructor – Defined by programmer, takes no parameters.
Parameterized Constructor – Accepts arguments to initialize fields.
Copy Constructor – Creates an object by copying data from another object.
class Student {
String name;
int age;
Student(String name, int age) {
[Link] = name;
[Link] = age;
}
// Copy constructor
Student(Student s) {
[Link] = [Link];
[Link] = [Link];
}
}
e) Instance Block in Java
An instance block is a block of code inside a class, written with { }
It runs every time before the constructor when an object is created.
class Test {
{ [Link]("Instance Block"); }
Test() { [Link]("Constructor"); }
}
f) Ways to Initialize Object Properties?
Using constructor.
Using setter methods.
Using direct assignment ([Link] = value).
Using instance block.
Using static block (for static variables).
11. Relationship Between Classes
a) IS-A Relationship (Inheritance)
IS-A represents inheritance.
Child class inherits properties and behavior from the parent class.
Example: Dog IS-A Animal.
class Animal {}
class Dog extends Animal {}
b) HAS-A Relationship (Association)?
HAS-A represents association/composition.
One class contains another class as a reference.
Example: Car HAS-A Engine.
class Engine {}
class Car {
Engine e = new Engine();
}
c) Types of Inheritance
Single Inheritance – One parent, one child.
Multilevel Inheritance – Parent → Child → Grandchild.
Hierarchical Inheritance – One parent, multiple children.
Multiple Inheritance – ❌ Not supported in Java with classes (to avoid ambiguity).
e) Why Java does not support Multiple Inheritance
Java avoids ambiguity (diamond problem) caused when two parents have the same method.
To solve this, Java provides interfaces.
d) this() and super()
this() → Calls another constructor in the same class.
super() → Calls parent class constructor.
Both must be the first line inside a constructor.
f) Access Modifiers in Java?
public → Accessible everywhere.
protected → Accessible in same package + subclasses.
default (no keyword) → Accessible only within package.
private → Accessible only within same class.
12. JVM Architecture?
a) Class Loader Subsystem
Responsible for loading .class files into JVM.
Works in three steps:
Loading – Reads class file.
Linking – Verifies and prepares class.
Initialization – Assigns memory to static variables.
b) Types of Class Loaders?
Bootstrap ClassLoader – Loads core Java classes ([Link].*).
Extension ClassLoader – Loads extension classes from jre/lib/ext.
Application ClassLoader – Loads user-defined classes.
c) Runtime Data Areas?
Method Area – Stores class structure, static data.
Heap Memory – Stores objects.
Stack Memory – Stores method calls and local variables.
PC Register – Holds address of current instruction.
Native Method Stack – Used for native (C/C++) methods.
d) Execution Engine
Executes the bytecode.
Contains:
Interpreter → Executes line by line (slower).
JIT Compiler (Just-In-Time) → Converts frequently used code to native machine code (faster).