Loading...
Loading...
Cookie choices
WoHoTech uses essential cookies for login and site features. Non-essential analytics and advertising scripts load only after you accept them.
Read privacy policyCore Java interview questions, OOP revision, and practical placement preparation. Use this page as a focused learning resource for java concepts, interview preparation, and practical revision.
Aprogramming languageis a formal set of instructions and rules used to communicate with a computer and tell it what tasks to perform. It acts as a bridge between human logic and machine-level operations.
Just as humans use natural languages (English, Hindi) to communicate with each other, programmers use programming languages to write instructions (calledprograms or code) that the computer can understand and execute.
Examples: Java, Python, C, C++, JavaScript, Ruby, Go.
Programming languages are broadly classified into:
High-level languages are further divided into:
Ahigh-level programming languageis a language that is designed to be easy for humans to read, write, and understand. It uses English-like syntax and abstracts away the complex details of hardware and memory management.
Key characteristics:
Examples: Java, Python, C++, C#, JavaScript, Ruby.
High-level language is oftwo types:
| Procedure-Oriented Programming (POP) | Object-Oriented Programming (OOP) |
|---|---|
| Program is divided into functions or procedures. | Program is divided into objects and classes. |
| Follows a top-down approach. | Follows a bottom-up approach. |
| Data is exposed and can be accessed freely. | Data is hidden through encapsulation. |
| Functions are the primary unit of programming. | Objects are the primary unit of programming. |
| Less secure because data hiding is not supported. | More secure because data hiding is supported. |
| Code reusability is limited. | Supports inheritance for better code reusability. |
| Examples: C, Pascal, FORTRAN. | Examples: Java, C++, Python. |
| Compiler | Interpreter |
|---|---|
| Translates the entire source code at once into machine code. | Translates and executes the source code line-by-line. |
| Shows all errors after complete translation. | Stops execution at the first error found. |
| Execution is faster after compilation. | Execution is slower because translation occurs at runtime. |
| Generates an intermediate file (e.g., .class in Java). | No intermediate file is generated. |
| Used by C, C++, and Java (javac compiler). | Used by Python, JavaScript, and Ruby. |
Thefour pillars of OOPare:
extendskeyword.1. Encapsulation: It is the mechanism of binding data (variables) and the methods that operate on that data together in a single unit called a class. It restricts direct access to data and provides it through getter and setter methods. It helps achieve data hiding and security.
2. Inheritance: It is a mechanism by which one class (child/subclass) acquires the properties (fields) and behaviors (methods) of another class (parent/superclass). It promotes code reusability. Achieved using theextendskeyword in Java.
3. Polymorphism: It means "many forms." The same method name can behave differently based on the context. Achieved in two ways: (a) Compile-time polymorphism via method overloading, (b) Runtime polymorphism via method overriding.
4. Abstraction: It is the mechanism of hiding the internal implementation details and showing only the essential features/functionality to the user. Achieved using abstract classes and interfaces in Java. Example: You use a TV remote without knowing its internal circuit.
Java is called** platform-independent**because Java programs can run on any operating system (Windows, Mac, Linux, etc.) without any modification, as long as that system has a JVM (Java Virtual Machine) installed.
How it works:
"Write Once, Run Anywhere (WORA)"
Bytecodeis the intermediate code generated by the Java compiler (javac) after compiling the Java source code (.java file). It is stored in a .class file .
It is called "magical code" because:
This is what makes Java platform-independent - the same .class file (bytecode) can run on any OS that has a JVM.
TheJVM (Java Virtual Machine) is a virtual machine that resides on top of the real hardware and OS. It is responsible for executing Java bytecode.
Working of JVM:
JVM isplatform-specific (different JVM for Windows, Mac, Linux) but bytecode is platform-neutral - this combination makes Java platform-independent.
In Java, errors are broadly classified into three types:
Compile-Time Error:
int x = "hello";- assigning a String to int is a compile-time error.Runtime Error:
int result = 10 / 0;throwsArithmeticExceptionat runtime.AnExceptionis anunwanted or unexpected eventthat occurs during the execution of a program and disturbs its normal flow. It is a runtime error that can be handled (caught and managed) by the programmer.
In Java, exceptions are objects - instances of classes that extend theThrowableclass.
Hierarchy: Throwable → Exception → Checked/Unchecked Exceptions
Common Examples:
NullPointerException- accessing a null referenceArrayIndexOutOfBoundsException- invalid array indexArithmeticException- dividing by zeroNumberFormatException- converting invalid string to numberClassCastException- invalid type castingException Handlingis a mechanism in Java to handle runtime errors gracefully so that the program does not terminate abnormally. It allows the program to continue executing even after an exception occurs.
Java provides 5 keywords for exception handling:
If a Java program does not have amainmethod, it willcompile successfully(no syntax error), but when you try torunit, the JVM will throw an error:
This is because the JVM's entry point for execution is alwayspublic static void main(String[] args). Without it, the JVM does not know where to begin execution.
Keywordsare reserved words in Java that have a predefined meaning and purpose in the language. They cannot be used as variable names, class names, or identifiers.
Java has53 keywords(including reserved words).
Some important keywords:
The main method signature is:public static void main(String[] args)
It uses3 keywords:
mainis an identifier (not a keyword), andStringis a class name.
Anidentifieris any user-defined name given to a variable, method, class, interface, or package.
Rules for identifiers:
123nameis invalid;name123is valid)class,intare invalid)my variableis invalid)Nameandnameare different)my@varis invalid)| Keywords | Identifiers |
|---|---|
| Reserved words with predefined meaning in Java. | User-defined names for variables, methods, classes, interfaces, and packages. |
| Cannot be used as identifiers. | Cannot be the same as Java keywords. |
| Usually written in lowercase (e.g., class, int, void). | Can be written in uppercase, lowercase, or mixed case. |
| Fixed in number and defined by the Java language. | Unlimited; programmers can create their own names. |
| Provide special meaning to the compiler. | Used to identify program elements. |
| Cannot be modified or redefined. | Can be chosen according to naming conventions. |
| Examples: class, static, void, int, if, else. | Examples: main, age, name, calculate, Student. |
String[] argsused in the main method of Java? What is its use?String[] argsis aString array parameterthat allows the user to passcommand-line argumentsto the Java program at the time of execution.
When you run a Java program from the command line like:
The values"Hello","World", and"123"are stored inargs[0],args[1], andargs[2]respectively.
This feature is called theCommand-Line Argument Feature. It allows users to provide input to the program before it runs, without modifying the source code.
Thecommand-line argumentfeature allows you to pass values (arguments) to a Java program at runtime through the command line/terminal. These arguments are received in theString[] argsparameter of the main method.
**Note:**All arguments are received as Strings. Convert to other types as needed (e.g.,Integer.parseInt(args[0])).
If a program has multiple methods along with themainmethod, thenonly the main method will be automatically executed by the JVM. The other methods will only be executed when they areexplicitly calledfrom inside the main method or from within another method that is called.
If there isno main method, none of the methods will execute - the JVM will throw a runtime error.
In Java,maincan beoverloaded- you can have multiple methods namedmainwith different arguments. However, the JVM willalways execute only the standard main methodwhich has the exact signature:public static void main(String[] args).
Other overloadedmainmethods (likemain(int args),main(String args)) are treated as regular methods and will not be called by the JVM automatically.
Adata typedefines what kind of data a variable can hold, how much memory it occupies, and what operations can be performed on it.
Why are they used?
Example:int age = 25;- Java allocates 4 bytes, stores only integer values.
Java hastwo categories of data types:
1. Primitive Data Types (8 types):
| Type | Size | Default Value | Range |
|---|---|---|---|
| byte | 1 byte (8 bits) | 0 | -128 to 127 |
| short | 2 bytes (16 bits) | 0 | -32,768 to 32,767 |
| int | 4 bytes (32 bits) | 0 | -2,147,483,648 to 2,147,483,647 |
| long | 8 bytes (64 bits) | 0L | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| float | 4 bytes (32 bits) | 0.0f | Approximately ±3.4 × 1038 |
| double | 8 bytes (64 bits) | 0.0d | Approximately ±1.7 × 10308 |
| char | 2 bytes (16 bits) | \u0000 | 0 to 65,535 (Unicode characters) |
| boolean | JVM dependent | false | true or false |
2. Non-Primitive Data Types: String, Array, Class, Interface, Enum. These are objects (reference types).
| Primitive Data Types | Non-Primitive Data Types |
|---|---|
| Store a single value directly in memory. | Can store multiple values or complex data structures. |
| Predefined by the Java language. | Created by programmers or provided by Java libraries. |
| Fixed size in memory. | Size may vary depending on the data stored. |
| Not objects. | Objects created from classes. |
| Store actual values directly. | Store references (memory addresses) to objects. |
| Cannot call methods directly on primitive values. | Methods can be invoked on objects. |
| More memory-efficient and faster. | Require more memory because of object overhead. |
| Have predefined default values. | Default value is null for object references. |
| Examples: byte, short, int, long, float, double, char, boolean. | Examples: String, Array, Class, Interface, Object, Collection. |
In Java, thebytedata type uses8 bitswith2's complement representationfor negative numbers.
2's Complement Steps (for negative numbers):
Most Significant Bit (MSB)
Java is called a**strictly typed (strongly typed)**programming language because:
Primitive type castingis the process of converting a value from one primitive data type to another primitive data type. When the data types are incompatible or the target type has less capacity, an explicit cast is needed.
There are two types:
Widening (Promotion):Converting a smaller data type to a larger data type. It is safe because no data is lost. Java does thisautomatically.
Narrowing (Demotion):Converting a larger data type to a smaller data type. Data loss may occur. Must be doneexplicitlyby the programmer.
Implicit Conversion (Automatic): The conversion is done automatically by the Java compiler without programmer intervention. No data is lost. This happens in widening conversions.
Explicit Conversion (Manual Cast): The programmer manually tells the compiler to convert one type to another using cast operator(type). May result in data loss. This happens in narrowing conversions.
Widening is called Implicit Conversion because:
Narrowing is called Explicit Conversion because:
(type).Object-Oriented Programming (OOP) is a programming paradigm that organizes software design arounddata(objects) rather than functions and logic. Everything in OOP revolves around objects that have attributes (state) and behaviors (methods).
Why is it used?
No, Java is NOT a 100% Object-Oriented language.
For a language to be 100% OOP,everythingmust be an object. Java violates this because:
Wrapper classes
Class: A class is ablueprintortemplatethat defines the structure and behavior for a group of objects. It defines what attributes (fields/variables) and behaviors (methods) its objects will have. A class does not occupy memory until an object is created from it.
Object: An object is areal-world instancecreated from a class. It occupies actual memory (in the Heap area) and has its own copy of non-static variables. An object is the actual entity that stores data and uses the behaviors defined in the class.
newkeyword.The new keyword in Java is used to create a new object (instance) of a class at runtime. It performs the following tasks:
In Java, an object is created inthree steps:
ClassName obj;newkeyword to create the object and allocate memory.obj = new ClassName();Aconstructoris a special method-like block that is calledautomaticallywhen an object is created using thenewkeyword. Its primary job is toinitialize the object's state(set initial values for the object's instance variables).
Key responsibilities:
Reference data types (also called non-primitive types) are data types that store areference (memory address) pointing to an object in the Heap, rather than the actual value. They include Classes, Interfaces, Arrays, Strings, and Enums.
Thedefault value of any reference variable (that is a class/instance field) isnull.
Instantiation: The process of creating an object (instance) from a class using thenewkeyword is called instantiation. When we writenew ClassName(), we are "instantiating" the class.
Instance: An instance is a specific, concrete object created from a class. Each instance has its own copy of non-static (instance) variables. When you create multiple objects of the same class, each one is a separate instance.
Memory area for objects: Objects are created in theHeap memory area. The JVM's Heap is a shared runtime data area from which all class instances (objects) are allocated. The reference variable (pointing to the object) is stored in theStack.
A class is a user-defined non-primitive data type that groups related data and behavior into a single unit. The following Employee class represents an employee with common attributes.
class Employee {
int employeeId;
String employeeName;
double salary;
String department;
String designation;
}| Attribute | Data Type | Description |
|---|---|---|
| employeeId | int | Unique identification number of the employee. |
| employeeName | String | Name of the employee. |
| salary | double | Salary of the employee. |
| department | String | Department in which the employee works. |
| designation | String | Job title or position of the employee. |
public class Main {
public static void main(String[] args) {
Employee emp = new Employee();
emp.employeeId = 101;
emp.employeeName = "John Smith";
emp.salary = 50000.0;
emp.department = "Information Technology";
emp.designation = "Software Engineer";
System.out.println("Employee ID: " + emp.employeeId);
System.out.println("Employee Name: " + emp.employeeName);
System.out.println("Salary: " + emp.salary);
System.out.println("Department: " + emp.department);
System.out.println("Designation: " + emp.designation);
}
}Therefore, Employee is a user-defined non-primitive data type in Java.
Avariableis a named memory location that stores a value of a specific data type. The value stored in a variable can change during program execution (hence "variable").
Why are variables used?
In Java, there arethree types of variables:
1. Local Variable:
2. Static Variable (Class Variable):
statickeyword inside the class but outside methods.ClassName.variableName.3. Non-Static Variable (Instance Variable):
statickeyword inside the class but outside methods.obj.variableName.| Variable Type | Default Value | Scope |
|---|---|---|
| Local Variable | No default value. Must be initialized before use; otherwise, a compile-time error occurs. | Accessible only within the method, constructor, or block in which it is declared. |
| Static Variable | Has a default value such as 0, false, or null. | Belongs to the class and can be accessed using the class name. Exists as long as the class remains loaded in memory. |
| Instance Variable (Non-Static Variable) | Has a default value such as 0, false, or null. | Belongs to an object and can be accessed through object references. Exists as long as the object exists. |
Amethod is a named block of code that performs a specific task. It is defined inside a class and can be called (invoked) to execute its code whenever needed.
Why are methods used?
Method execution takes place in theStack memory area (also called the Call Stack or Method Stack).
The mechanism followed isLIFO (Last In First Out):
Static Method: Can be called directly using the class name (or method name if in same class) without creating an object.
Non-Static Method: Requires an object of the class to be created first. Called using object reference.
The main method must bepublicbecause theJVM needs to call it from outside the class(from any location) to start the program.
If it wereprivateorprotected, the JVM (which is outside the class's access boundary) would not be able to access and invoke it, resulting in a runtime error.
public
The main method must bestaticbecausethe JVM needs to call it without creating an object of the class.
When a Java program starts, no objects exist yet - the JVM needs to invoke main() to begin execution. If main() were non-static, JVM would need to create an object first, but it cannot do so because the program hasn't started yet (chicken-and-egg problem).
Making itstaticallows JVM to call it using just the class name:ClassName.main(args).
The return type of main isvoidbecausethe JVM calls main() but does not expect any value in return. There is no caller in the program that would use a returned value - the JVM simply starts execution and the program runs until it finishes or exits.
If you want to send an exit status to the OS, you can useSystem.exit(statusCode)instead.
Access Modifiers control the visibility and accessibility of classes, methods, constructors, and variables in Java. Java provides four access modifiers: public, protected, default (package-private), and private.
| Modifier | Same Class | Same Package | Subclass (Different Package) | Anywhere |
|---|---|---|---|---|
| public | ✅ | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ✅ | ❌ |
| default (no keyword) | ✅ | ✅ | ❌ | ❌ |
| private | ✅ | ❌ | ❌ | ❌ |
| Modifier | Description |
|---|---|
| public | Accessible from any class in any package. |
| protected | Accessible within the same package and by subclasses in different packages. |
| default (package-private) | Accessible only within the same package. |
| private | Accessible only within the same class. |
Method Signature: Uniquely identifies a method. It consists of the method name and its parameter list (types and order). Return type and access modifiers are NOT part of the signature.
Method Declaration: The method header - includes access modifier, return type, method name, and parameters. In abstract classes/interfaces, this is the entire method (no body).
Method Definition: The complete method including both the declaration (header) and the body (implementation code).
Formal Arguments (Parameters): Variables declared in the method definition that receive values when the method is called. They are placeholders.
Actual Arguments: The real values passed to the method when it is called. They are copied into the formal parameters.
Call by Value: A copy of the actual argument's value is passed to the method. Changes made to the parameter inside the method do NOT affect the original variable.
Call by Reference: The actual memory address (reference) is passed. Changes inside the method affect the original data.
Does Java support Call by Reference?
NOT
reference
Static members are variables and methods declared with thestatickeyword. They belong to theclassitself rather than to any specific object.
Main purpose:To help in better memory management- onlyone copyof a static member is loaded in memory regardless of how many objects are created. This shared copy is accessible by all objects of the class.
Number of copies:Only ONE copy of a static member exists in memory throughout the program, stored in theMethod Area (Static Pool/Class Area).
Non-static members (instance members) are variables and methods declared without thestatickeyword. They belong to each individual object (instance) of the class.
Main purpose: To load adifferent, independent copyof the data for each object, allowing each object to maintain its own state.
Number of copies: One copy per object- if you create 3 objects, there are 3 separate copies of each non-static variable, each stored in their own space in the Heap.
JVM Memory Areas:
Stack and Heap are two important memory areas used by the Java Virtual Machine (JVM) during program execution.
| Stack Memory | Heap Memory |
|---|---|
| Stores method frames, local variables, and references. | Stores objects and instance variables. |
| Memory is automatically released when a method completes execution. | Memory is released by the Garbage Collector when objects are no longer needed. |
| Each thread has its own separate stack memory. | Shared among all threads in the application. |
| Provides very fast memory access. | Access is comparatively slower due to object management and garbage collection. |
| Follows Last In First Out (LIFO) order. | Does not follow any specific order. |
| Usually smaller in size and fixed for each thread. | Generally larger and dynamically managed by the JVM. |
Exceeding the stack limit causes StackOverflowError. | Exceeding heap memory causes OutOfMemoryError. |
public class MemoryDemo {
int age = 25; // Stored in Heap (inside object)
public static void main(String[] args) {
int number = 10; // Stored in Stack
MemoryDemo obj = new MemoryDemo(); // Object stored in Heap
// Reference variable stored in Stack
System.out.println(number);
System.out.println(obj.age);
}
}Static Initializer Block:Runsoncewhen the class is first loaded into memory by the JVM. Used to initialize static variables or run one-time class-level setup.
Non-Static Initializer Block (Instance Initializer Block):Runsevery time an object is created, before the constructor executes. Used to initialize instance variables with complex logic.
The accessibility of static and non-static members depends on the context from which they are accessed.
| Can Access Directly? | Static Members | Non-Static Members |
|---|---|---|
| Inside Static Method | ✅ Yes | ❌ No (requires an object reference) |
| Inside Non-Static Method | ✅ Yes | ✅ Yes |
| Inside Static Block | ✅ Yes | ❌ No (requires an object reference) |
| Inside Non-Static Block | ✅ Yes | ✅ Yes |
| Member Type | Description |
|---|---|
| Static Member | Belongs to the class and can be accessed without creating an object. |
| Non-Static Member | Belongs to an object and requires an object reference for access from a static context. |
thiskeyword.Variable Shadowing: When a local variable (inside a method/constructor) has the same name as an instance variable, the local variableshadows(hides) the instance variable within that scope.
Resolution usingthiskeyword: Thethiskeyword refers to the** current object under execution**. Usethis.variableNameto distinguish instance variables from local/parameter variables.
For static variable shadowing: Use the class name -ClassName.staticVar.**For non-static variable shadowing:**Usethis.variableName.
Aconstructoris a special block of code that:
new.Use of Constructor:
Constructors and methods are both members of a class, but they serve different purposes. A constructor is used to initialize objects, whereas a method is used to perform specific operations or tasks.
| Constructor | Method |
|---|---|
| Must have the same name as the class. | Can have any valid name except Java keywords. |
Does not have a return type, not even void. | Must declare a return type such as void, int, String, etc. |
Called automatically when an object is created using the new keyword. | Called explicitly by the programmer. |
Cannot be static, final, abstract, or synchronized. | Can be static, final, abstract, or synchronized. |
| Used to initialize object state. | Used to perform operations or implement business logic. |
| Not inherited by child classes. | Inherited by child classes unless declared private. |
| A class can have default and parameterized constructors. | A class can have multiple methods with different functionalities. |
| Executed only once per object creation. | Can be called multiple times during the object's lifetime. |
class Student {
// Constructor
Student() {
System.out.println("Constructor Called");
}
// Method
void display() {
System.out.println("Method Called");
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student(); // Constructor executes automatically
s.display(); // Method called explicitly
}
}A constructor hasno return type- not evenvoid. If you add a return type, Java treats it as a regular method, not a constructor.
Can a constructor be static? NO. A constructor is called with an object (vianew). Static members belong to the class and don't require objects. Making a constructor static is contradictory and illegal in Java.
Can a constructor be final? NO .finalprevents overriding. Constructors are never inherited or overridden, sofinalhas no meaning for constructors.
Java has the following types of constructors:
Adefault constructor is a no-argument constructor that Javaautomatically provideswhen the programmer does not define any constructor. It initializes all instance variables to their default values (0, null, false).
**Use:**Allows creating objects without providing any initial values.
Aparameterized constructor is a constructor that accepts one or more parameters (arguments) to initialize the instance variables of an object with specific values at the time of creation.
Use: Allows creating objects with custom initial values, avoiding the need to set properties separately after object creation.
Constructor Overloading: Having multiple constructors in the same class with different parameter lists. Each constructor provides a different way to initialize an object.
Advantage: Provides flexibility - objects can be created in multiple ways based on available data. More readable and user-friendly API.
Disadvantage: If there are many constructors, it leads toboilerplate code(repeated, redundant initialization code). This is where constructor chaining helps.
this()statement.Constructor Chaining: The technique of calling one constructor from another constructor in the same class (or parent class) to avoid code duplication. It helps reduce boilerplate code.
this()statement: Used to call another constructor of thesame class. Must be thefirst statementin the constructor body.
Advantage: Reduces boilerplate code - initialization logic written once in one constructor, reused by others.
How many constructors can one constructor call? A constructor can call onlyONE other constructor- either usingthis()orsuper()- and that call must be the first statement.
Can this() be the second statement?NO. this()must always be thefirst statement in a constructor. If it is not the first, a compile-time error occurs.
Can a constructor call a method? YES. A constructor can call any method (static or non-static) of the class. This is perfectly legal.
Can we use this() inside a method? NO.this()(constructor call) is only allowed inside constructors, not inside regular methods.
Copy Constructor: A constructor that creates a new object as a copy of an existing object. Java does not provide a built-in copy constructor (unlike C++) - it must be written manually.
Shallow Copy: Copies the field values directly. For reference fields, copies the reference (address) - both objects point to the same inner object. Changes to the inner object via one reference affect the other.
Deep Copy: Creates completely independent copies of all fields, including all referenced objects. Changes to one object do not affect the other. Safer but more complex to implement.
Encapsulation is the OOP mechanism ofwrapping data (variables) and the methods that operate on that data together inside a class, andrestricting direct access to the datafrom outside the class.
Data Binding: The process of binding (combining) data and the methods that manipulate it together in a single unit (class) is called data binding. It is a key part of encapsulation.
How to achieve Encapsulation:
private.Getter (Accessor Method): A public method used toread/getthe value of a private field. Convention:getFieldName(). For boolean:isFieldName().
Setter (Mutator Method): A public method used toset/updatethe value of a private field. Convention:setFieldName(value). Can include validation logic.
Data Hiding: Making class fields private so that they cannot be directly accessed or modified from outside the class. Access is only through controlled getter/setter methods. This protects the object's internal state.
When to use encapsulation for validation: If a class needs to ensure that only valid data is set for its fields (e.g., age cannot be negative, salary cannot be zero), then encapsulation with setters containing validation logic should be used.
Advantages:
Disadvantages:
APOJO (Plain Old Java Object) is a simple, lightweight Java class that:
Key Characteristics of a POJO:
toString(),equals(),hashCode().AJava Beanis a special type of POJO that follows specific conventions defined by the JavaBeans specification. It is commonly used in frameworks like Spring, Hibernate, JSP.
Rules for a Java Bean Class:
POJO (Plain Old Java Object) and Java Bean are commonly used object models in Java. A Java Bean is a special type of POJO that follows additional rules defined by the JavaBeans specification.
| POJO | Java Bean |
|---|---|
| Has no strict rules and provides a flexible structure. | Must follow the JavaBeans specification. |
| Does not require any framework support. | Commonly used with frameworks and tools. |
| No mandatory no-argument constructor. | Must have a public no-argument constructor. |
| Fields may have any access modifier. | Fields should generally be private. |
| Getter and Setter methods are optional. | Getter and Setter methods are required for accessing properties. |
| Serialization is optional. | Often implements Serializable for persistence and framework support. |
| Used as a simple Java object. | Used for data transfer, persistence, and framework integration. |
| Not all POJOs are Java Beans. | All Java Beans are POJOs. |
Inheritance is an OOP mechanism where achild class (subclass) acquires the properties (fields) and behaviors (methods) of aparent class (superclass). It establishes an IS-A relationship and promotes code reusability.
In Java, inheritance is achieved using the extendskeyword.
superkeyword.The super keyword in Java refers to theimmediate parent class. It is used in three ways:
super.variableName- when a child class variable shadows the parent's variable.super.methodName()- when child overrides the method but also needs to call parent's version.super()orsuper(args)- must be the first statement in child constructor.thisandsuperkeyword.The this and super keywords are special reference variables in Java used to access class members and constructors. While this refers to the current class object, super is used to access members of the immediate parent class.
| this Keyword | super Keyword |
|---|---|
| Refers to the non-static members of the current class. | Refers to the non-static members of the immediate parent class. |
| Holds the reference of the current object under execution. | Represents the parent class reference associated with the current object. |
| Used to resolve variable shadowing within the same class. | Used to access parent class members hidden by child class members. |
this() invokes another constructor of the same class. | super() invokes the constructor of the immediate parent class. |
| Can be used to pass the current object as an argument. | Cannot be used to pass the current object. |
| Can be used to return the current object from a method. | Cannot be used to return the current object. |
| Used when working with members of the current class. | Used when accessing inherited members from the parent class. |
| Rule | Description |
|---|---|
| this() | Must be the first statement inside a constructor. |
| super() | Must be the first statement inside a constructor. |
| Constructor Chaining | A constructor can contain either this() or super(), but not both. |
super()statement. Difference betweenthis()andsuper().super()statement is used inside a child class constructor tocall the constructor of the immediate parent class. It must be thefirst statementin the child constructor.
If you don't writesuper(), Java automatically insertssuper()(implicit call to parent's no-arg constructor).
The this() and super() constructor calls are used for constructor chaining in Java. The this() call invokes another constructor of the same class, while the super() call invokes a constructor of the immediate parent class.
| this() | super() |
|---|---|
| Calls a constructor of the same class. | Calls a constructor of the immediate parent class. |
| Used for constructor chaining within the same class. | Used for constructor chaining between child and parent classes. |
| Must be the first statement inside a constructor. | Must be the first statement inside a constructor. |
| Helps avoid code duplication among constructors of the same class. | Ensures proper initialization of inherited members. |
| Can invoke both default and parameterized constructors of the same class. | Can invoke both default and parameterized constructors of the parent class. |
Cannot be used together with super() in the same constructor. | Cannot be used together with this() in the same constructor. |
| Used when multiple constructors exist in the current class. | Used when a child class needs to initialize parent class data. |
| Rule | Description |
|---|---|
| First Statement Rule | Both this() and super() must be the first statement inside a constructor. |
| Mutual Exclusion Rule | A constructor can contain either this() or super(), but never both. |
Multiple inheritance (a class having more than one parent class) is** NOT supported in Java with classesbecause it creates theDiamond Shape Problem (Diamond Ambiguity)**.
Diamond Shape Problem: When a class inherits from two classes that both have a common parent, and both override the same method, the compiler becomes confused about which version of the method to use. This ambiguity makes it impossible to determine which parent's constructorsuper()should call.
Resolution: Java resolves this usinginterfaces. A class can implement multiple interfaces - since interfaces (before Java 8) only had abstract methods (no implementation), there is no ambiguity. From Java 8, default methods in interfaces can cause ambiguity, but the implementing class must override the conflicting method.
Members NOT inherited from parent to child class:
Can a child class inherit constructors? NO. Constructors are never inherited. However, a child class constructor can call the parent's constructor usingsuper(). The reason is that a constructor is tied to the specific class name - a constructor namedAnimal()cannot be a constructor ofDog.
IS-A Relationship (Inheritance): When one class is a type of another class. Achieved viaextendsorimplements.
Dog IS-A Animal,Car IS-A Vehicle.HAS-A Relationship (Composition/Aggregation): When one class contains a reference to another class as a field/attribute.
Car HAS-A Engine,Employee HAS-A Address.Why favor HAS-A over IS-A?
Non-primitive type casting (also called object type casting or reference type casting) is the process of converting a reference variable from one class type to another class type within an inheritance hierarchy.
There are two directions:
Type casting between unrelated classes is NOT allowed and results in a compile-time error orClassCastException.
Upcasting is converting a child class object reference to a parent class reference type. The object remains a child class object in memory, but the reference is typed as the parent.
Upcasting isimplicit (automatic)- Java does it without requiring explicit cast syntax because it is always safe (child IS-A parent).
Downcasting is converting a parent class reference back to a child class reference type to access child-specific members. The underlying object must actually be an instance of the child class.
Downcasting isexplicit (manual)- requires explicit cast operator. Java requires the programmer to take responsibility for this potentially unsafe operation.
After Upcasting (child → parent reference):
After Downcasting (parent → child reference):
ClassCastException is a runtime exception that occurs when you try to downcast an object to a type that it is not actually an instance of.
Safe Downcasting usinginstanceof: Always check usinginstanceofbefore downcasting to prevent ClassCastException.
pattern matching instanceof
if (a instanceof Dog d) { d.bark(); }
Polymorphism means "many forms." It is the ability of an entity (method or object) to behave differently in different situations.
Types of Polymorphism in Java:
Method Overloading is having multiple methods with thesame namebutdifferent parameter lists(different number, type, or order of parameters) within the same class.
Advantage: We can achieve different forms of behavior with the same method name, so the user doesn't have to remember many different names for similar operations. It reduces complexity and confusion.
println()
print()
Method Overriding is when a child class provides its own specific implementation of a method that is already defined in its parent class. The method in the child has the same name, same parameters, and same (or covariant) return type.
Conditions for Method Overriding:
Advantage: We can achieve/update new features from child class by changing/overriding old implementations of parent class at runtime - making the application flexible and extensible.
Method Overloading and Method Overriding are two important ways of achieving polymorphism in Java. Overloading occurs within the same class, while overriding occurs between parent and child classes.
| Method Overloading | Method Overriding |
|---|---|
| Achieved within the same class. | Achieved between a parent class and a child class. |
| Method name remains the same, but parameter list must be different. | Method name, parameter list, and return type must be the same. |
| Can be applied to both static and non-static methods. | Applies only to non-static methods. |
| Represents Compile-Time (Static) Polymorphism. | Represents Runtime (Dynamic) Polymorphism. |
| Method selection is performed during compilation. | Method selection is performed during runtime. |
| Generally provides faster execution. | Slightly slower because method resolution occurs at runtime. |
The main() method can be overloaded. | The main() method cannot be overridden because it is static. |
| Execution depends on the reference type and method signature. | Execution depends on the actual object created at runtime. |
| Inheritance is not required. | Inheritance is mandatory. |
| Used to increase method flexibility. | Used to provide a specific implementation in the child class. |
Can we override the main method? NO. The main method is static, and static methods cannot be overridden. You can define a method with the same signature in a child class, but it will be method hiding, not overriding. JVM will still call the parent's main method.
Can we override static methods? NO.
Why can't we override static methods? Static methods belong to the class , not to any object instance. Method overriding requires runtime polymorphism - the JVM decides which method to call based on the actual object type at runtime. Since static methods don't require objects, there is no runtime dispatch mechanism. What looks like "overriding" of static methods is actuallymethod hiding- the child class hides the parent's static method.
Covariant Return Type allows a child class to override a method and return a subtype (more specific type) of the return type declared in the parent class method.
Introduced in Java 5, it allows overriding methods to return a subclass type while still satisfying the parent class contract.
This is useful in factory patterns and fluent builder APIs where you want the overridden method to return the more specific type without needing explicit casting.
Polymorphism allows a single interface to represent different forms of behavior. In Java, polymorphism is mainly classified into Compile-Time Polymorphism and Runtime Polymorphism.
| Compile-Time Polymorphism | Runtime Polymorphism |
|---|---|
| Method binding is performed by the compiler during compilation. | Method binding is performed by the JVM during program execution. |
| Execution is generally faster. | Execution is slightly slower due to runtime method resolution. |
| Primarily achieved through method overloading. | Primarily achieved through method overriding. |
| The method to execute is known at compile time. | The method to execute is determined at runtime. |
| Also known as Static Binding or Early Binding. | Also known as Dynamic Binding or Late Binding. |
| Inheritance is not required. | Inheritance is required. |
| Decision is based on method signature. | Decision is based on the actual object created at runtime. |
| More efficient because no runtime decision is needed. | Provides greater flexibility and extensibility. |
| Example: Method Overloading. | Example: Method Overriding. |
Abstraction is the OOP mechanism ofhiding internal implementation details and showing only the essential features/functionalityto the user. The user knows WHAT something does, not HOW it does it.
Real-world examples:
How to achieve Abstraction in Java:
Anabstract class is a class declared with theabstractkeyword. It is designed to be extended by subclasses and serves as a base/template.
Can we create an object of an abstract class? NO.
Why not? An abstract class may containabstract methods (methods without a body/implementation). If we could create an object and call an abstract method, the JVM would not know what code to execute (since there is no implementation). Therefore, Java prevents object creation of abstract classes.
A Class is a blueprint for creating objects and contains complete implementations. An Abstract Class is a special type of class that cannot be instantiated and is used to provide a common template for its subclasses.
| Class | Abstract Class |
|---|---|
Declared using the class keyword. | Declared using the abstract class keyword. |
| Objects can be created directly. | Objects cannot be created directly. |
| Methods are generally concrete (implemented). | Can contain both abstract and concrete methods. |
| Used to provide complete implementation. | Used to provide partial or complete implementation. |
| Suitable when the class is fully defined and ready to use. | Suitable when a common base structure is needed for child classes. |
| Subclass implementation is optional. | Child classes must implement inherited abstract methods. |
| Cannot contain abstract methods. | Can contain one or more abstract methods. |
| Supports inheritance and object creation. | Supports inheritance but prevents direct object creation. |
| Used when behavior is completely known. | Used when some behavior is common and some behavior varies. |
new keyword.abstract.Encapsulation and Abstraction are two fundamental Object-Oriented Programming (OOP) concepts. Encapsulation focuses on protecting data, while Abstraction focuses on hiding implementation details and exposing only essential functionality.
| Encapsulation | Abstraction |
|---|---|
| Restricts direct access to data and provides controlled access through methods. | Shows only essential functionality while hiding implementation details. |
| Achieved using private fields along with public getter and setter methods. | Achieved using abstract classes and interfaces. |
| Focuses on hiding data. | Focuses on hiding implementation details. |
| Provides data security and integrity. | Reduces complexity and improves usability. |
| Controls how data is accessed and modified. | Controls what functionality is visible to the user. |
| Protects object state from unauthorized access. | Hides unnecessary implementation details from users. |
| Implemented mainly through access modifiers. | Implemented mainly through inheritance and polymorphism. |
| Example: Private variables accessed through getter and setter methods. | Example: Using an interface without knowing its implementation class. |
Q.91 What is an interface? How do we design one?
Aninterfaceis a blueprint of a class. It defines a contract - a set of abstract methods (and constants) that implementing classes must provide. Before Java 8, interfaces could only have abstract methods and constants.
Designed using theinterfacekeyword:
extends.implements.Default Method (Java 8): A concrete method inside an interface with a body. Implementing classes get this method for free (they don't have to override it, but can). Used to add new methods to interfaces without breaking existing implementing classes.
Static Method (Java 8): A utility/helper method inside an interface that belongs to the interface itself. Cannot be overridden. Called using the interface name.
Private Method (Java 9): A helper method inside the interface that can only be used by other default or static methods within the same interface. Used to achieve code reusability within the interface without exposing the helper to implementing classes.
Functional Interface: An interface that hasexactly ONE abstract method. Can have any number of default or static methods. Used with Lambda expressions in Java 8+. Annotated with@FunctionalInterface.
Examples: Runnable, Callable, Comparator, Predicate, Consumer, Supplier, Function.
Marker/Tagged Interface: An interface with NO methods and NO fields (completely empty). Used to mark/tag a class to indicate a capability or provide metadata to the JVM/framework.
Examples:
Serializable- marks class as serializableCloneable- marks class as cloneableRemote- marks class for RMIA Class is used to define objects with state and behavior, whereas an Interface is used to define a contract that classes must implement.
| Class | Interface |
|---|---|
Declared using the class keyword. | Declared using the interface keyword. |
| Objects can be created directly (if the class is not abstract). | Objects cannot be created directly. |
| Variables can be static, non-static, final, or non-final. | Variables are implicitly public static final. |
| Constructors are allowed. | Constructors are not allowed. |
| Methods can be concrete, abstract, static, or final. | Methods are public abstract by default (except default and static methods introduced in Java 8). |
| Static and non-static initialization blocks are allowed. | Initialization blocks are not allowed. |
| Supports single inheritance only. | Supports multiple inheritance through multiple interfaces. |
| Used when both state and behavior with implementation are required. | Used when only a behavior contract is required. |
| A class can extend only one class. | An interface can extend multiple interfaces. |
Declared using the extends keyword for inheritance. | Implemented using the implements keyword. |
Abstract Classes and Interfaces are both used to achieve abstraction in Java. However, they differ in terms of implementation, inheritance, variables, and usage.
| Abstract Class | Interface |
|---|---|
| Can provide 0% to 100% abstraction. | Provided 100% abstraction before Java 8. |
| Variables can be static, non-static, final, or non-final. | Variables are implicitly public static final. |
| Constructors are allowed. | Constructors are not allowed. |
| Methods can be abstract or concrete. | Methods are public abstract by default; Java 8+ also supports default and static methods. |
| Supports only single inheritance. | Supports multiple inheritance. |
| Used when both state and behavior are required. | Used when only a behavior contract is required. |
A class extends an abstract class using the extends keyword. | A class implements an interface using the implements keyword. |
| Can contain instance variables. | Cannot contain instance variables. |
| Can have access modifiers such as private, protected, public, and default. | Methods are public by default (except private methods introduced in Java 9). |
| Suitable for closely related classes sharing common code. | Suitable for unrelated classes that must follow a common contract. |
Q.95 Mention important features of Java 8. [Very Important]
Java 8, released in March 2014, is one of the most significant versions of Java. It introduced several powerful features that made Java programming more concise, functional, readable, and efficient. These enhancements helped developers write less code, improve performance, and simplify data processing.
The major features introduced in Java 8 are described below.
A Functional Interface is an interface that contains exactly one abstract method. It serves as the foundation for Lambda Expressions and Functional Programming in Java.
Functional Interfaces can contain multiple default and static methods, but only one abstract method.
@FunctionalInterface
interface Calculator {
int add(int a, int b);
}Lambda Expressions provide a concise way to represent anonymous functions. They eliminate the need to create separate classes for implementing functional interfaces.
(parameters) -> expressionCalculator c = (a, b) -> a + b;
System.out.println(c.add(10, 20));Calculator c = new Calculator() {
@Override
public int add(int a, int b) {
return a + b;
}
};The Stream API allows processing collections of data using a functional and declarative approach. Streams do not store data; instead, they process data from collections.
List<Integer> numbers =
Arrays.asList(10, 20, 30, 40, 50);
numbers.stream()
.filter(n -> n > 20)
.forEach(System.out::println);30
40
50Java 8 introduced the forEach() method in the Iterable interface to simplify collection traversal.
for(String name : names) {
System.out.println(name);
}names.forEach(System.out::println);List<String> names =
Arrays.asList("John", "David", "Alex");
names.forEach(System.out::println);The Optional class is a container object introduced to reduce the chances of NullPointerException.
Instead of returning null values, methods can return an Optional object.
Optional<String> name =
Optional.of("Java");
System.out.println(name.get());Optional<String> name =
Optional.ofNullable(null);
System.out.println(
name.orElse("Default Value")
);Default ValueJava 8 introduced the java.time package to replace the old Date and Calendar APIs.
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
System.out.println(date);
System.out.println(time);2026-06-04
12:30:45Before Java 8, interfaces could contain only abstract methods. Java 8 introduced default methods, allowing interfaces to provide method implementations.
interface Vehicle {
default void start() {
System.out.println("Vehicle Started");
}
}Java 8 allows interfaces to contain static methods.
interface MathUtility {
static int square(int n) {
return n * n;
}
}System.out.println(
MathUtility.square(5)
);25| Feature | Purpose |
|---|---|
| Functional Interface | Supports functional programming using a single abstract method. |
| Lambda Expression | Provides concise implementation of functional interfaces. |
| Stream API | Processes collection data efficiently using pipelines. |
| forEach() | Simplifies collection iteration. |
| Optional Class | Helps avoid NullPointerException. |
| Date and Time API | Provides modern date and time handling. |
| Default Methods | Allows implementation inside interfaces. |
| Static Methods | Allows utility methods inside interfaces. |
Java 8 brought revolutionary improvements to the Java platform by introducing Functional Programming concepts, Lambda Expressions, Stream API, Optional Class, Modern Date-Time API, and enhanced Interface capabilities. These features significantly improved code readability, maintainability, performance, and developer productivity, making Java 8 one of the most widely adopted Java versions in software development.
Java provides many built-in interfaces that support multithreading, sorting, functional programming, object serialization, cloning, and collection processing. Some of the most important interfaces are explained below.
The Runnable interface is a Functional Interface used for creating and executing threads. It contains only one abstract method named run().
void run()class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyTask());
t.start();
}
}The Comparable interface is used to define the natural ordering of objects. The class itself implements this interface.
int compareTo(T obj)class Student implements Comparable<Student> {
int age;
Student(int age) {
this.age = age;
}
@Override
public int compareTo(Student s) {
return this.age - s.age;
}
}The Comparator interface is used for custom sorting. Unlike Comparable, it is implemented outside the target class.
int compare(T o1, T o2)Comparator<Student> byAge =
(s1, s2) -> s1.age - s2.age;Predicate<T> InterfaceThe Predicate<T> interface represents a condition that returns either true or false.
boolean test(T t)Predicate<Integer> isEven =
n -> n % 2 == 0;
System.out.println(isEven.test(10));trueSupplier<T> InterfaceThe Supplier<T> interface supplies or generates data without taking any input.
T get()Supplier<String> supplier =
() -> "Hello Java";
System.out.println(supplier.get());Hello JavaConsumer<T> InterfaceThe Consumer<T> interface accepts an input and performs an operation without returning any result.
void accept(T t)Consumer<String> consumer =
name -> System.out.println(name);
consumer.accept("John");JohnFunction<T, R> InterfaceThe Function<T,R> interface accepts one input and returns a transformed output.
R apply(T t)Function<String, Integer> length =
str -> str.length();
System.out.println(
length.apply("Java")
);4The Serializable interface is a Marker Interface used to indicate that an object can be converted into a byte stream.
import java.io.Serializable;
class Employee implements Serializable {
int id;
String name;
}Serializable does not contain any methods.
The Cloneable interface is a Marker Interface used to indicate that an object can be cloned.
class Student implements Cloneable {
int age = 20;
@Override
protected Object clone()
throws CloneNotSupportedException {
return super.clone();
}
}Without implementing Cloneable, calling clone() throws CloneNotSupportedException.
| Interface | Main Method | Purpose |
|---|---|---|
| Runnable | run() | Thread creation and execution. |
| Comparable | compareTo() | Natural ordering of objects. |
| Comparator | compare() | Custom sorting logic. |
| Predicate<T> | test() | Condition checking and filtering. |
| Supplier<T> | get() | Provides values without input. |
| Consumer<T> | accept() | Consumes input and performs actions. |
| Function<T,R> | apply() | Transforms input into output. |
| Serializable | No Methods | Object serialization. |
| Cloneable | No Methods | Object cloning. |
Runnable, Comparable, Comparator, Predicate, Supplier, Consumer, Function, Serializable, and Cloneable are among the most important interfaces in Java. They support multithreading, sorting, functional programming, object persistence, and object cloning. Understanding these interfaces is essential for modern Java development, especially when working with Java 8 features, collections, streams, and enterprise applications.
finalkeyword?The final keyword in Java is a non-access modifier used to restrict the user. It can be applied to variables, methods, and classes, and it has different effects in each context:
VVI
The final keyword in Java is used to restrict modification. It can be applied to classes, methods, and variables. When applied to a class or method, it prevents inheritance or overriding respectively.
YES.
A class can be declared as final. A final class cannot be inherited or extended by any other class.
final class Vehicle {
void display() {
System.out.println("Vehicle Class");
}
}NO.
A final class cannot be extended. Attempting to inherit from a final class causes a compile-time error.
final class Vehicle {
}
class Car extends Vehicle {
}Compile-Time Error:
Cannot inherit from final VehicleYES.
A method can be declared as final. A final method can be inherited but cannot be overridden by a child class.
class Parent {
final void show() {
System.out.println("Parent Method");
}
}NO.
A final method cannot be overridden in a subclass.
class Parent {
final void show() {
System.out.println("Parent Method");
}
}
class Child extends Parent {
@Override
void show() {
System.out.println("Child Method");
}
}Compile-Time Error:
Cannot override the final method from ParentNO.
An abstract class cannot be declared as final.
final abstract class Animal {
}Compile-Time ErrorNO.
An abstract method cannot be declared as final.
abstract class Animal {
abstract final void sound();
}Compile-Time Error| Question | Answer | Reason |
|---|---|---|
| Can a class be final? | YES | Prevents inheritance. |
| Can we extend a final class? | NO | Final classes cannot be subclassed. |
| Can a method be final? | YES | Prevents method overriding. |
| Can we override a final method? | NO | Final methods cannot be overridden. |
| Can an abstract class be final? | NO | Abstract requires inheritance; final prevents inheritance. |
| Can an abstract method be final? | NO | Abstract requires overriding; final prevents overriding. |
VVI
The final keyword is used to make variables constant, prevent method overriding, and restrict inheritance. Final variables must be initialized exactly once, either during declaration or through allowed initialization mechanisms.
A static final variable belongs to the class and must be initialized before the class is used.
A static final variable can be initialized in the following ways:
class Test {
static final int MAX_VALUE = 100;
}class Test {
static final int MAX_VALUE;
static {
MAX_VALUE = 100;
}
}A non-static final variable (instance final variable) belongs to an object and must be initialized before object creation is completed.
A non-static final variable can be initialized in the following ways:
class Student {
final int age = 20;
}class Student {
final int age;
{
age = 20;
}
}class Student {
final int age;
Student() {
age = 20;
}
}YES.
A final method can be overloaded because overloading and overriding are completely different concepts.
final prevents overriding in child classes.final does not prevent creating methods with the same name but different parameter lists in the same class.class Calculator {
final void add() {
System.out.println("No Parameters");
}
final void add(int a, int b) {
System.out.println(a + b);
}
final void add(double a, double b) {
System.out.println(a + b);
}
}Method Overloading SuccessfulBecause:
final keyword only restricts overriding.| Concept | Answer | Explanation |
|---|---|---|
| Static Final Variable Initialization | Declaration or Static Block | Must be initialized before the class is used. |
| Instance Final Variable Initialization | Declaration, Instance Block, or Constructor | Must be initialized before object creation completes. |
| Can a Final Method be Overloaded? | YES | Final prevents overriding, not overloading. |
| Can a Final Method be Overridden? | NO | Final methods cannot be redefined in child classes. |
VVI
The final keyword is used in Java to prevent inheritance, method overriding, and modification of variables. However, it cannot be applied to constructors because constructors are not inherited.
NO.
A constructor cannot be declared as final.
The purpose of the final keyword is to prevent method overriding in child classes. Constructors are never inherited by child classes, so they cannot be overridden.
Since constructors are not inherited, applying the final keyword to a constructor has no meaning.
Therefore, Java does not allow constructors to be declared as final.
class Student {
final Student() {
}
}Compile-Time Error:
modifier final not allowed hereA final class is a class that cannot be extended or inherited.
String name = "Java";Examples:
Integer num = 100;
Double price = 99.99;System.out.println(Math.sqrt(25));System.out.println("Hello Java");StringBuilder sb = new StringBuilder("Java");StringBuffer sb = new StringBuffer("Java");| Question | Answer | Reason |
|---|---|---|
| Can a Constructor be final? | NO | Constructors are not inherited and therefore cannot be overridden. |
| Can a Constructor be Overloaded? | YES | Multiple constructors with different parameter lists are allowed. |
| Can a Constructor be Overridden? | NO | Constructors are never inherited. |
| Final Class | Purpose |
|---|---|
| String | Immutable text representation. |
| Integer | Wrapper class for int. |
| Double | Wrapper class for double. |
| Float | Wrapper class for float. |
| Long | Wrapper class for long. |
| Math | Mathematical utility methods. |
| System | System-level utility functionality. |
| StringBuilder | Mutable string manipulation. |
| StringBuffer | Thread-safe mutable string manipulation. |
In Java, classes are categorized as mutable or immutable based on whether the state of their objects can change after creation.
A Mutable Class is a class whose object state can be modified after the object has been created.
In other words, the values stored in the object's fields can be changed during its lifetime.
class Employee {
private String name;
Employee(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}Employee emp = new Employee("John");
emp.setName("David");
System.out.println(emp.getName());DavidAn Immutable Class is a class whose object state cannot be changed after the object has been created.
Once the object is initialized, its data remains constant throughout its lifetime.
final class Employee {
private final String name;
Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}Employee emp = new Employee("John");
System.out.println(emp.getName());JohnTo create an immutable class in Java, follow the rules below.
Making the class final prevents inheritance, which could otherwise break immutability.
final class Employee {
}This prevents direct access and modification.
private final String name;
private final int age;All values should be assigned during object creation.
Employee(String name, int age) {
this.name = name;
this.age = age;
}Setter methods allow modification of object state and therefore must be avoided.
// Not Allowed
public void setName(String name) {
this.name = name;
}Getter methods allow reading values without modifying them.
public String getName() {
return name;
}If the class contains mutable objects, return copies instead of the original object.
public Date getDate() {
return joiningDate;
}public Date getDate() {
return new Date(joiningDate.getTime());
}This technique is called Defensive Copying.
final class Employee {
private final int id;
private final String name;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}public class Main {
public static void main(String[] args) {
Employee emp =
new Employee(101, "John");
System.out.println(emp.getId());
System.out.println(emp.getName());
}
}| Mutable Class | Immutable Class |
|---|---|
| Object state can change after creation. | Object state cannot change after creation. |
| Setter methods are usually available. | Setter methods are not allowed. |
| Fields are generally non-final. | Fields are final. |
| Not inherently thread-safe. | Naturally thread-safe. |
| Examples: ArrayList, HashMap, StringBuilder. | Examples: String, Integer, LocalDate. |
A Mutable Class allows modification of object data after creation, whereas an Immutable Class does not allow any changes once the object is constructed. Immutable classes provide better security, thread safety, predictability, and maintainability. To design an immutable class, declare the class as final, make all fields private and final, initialize them through constructors, avoid setters, and use defensive copies for mutable fields.
final,finally, andfinalize()?| final | finally | finalize() |
|---|---|---|
| A keyword. | A keyword used with exception handling. | A method of the Object class. |
| Applied to variables, methods, and classes. | Used as a block after try-catch. | Invoked by the Garbage Collector before object destruction. |
| Prevents modification, overriding, or inheritance. | Executes regardless of whether an exception occurs. | Used for cleanup operations before garbage collection. |
final int x = 10; | finally { cleanup(); } | protected void finalize() |
A Package in Java is a namespace that groups related classes, interfaces, enums, annotations, and sub-packages together. Packages help organize code, avoid naming conflicts, and provide access control.
Packages are similar to folders in an operating system.
A package is a collection of related Java classes and interfaces stored in a directory structure.
java.langjava.utiljava.iojava.sqljava.timeimport java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number:");
int num = sc.nextInt();
System.out.println(num);
}
}Here, Scanner belongs to the java.util package.
A custom package is created using the package keyword.
package com.company.employee;
public class Employee {
public void display() {
System.out.println("Employee Package");
}
}import com.company.employee.Employee;
public class Main {
public static void main(String[] args) {
Employee emp = new Employee();
emp.display();
}
}Java follows the reverse domain name convention.
com.google.utils
com.amazon.shopping
com.microsoft.azure
org.apache.commonsYES.
A package can contain one or more sub-packages.
Package Name:
java.util.loggingExamples:
java.utiljava.util.loggingjava.time.format| Advantage | Description |
|---|---|
| Code Organization | Groups related classes and interfaces together. |
| Name Conflict Prevention | Allows classes with the same name in different packages. |
| Access Protection | Supports package-level access control. |
| Code Reusability | Packages can be reused across multiple projects. |
| Easy Maintenance | Makes large applications easier to manage. |
| Modular Development | Encourages separation of concerns. |
| Type | Description |
|---|---|
| Built-in Package | Provided by Java API such as java.util and java.io. |
| User-Defined Package | Created by programmers according to project requirements. |
A Package is a mechanism used to organize Java classes and interfaces into logical groups. Packages improve code organization, prevent naming conflicts, enhance security, and simplify maintenance. Custom packages are created using the package keyword and are generally named using the reverse domain naming convention.
Access Modifiers in Java control the visibility and accessibility of classes, variables, methods, and constructors. They help implement encapsulation and provide security by restricting access to program components.
Java provides four access modifiers:
publicprotecteddefault (package-private)private| Modifier | Same Class | Same Package | Subclass (Different Package) | Other Package |
|---|---|---|---|---|
| public | ✅ | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ✅ | ❌ |
| default (package-private) | ✅ | ✅ | ❌ | ❌ |
| private | ✅ | ❌ | ❌ | ❌ |
The public access modifier provides the widest accessibility.
public class Employee {
public void display() {
System.out.println("Public Method");
}
}The protected access modifier allows access within the same package and in subclasses located in different packages.
protected int salary;When no access modifier is specified, Java automatically assigns default access.
class Employee {
void display() {
System.out.println("Default Access");
}
}The private access modifier provides the highest level of access restriction.
private int age;NO.
A top-level (outer) class cannot be declared as private.
private class Employee {
}Compile-Time ErrorNO.
A top-level (outer) class cannot be declared as protected.
protected class Employee {
}Compile-Time ErrorOnly the following modifiers are allowed:
| Modifier | Allowed? |
|---|---|
| public | ✅ Yes |
| default | ✅ Yes |
| protected | ❌ No |
| private | ❌ No |
Nested classes can use all four access modifiers.
| Modifier | Allowed for Inner Class? |
|---|---|
| public | ✅ Yes |
| protected | ✅ Yes |
| default | ✅ Yes |
| private | ✅ Yes |
| protected | default |
|---|---|
| Accessible within the same package. | Accessible within the same package. |
| Accessible in subclasses of different packages. | Not accessible in subclasses of different packages. |
| Provides wider access. | Provides package-level access only. |
Package-Private is another name for the default access modifier.
class Employee {
}Access Modifiers control the visibility of Java components and play a major role in encapsulation and security. The public modifier provides maximum accessibility, while private provides maximum restriction. Top-level classes can only be public or default, whereas inner classes can use all four access modifiers.
VVI
Private methods have special access restrictions in Java. Since they are accessible only within their own class, they cannot participate in inheritance and overriding.
NO.
A private method cannot be overridden because it is not visible to child classes.
Since the child class cannot access the private method, it cannot override it.
If a child class declares a method with the same name and signature, it is treated as an entirely new method rather than an overridden method.
class Parent {
private void display() {
System.out.println("Parent Method");
}
}
class Child extends Parent {
void display() {
System.out.println("Child Method");
}
}The display() method in Child is not overriding the parent's method. It is a completely separate method.
NO.
Private methods belong exclusively to the class in which they are declared.
They are not visible outside the class and therefore cannot be inherited by child classes.
class Parent {
private void show() {
System.out.println("Private Method");
}
}
class Child extends Parent {
}The show() method does not become part of the Child class.
NO.
While overriding a method, the access modifier of the child method must be the same or more accessible than the parent method.
Reducing visibility causes a compile-time error.
class Parent {
public void display() {
}
}
class Child extends Parent {
protected void display() {
}
}Compile-Time Error:
Cannot reduce the visibility of the inherited method| Parent Method | Child Method | Allowed? |
|---|---|---|
| public | public | ✅ Yes |
| public | protected | ❌ No |
| protected | public | ✅ Yes |
| protected | protected | ✅ Yes |
| default | public | ✅ Yes |
| default | private | ❌ No |
You may increase visibility, but you cannot decrease it.
NO.
If every constructor of a class is private, a child class cannot call the parent constructor using super().
As a result, inheritance becomes impossible.
class Parent {
private Parent() {
}
}
class Child extends Parent {
}Compile-Time Error
Parent() has private access in ParentPrivate constructors are commonly used in:
class Singleton {
private Singleton() {
}
}This prevents other classes from creating or inheriting objects directly.
| Question | Answer | Reason |
|---|---|---|
| Can a private method be overridden? | NO | Private methods are not visible to child classes. |
| Can private methods be inherited? | NO | Private members belong only to the declaring class. |
| Can visibility be reduced while overriding? | NO | Visibility can only remain the same or become broader. |
| Can a class be inherited if all constructors are private? | NO | The child class cannot call the parent constructor. |
VVI
YES, Java allows constructors to be declared as private.
A private constructor can only be accessed from within the same class. Objects of such a class cannot be created directly from outside the class using the new keyword.
Private constructors are commonly used to control object creation and enforce specific design patterns.
A private constructor is a constructor declared using the private access modifier.
class Employee {
private Employee() {
System.out.println("Private Constructor");
}
}public class Main {
public static void main(String[] args) {
Employee emp = new Employee();
}
}Compile-Time Error:
Employee() has private access in EmployeeThe Singleton Pattern ensures that only one object of a class can exist throughout the application.
A private constructor prevents external object creation.
class Singleton {
private static Singleton instance =
new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}Singleton obj =
Singleton.getInstance();A private constructor forces object creation through static factory methods.
class Employee {
private Employee() {
}
public static Employee createObject() {
return new Employee();
}
}Employee emp =
Employee.createObject();Classes containing only static methods do not need objects.
A private constructor prevents unnecessary instantiation.
class Utility {
private Utility() {
}
public static void display() {
System.out.println("Utility Method");
}
}Utility.display();A child class must call a parent constructor using super().
If all constructors are private, inheritance becomes impossible.
class Parent {
private Parent() {
}
}
class Child extends Parent {
}Compile-Time Error
Parent() has private access in Parent| Advantage | Description |
|---|---|
| Controlled Object Creation | Objects can only be created through approved methods. |
| Supports Singleton Pattern | Ensures a single object instance. |
| Supports Factory Pattern | Allows object creation through factory methods. |
| Prevents Unnecessary Instantiation | Useful for utility classes. |
| Prevents Inheritance | Child classes cannot invoke private constructors. |
| Question | Answer |
|---|---|
| Can a constructor be private? | ✅ Yes |
| Can objects be created outside the class? | ❌ No |
| Used in Singleton Pattern? | ✅ Yes |
| Used in Factory Pattern? | ✅ Yes |
| Used in Utility Classes? | ✅ Yes |
| Can it prevent inheritance? | ✅ Yes |
A Singleton Class is a design pattern that ensures a class has only one instance throughout the entire application and provides a global access point to that instance.
Singleton is one of the most commonly used design patterns in Java and is widely used when exactly one object is required to coordinate actions across the system.
A Singleton Class allows only one object to be created and provides controlled access to that object.
A Singleton class generally contains the following components:
Prevents object creation from outside the class.
private Singleton() {
}Stores the single object of the class.
private static Singleton instance;Returns the Singleton object.
public static Singleton getInstance() {
return instance;
}In Eager Initialization, the object is created when the class is loaded into memory.
class Singleton {
private static final Singleton instance =
new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}Singleton obj =
Singleton.getInstance();In Lazy Initialization, the object is created only when it is requested for the first time.
class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}Singleton obj =
Singleton.getInstance();| Eager Initialization | Lazy Initialization |
|---|---|
| Object is created during class loading. | Object is created when first requested. |
| Consumes memory immediately. | Saves memory until object is required. |
| Thread-safe by default. | Not thread-safe without synchronization. |
| Faster object retrieval. | Object creation occurs on first access. |
| May create unnecessary objects. | Creates object only when needed. |
Singleton is commonly used when exactly one shared object is required.
| Application | Purpose |
|---|---|
| Configuration Settings | Maintains common application configuration. |
| Logger | Provides centralized logging. |
| Database Connection Pool | Manages shared database resources. |
| Cache Manager | Maintains a single cache instance. |
| Thread Pool Manager | Controls worker threads centrally. |
| Service Locator | Provides access to shared services. |
| Selenium WebDriver | Maintains a single browser driver instance. |
| Feature | Singleton Class |
|---|---|
| Number of Objects | Only One |
| Constructor | Private |
| Object Access | Public Static Method |
| Memory Usage | Efficient |
| Common Usage | Logger, Configuration, Cache, Database Pool |
Java is a high-level, object-oriented, platform-independent programming language that follows the Write Once Run Anywhere principle.
Java source code is compiled into bytecode, which can run on any system that has a JVM installed.
JVM (Java Virtual Machine) executes Java bytecode and provides platform independence.
JDK is used for development, JRE provides the runtime environment, and JVM executes Java bytecode.
Encapsulation, Inheritance, Polymorphism, and Abstraction are the four pillars of Object-Oriented Programming.
Method overloading occurs in the same class with different parameter lists, while method overriding occurs in inheritance with the same method signature.
Encapsulation is the process of binding data and methods together and restricting direct access to data using private fields and public getters/setters.
Inheritance allows a child class to acquire properties and behaviors of a parent class using the extends keyword.
Polymorphism allows the same method or object to behave differently in different situations.
Abstraction hides implementation details and exposes only essential functionality through abstract classes and interfaces.
A constructor is a special member of a class used to initialize objects when they are created.
A constructor initializes objects and has no return type, whereas a method performs operations and must have a return type.
Java provides four access modifiers: public, protected, default, and private, which control visibility and accessibility.
A package is a namespace used to organize related classes and interfaces and prevent naming conflicts.
A Singleton class ensures that only one object of the class exists throughout the application.