Constructors in Java
Introduction
In Java, a constructor is a special method that is used to initialize objects.
When an object is created, the constructor is automatically called.
It looks like a normal method, but it has the same name as the class and no return type (not even
void).
Definition
A constructor in Java is a block of code that initializes the newly created object.
Important Points About Constructors
1. Constructor name must be same as class name.
2. Constructor has no return type.
3. It is automatically invoked when an object is created.
4. Constructors can be parameterized or non-parameterized.
5. If you don’t write a constructor, Java provides a default constructor automatically.
Types of Constructors
There are two main types of constructors in Java:
1. Default (Non-Parameterized) Constructor
• Does not take any arguments.
• Used to assign default values to objects.
2. Parameterized Constructor
• Takes parameters (arguments).
• Used to assign specific values to object properties.
Example Program
// Example of Constructors in Java
class Student {
int rollNo;
String name;
// Default Constructor
Student() {
rollNo = 0;
name = "Unknown";
[Link]("Default constructor called");
// Parameterized Constructor
Student(int r, String n) {
rollNo = r;
name = n;
[Link]("Parameterized constructor called");
void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
public class ConstructorExample {
public static void main(String[] args) {
// Object creation
Student s1 = new Student(); // calls default constructor
Student s2 = new Student(101, "Anurag"); // calls parameterized constructor
// Display information
[Link]();
[Link]();
}
Output
Default constructor called
Parameterized constructor called
Roll No: 0, Name: Unknown
Roll No: 101, Name: Anurag
Diagram: Working of Constructor
+------------------------+
| Student |
+------------------------+
| rollNo | name |
+------------------------+
| Student() | --> Default Constructor
| Student(int, String) | --> Parameterized Constructor
| display() |
+------------------------+
⬇ Object Created
----------------------------------
Student s1 = new Student(); --> calls Student()
Student s2 = new Student(101,"A"); --> calls Student(int,String)
----------------------------------
Advantages of Using Constructors
1. Automatic initialization of objects.
2. Improves readability and reduces coding errors.
3. Makes program organized and efficient.
4. Reusability — we can overload constructors for different initializations.
Constructor Overloading
You can create multiple constructors in a class with different parameter lists.
This is called constructor overloading.
Example:
class Example {
Example() {
[Link]("No argument constructor");
Example(int x) {
[Link]("Parameterized constructor: " + x);
Dynamic Method Dispatch and Use of Final Keyword in Java
1. Introduction
Java is an object-oriented programming language, and one of its strongest features is runtime
polymorphism.
This feature is achieved using Dynamic Method Dispatch.
Also, Java provides the final keyword to restrict changes in variables, methods, or classes.
Let’s understand both concepts one by one.
2. Dynamic Method Dispatch (Runtime Polymorphism)
Definition:
Dynamic Method Dispatch is the process of calling an overridden method through a reference
variable of the parent class, which is determined at runtime, not compile-time.
This means Java decides which method to call (parent’s or child’s) during program execution.
Why It Is Called “Dynamic”?
Because the method that will be executed is decided dynamically at runtime, based on the object
being referred to.
Key Points:
1. It is used to achieve runtime polymorphism.
2. It works only with method overriding.
3. The reference variable of the parent class can refer to an object of the child class.
4. The method call is resolved at runtime.
Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
public class DynamicDispatchExample {
public static void main(String[] args) {
Animal a; // reference of parent class
a = new Dog(); // object of subclass Dog
[Link](); // calls Dog's sound()
a = new Cat(); // object of subclass Cat
[Link](); // calls Cat's sound()
Output:
Dog barks
Cat meows
Diagram:
+-------------------+
| Animal |
|-------------------|
| sound() |
+-------------------+
▲
|
-------------------------
| |
+-------+ +-------+
| Dog | | Cat |
| sound()| | sound()|
+-------+ +-------+
At runtime:
Animal a = new Dog(); → Dog’s sound()
Animal a = new Cat(); → Cat’s sound()
Explanation:
• The reference variable a belongs to the parent class Animal.
• At runtime, it points to the object of a subclass (Dog or Cat).
• The method that gets executed depends on the actual object type, not the reference type.
• Hence, the child class method overrides the parent’s method.
Advantages of Dynamic Method Dispatch
1. Helps achieve runtime polymorphism.
2. Makes programs flexible and extendable.
3. Allows code reusability.
4. Improves maintainability of object-oriented programs.
3. Use of Final Keyword in Java
The final keyword in Java is used as a non-access modifier that restricts changes to variables,
methods, and classes.
Meaning:
The final keyword means “cannot be changed or modified”.
Use of final Description Example
1. Final Variable Value cannot be changed once assigned. final int x = 10;
2. Final Method Method cannot be overridden by subclasses. final void show() { }
3. Final Class Class cannot be inherited. final class Test { }
Examples:
(a) Final Variable Example
class Demo {
final int SPEED_LIMIT = 60;
void show() {
// SPEED_LIMIT = 80; // Error! Can't change final variable
[Link]("Speed limit is " + SPEED_LIMIT);
}
}
(b) Final Method Example
class Vehicle {
final void run() {
[Link]("Vehicle is running");
class Car extends Vehicle {
// void run() { } // Error! Cannot override final method
(c) Final Class Example
final class Bike {
void display() {
[Link]("This is a final class");
// class Honda extends Bike { } // Error! Can't inherit final class
Diagram: Final Keyword
+---------------------------+
| final keyword in Java |
+---------------------------+
| 1. final variable | --> value cannot change
| 2. final method | --> cannot override
| 3. final class | --> cannot inherit
+---------------------------+
Advantages of Using final Keyword
1. Security — prevents unwanted modification.
2. Reliability — ensures values remain constant.
3. Efficiency — helps compiler optimize performance.
4. Control — allows programmer to fix parts of code.
4. Difference Between Dynamic Method Dispatch and final Keyword
Basis Dynamic Method Dispatch final Keyword
Purpose Achieve runtime polymorphism Restrict modification
Works On Method overriding Variables, methods, classes
Execution Time Runtime Compile-time
Flexibility Increases flexibility Reduces flexibility
Example a = new Dog(); [Link](); final int x = 10;
5. Summary
Concept Meaning Example
Dynamic Method Dispatch Calls overridden method at runtime Animal a = new Dog(); [Link]();
final Variable Constant value final int a = 10;
final Method Cannot override final void run()
final Class Cannot inherit final class A {}
Types of Inheritance in Java
1. Introduction
Inheritance is one of the most important features of Object-Oriented Programming (OOP).
It allows a new class (child class) to acquire the properties and behavior (methods and variables) of
an existing class (parent class).
This helps in code reusability, reduces redundancy, and improves program structure.
Definition
Inheritance is the process by which one class inherits the properties (fields) and behaviors (methods)
of another class.
The class that inherits is called the subclass (child class), and the class whose members are inherited
is called the superclass (parent class).
Syntax:
class Parent {
// parent properties and methods
class Child extends Parent {
// child properties and methods
}
Here, the extends keyword is used to inherit from the parent class.
Advantages of Inheritance
1. Promotes code reusability.
2. Reduces code duplication.
3. Improves readability and maintainability.
4. Supports method overriding and polymorphism.
2. Types of Inheritance in Java
Java supports five types of inheritance (the last one — multiple inheritance — is achieved indirectly).
(1) Single Inheritance
Definition:
When one class inherits another class, it is called Single Inheritance.
Diagram:
Parent
▼
Child
Example:
class Animal {
void eat() {
[Link]("Eating...");
class Dog extends Animal {
void bark() {
[Link]("Barking...");
public class SingleInheritance {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // from parent class
[Link](); // from child class
Output:
Eating...
Barking...
(2) Multilevel Inheritance
Definition:
When a class is derived from another class, which is itself derived from another class.
Diagram:
Grandparent
▼
Parent
▼
Child
Example:
class Animal {
void eat() {
[Link]("Eating...");
class Dog extends Animal {
void bark() {
[Link]("Barking...");
class Puppy extends Dog {
void weep() {
[Link]("Weeping...");
public class MultilevelInheritance {
public static void main(String[] args) {
Puppy p = new Puppy();
[Link]();
[Link]();
[Link]();
Output:
Eating...
Barking...
Weeping...
(3) Hierarchical Inheritance
Definition:
When multiple classes inherit from the same parent class, it is called Hierarchical Inheritance.
Diagram:
Parent
/ \
▼ ▼
Child1 Child2
Example:
class Animal {
void eat() {
[Link]("Eating...");
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
class Cat extends Animal {
void meow() {
[Link]("Meowing...");
public class HierarchicalInheritance {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
Cat c = new Cat();
[Link]();
[Link]();
Output:
Eating...
Barking...
Eating...
Meowing...
(4) Multiple Inheritance (Through Interfaces Only)
Definition:
Java does not support multiple inheritance using classes (to avoid ambiguity),
but it supports it through interfaces.
Diagram:
Interface1 Interface2
\ /
\ /
▼
Class
Example:
interface A {
void show();
interface B {
void display();
class C implements A, B {
public void show() {
[Link]("Showing...");
public void display() {
[Link]("Displaying...");
public class MultipleInheritance {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
Output:
Showing...
Displaying...
(5) Hybrid Inheritance
Definition:
Hybrid inheritance is a combination of two or more types of inheritance.
Java does not directly support hybrid inheritance using classes because it can cause ambiguity
problems,
but it can be achieved using interfaces.
Example (via interfaces):
interface A {
void methodA();
interface B extends A {
void methodB();
class C {
void methodC() {
[Link]("Method of class C");
class D extends C implements B {
public void methodA() {
[Link]("Method A");
public void methodB() {
[Link]("Method B");
public class HybridInheritance {
public static void main(String[] args) {
D obj = new D();
[Link]();
[Link]();
[Link]();
3. Diagram Summary of All Types
Single:
A→B
Multilevel:
A→B→C
Hierarchical:
/\
B C
Multiple (via Interfaces):
I1 I2
\ /
\/
Hybrid:
Combination of above (via interfaces)
4. Difference Between Inheritance Types
Type Description Supported by Java Example Keyword
Single One class inherits another Yes extends
Type Description Supported by Java Example Keyword
Multilevel Class derived from another derived class Yes extends
Hierarchical Multiple classes inherit one parent Yes extends
Multiple One class inherits multiple parents Only via Interfaces implements
Hybrid Combination of inheritance types Only via Interfaces extends + implements
5. Advantages of Inheritance
1. Code Reusability — same code can be used in multiple classes.
2. Less Code Duplication — write once, use many times.
3. Improved Maintenance — easy to modify or extend.
4. Supports Polymorphism — enables method overriding.
5. Real-world Modeling — represents “is-a” relationship (e.g., Dog is an Animal).
6. Conclusion
• Inheritance is the backbone of Object-Oriented Programming in Java.
• It allows one class to reuse code of another class, making the program efficient and
organized.
• Java supports single, multilevel, and hierarchical inheritance using classes,
and multiple and hybrid inheritance through interfaces.
In short:
Inheritance = Code Reusability + Extensibility + Simplicity
QUESTION PAPER 2
Characteristics of Java Language
1. Simple –
Java is easy to learn and understand. It removes complex features like pointers, operator
overloading, and multiple inheritance.
2. Object-Oriented –
Everything in Java is treated as an object. It supports all OOP concepts like inheritance,
polymorphism, abstraction, and encapsulation.
3. Platform Independent –
Java code is compiled into bytecode, which can run on any system having JVM.
Write Once, Run Anywhere (WORA).
4. Secure –
Java provides a secure environment by removing pointers, checking bytecode, and using a
security manager to protect data.
5. Robust –
Java is reliable due to strong memory management, exception handling, and garbage
collection.
6. Portable –
Java programs can run on any device or operating system without modification.
7. Multithreaded –
Java allows multiple threads to run at the same time, improving performance and efficiency.
8. Architecture Neutral –
Java code is independent of hardware and operating system type.
9. Distributed –
Java supports networking and distributed applications using RMI and networking APIs.
10. Dynamic –
Java loads classes at runtime and links them dynamically, making programs more flexible.
11. Interpreted –
Java bytecode is executed line by line by the JVM, making it portable and easy to debug.
12. High Performance –
Java uses a Just-In-Time (JIT) compiler to convert bytecode into machine code, improving
speed.
13. Automatic Memory Management –
Java has an automatic garbage collector that frees unused memory, reducing programmer
effort.
No. Characteristic Description
1 Simple Easy to learn, no pointers
2 Object-Oriented Based on OOP principles
3 Platform Independent Runs on any OS with JVM
4 Secure No memory access via pointers
5 Robust Strong and error-free
6 Portable Same code runs everywhere
7 Multithreaded Multiple tasks run together
No. Characteristic Description
8 Architecture Neutral Independent of processor
9 Distributed Supports networked programs
10 Dynamic Classes loaded at runtime
11 Interpreted Bytecode executed by JVM
12 High Performance JIT compiler improves speed
13 Automatic Memory Uses Garbage Collection
+-----------------------------------+
| CHARACTERISTICS OF JAVA |
+-----------------------------------+
| Simple | Secure |
| Object-Oriented | Robust |
| Portable | Platform Indep. |
| Multithreaded | Dynamic |
| Distributed | High Performance|
+-----------------------------------+
Abstract Class and Abstract Method in Java
1. Introduction
In Java, abstraction means hiding internal details and showing only the essential features of an
object.
This concept is achieved using abstract classes and abstract methods.
2. Abstract Class
An abstract class is a class that is declared using the keyword abstract.
It cannot be instantiated (objects cannot be created directly).
It can contain both:
• Abstract methods (without body)
• Non-abstract methods (with body)
Syntax:
abstract class ClassName {
abstract void display(); // abstract method
void show() { // normal method
[Link]("Normal method");
}
3. Abstract Method
An abstract method is a method declared without a body, and it must be defined (overridden) in the
subclass.
Syntax:
abstract return_type method_name();
4. Example Program
abstract class Animal {
abstract void sound(); // abstract method
void eat() { // normal method
[Link]("Animal is eating");
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
public class AbstractExample {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
Output:
Dog barks
Animal is eating
5. Important Points
1. Abstract class cannot be instantiated directly.
2. It can contain abstract and non-abstract methods.
3. A class inheriting an abstract class must override all abstract methods.
4. abstract keyword is used before class or method declaration.
5. Helps in achieving abstraction and polymorphism.
6. Diagram
Abstract Class
Animal
/ \
▼ ▼
sound() eat()
Overridden in
▼
Dog
7. Advantages
1. Promotes code reusability.
2. Improves security and abstraction.
3. Supports runtime polymorphism.
4. Defines a common template for all subclasses.
Method Overloading in Java
1. Introduction
In Java, sometimes we want to perform similar operations with different types or numbers of
inputs.
Instead of creating different method names for each case, Java allows us to use the same method
name with different parameters.
This concept is known as Method Overloading.
2. Definition
Method Overloading in Java means defining multiple methods with the same name but with
different parameters (different number, type, or order of arguments) within the same class.
It is a type of compile-time polymorphism (also known as static polymorphism).
3. Purpose of Method Overloading
The main aim of method overloading is to:
1. Increase code readability
2. Reduce code duplication
3. Make the program more flexible and reusable
4. Conditions for Method Overloading
Two or more methods are said to be overloaded if:
1. They have same method name
2. They have different number of parameters
or
different data types of parameters
or
different order of parameters
Overloading does not depend on:
• Return type of method
• Access modifiers
5. Syntax
class ClassName {
void methodName(int a) {
// code
void methodName(int a, int b) {
// code
void methodName(double a) {
// code
Here, all methods have the same name (methodName) but different parameters, so this is method
overloading.
6. Example Program
class Addition {
// Method 1 - adds two integers
int add(int a, int b) {
return a + b;
// Method 2 - adds three integers
int add(int a, int b, int c) {
return a + b + c;
// Method 3 - adds two double numbers
double add(double a, double b) {
return a + b;
public class OverloadingExample {
public static void main(String[] args) {
Addition obj = new Addition();
[Link]("Sum of two integers: " + [Link](5, 10));
[Link]("Sum of three integers: " + [Link](5, 10, 15));
[Link]("Sum of two doubles: " + [Link](2.5, 3.7));
Output:
Sum of two integers: 15
Sum of three integers: 30
Sum of two doubles: 6.2
7. Explanation of Program
1. Class Addition contains three add() methods.
2. Each method has the same name but different parameters:
o add(int, int)
o add(int, int, int)
o add(double, double)
3. When the program runs, Java compiler decides which method to call based on the
arguments passed.
4. This decision happens during compile time, so this is called compile-time polymorphism.
8. Diagram
+---------------------+
| Addition Class |
+---------------------+
| int add(int, int) |
| int add(int, int, int) |
| double add(double, double) |
+---------------------+
▼
Method call decided at compile time
9. Advantages of Method Overloading
1. Code Reusability:
You can use the same method name to perform similar actions with different inputs.
2. Improves Readability:
The same method name makes code easier to understand.
3. Saves Memory and Time:
No need to create multiple methods with different names.
4. Achieves Compile-Time Polymorphism:
Method selection happens at compile time.
10. Real-Life Example
Think of the “print()” method in Java.
You can use:
[Link](10);
[Link]("Hello");
[Link](10.5);
All these calls use the same method name (println), but with different argument types (int, string,
double).
This is method overloading in real life.
11. Important Points
1. Overloading is done in the same class.
2. It depends only on method parameters, not on return type.
3. It is an example of compile-time polymorphism.
4. Constructors can also be overloaded.
5. Overloading makes a program clean and easy to read.
12. Conclusion
Method Overloading is a powerful feature of Java that allows programmers to use the same method
name for performing different tasks based on the parameters.
It improves readability, flexibility, and maintainability of the code.
In short:
Same method name + different parameters = Method Overloading
Java Virtual Machine (JVM)
1. Introduction
Java is known as a platform-independent language, which means that Java programs can run on any
device or operating system that has the Java Virtual Machine (JVM) installed.
The Java Virtual Machine (JVM) is a part of the Java Runtime Environment (JRE) that is responsible
for running Java programs.
2. Definition
JVM (Java Virtual Machine) is a virtual machine that executes Java bytecode.
It converts the compiled .class files (bytecode) into machine code that your computer’s processor
can understand.
3. Role of JVM
When you compile a Java program:
1. The Java compiler (javac) converts your .java file into a .class file (which contains bytecode).
2. The JVM then takes this bytecode and converts it into machine-specific code for execution.
4. Java Program Execution Process
The Java program execution involves three main steps:
Step Tool Function
1 Compiler (javac) Converts Java source code into bytecode
2 JVM Loads and runs the bytecode
3 Operating System Executes machine code on hardware
5. Working of JVM
Here’s how JVM works step-by-step:
1. Class Loader:
Loads the .class (bytecode) file into memory.
2. Bytecode Verifier:
Checks the bytecode for errors, illegal code, or security issues.
3. Interpreter / JIT Compiler:
Converts bytecode into machine code.
o Interpreter executes code line by line.
o JIT (Just-In-Time compiler) improves performance by compiling code blocks at once.
4. Runtime Engine:
Executes the compiled machine code on the actual hardware.
6. Diagram of JVM Working
+-----------------------------+
| Java Source Code | (.java)
+-------------+---------------+
(Compiled by javac)
+-------------v---------------+
| Bytecode (.class) |
+-------------+---------------+
|
(Executed by JVM)
+-------------v---------------+
| Java Virtual Machine |
| -------------------------- |
| | Class Loader | |
| | Bytecode Verifier | |
| | Interpreter/JIT | |
| | Runtime Environment | |
+----------------------------+
(Machine Code Output)
+-------------v---------------+
| Operating System |
+------------------------------+
7. Main Components of JVM
1. Class Loader System
o Loads class files into memory.
o Links and initializes them for execution.
2. Method Area
o Stores class-level data such as method code, variable names, etc.
3. Heap Area
o Stores all objects and arrays created during execution.
4. Stack Area
o Stores local variables and partial results for each method.
5. Program Counter Register (PC)
o Keeps track of the current instruction being executed.
6. Native Method Stack
o Used for native (non-Java) methods like C/C++ library calls.
7. Execution Engine
o Converts bytecode to machine code using Interpreter and JIT Compiler.
8. Features of JVM
1. Platform Independent:
Run Java programs on any system with JVM installed.
2. Security:
JVM verifies and protects the program from malicious code.
3. Memory Management:
JVM includes an automatic Garbage Collector to free unused memory.
4. Performance Optimization:
The JIT compiler increases speed by converting bytecode into optimized machine code.
5. Portability:
Same .class file can run on Windows, macOS, or Linux without modification.
9. Example
class Hello {
public static void main(String[] args) {
[Link]("Hello JVM!");
When executed:
1. javac [Link] → creates [Link] (bytecode).
2. java Hello → JVM executes the bytecode.
10. Advantages of JVM
1. Write once, run anywhere (platform independent).
2. Automatic memory management using Garbage Collector.
3. Secure and safe execution environment.
4. Error detection before execution.
5. Efficient execution using JIT compiler.
11. Conclusion
The Java Virtual Machine (JVM) is the heart of Java programming.
It acts as a bridge between Java code and the operating system, converting bytecode into machine
code.
In short:
JVM = Engine that runs Java bytecode on any device.
Life Cycle of an Applet in Java
1. Introduction
Java Applet is a small program that runs inside a web browser or applet viewer.
It is used to create interactive web applications such as games, animations, or calculators.
Applets are a part of Java’s Abstract Window Toolkit (AWT) and work on the client-side (user’s
computer).
2. What is an Applet?
An applet is a Java program that runs inside a browser or an applet viewer instead of the command
prompt.
It does not have a main() method like normal Java programs.
Instead, it follows a specific life cycle managed by the Java Applet class and the browser or applet
viewer.
3. Life Cycle of an Applet
The life cycle of an applet means the various stages through which an applet passes during its
execution.
There are five main stages in the applet life cycle:
1. Initialization – init()
2. Starting – start()
3. Painting – paint()
4. Stopping – stop()
5. Destroying – destroy()
4. Applet Life Cycle Methods
Let’s understand each method in detail
1. init() Method – Initialization Phase
• This method is called only once when the applet is first loaded.
• It is used to initialize variables, set colors, or load images.
public void init() {
// Initialization code here
Example:
Setting background color or loading images when the applet starts.
2. start() Method – Start Phase
This method is called after init() or when the applet resumes from stop().
It is used to start animations or threads.
java
Copy code
public void start() {
// Start animations or threads
Example:
Starting a moving animation when the applet window becomes active.
3. paint(Graphics g) Method – Painting Phase
This method is used to display output on the applet window.
The Graphics object g is used to draw shapes, text, or images.
java
Copy code
public void paint(Graphics g) {
[Link]("Hello Applet!", 50, 50);
}
Example:
Displaying messages or graphics on the screen.
4. stop() Method – Stop Phase
This method is called when the applet is no longer visible or goes to the background.
It is used to pause animations or stop threads.
java
Copy code
public void stop() {
// Stop or pause activities
Example:
Pausing an animation when the user switches to another tab.
5. destroy() Method – Destroy Phase
This method is called only once, when the browser or applet viewer is closing.
It is used to release system resources or perform cleanup tasks.
java
Copy code
public void destroy() {
// Cleanup operations
}
7. Explanation of Program
1. init() → Called once when applet is loaded.
2. start() → Called when applet becomes active.
3. paint() → Displays output or drawings.
4. stop() → Called when applet is paused.
5. destroy() → Called when applet is closed.
8. Advantages of Applets
1. Platform Independent – Runs on any OS with JVM.
2. Secure – Runs inside browser sandbox.
3. Interactive – Can include animation, sound, and user input.
4. Portable – Easily shared through web pages.
9. Disadvantages of Applets
1. Needs Java Plugin or Applet Viewer.
2. Limited access to system resources.
3. Slower loading compared to modern web apps.
4. Not widely used in modern browsers (deprecated).
10. Conclusion
The life cycle of an applet defines how an applet starts, runs, pauses, and ends.
It goes through five stages:
init(), start(), paint(), stop(), and destroy().
In short:
Applet Life Cycle = Creation → Execution → Destruction