public class HelloWorld {
public static void main(String[] args) {
// This line prints the text to the console
[Link]("Hello World");
}
}
The same work with Class-Object format:
// Step 1: Define the Class (The Blueprint)
class GreetingMessenger {
// A method (behavior) that belongs to this class
void displayMessage() {
[Link]("Hello World from an Object!");
}
}
// Step 2: Define the Main Class to run the program
public class Main1{
public static void main(String[] args) {
// Step 3: Create an Object (An instance of the class)
// Syntax: ClassName objectName = new ClassName();
GreetingMessenger messenger = new GreetingMessenger();
// Step 4: Use the Object to call the method
[Link]();
}
}
Now the same work with Overriding:
// Step 1: Parent Class (Superclass)
class Messenger {
void displayMessage() {
[Link]("General Greeting: Hello!");
}
}
// Step 2: Child Class (Subclass) that overrides the method
class EnglishMessenger extends Messenger {
// The @Override annotation tells the compiler we are redefining this method
@Override
void displayMessage() {
[Link]("Specific Greeting: Hello World from a Subclass Object!");
}
}
public class Main {
public static void main(String[] args) {
// Step 3: Create an object of the Parent Class
Messenger generalObj = new Messenger();
[Link](); // Calls the parent method
// Step 4: Create an object of the Child Class
// Even though the reference is 'Messenger', the object is 'EnglishMessenger'
Messenger specialObj = new EnglishMessenger();
// This triggers OVERRIDING (Dynamic Method Dispatch)
[Link](); // Calls the child method
}
}
In Java, Method Overriding occurs when a subclass (child class) provides a specific
implementation of a method that is already defined in its superclass (parent class).
This is a core part of Polymorphism. In our "Hello World" example, a general "Messenger"
class and a specific "EnglishMessenger" that overrides the greeting.
The Java Code
Java
// Step 1: Parent Class (Superclass)
class Messenger {
void displayMessage() {
[Link]("General Greeting: Hello!");
}
}
// Step 2: Child Class (Subclass) that overrides the method
class EnglishMessenger extends Messenger {
// The @Override annotation tells the compiler we are redefining this method
@Override
void displayMessage() {
[Link]("Specific Greeting: Hello World from a Subclass Object!");
}
}
public class Main {
public static void main(String[] args) {
// Step 3: Create an object of the Parent Class
Messenger generalObj = new Messenger();
[Link](); // Calls the parent method
// Step 4: Create an object of the Child Class
// Even though the reference is 'Messenger', the object is 'EnglishMessenger'
Messenger specialObj = new EnglishMessenger();
// This triggers OVERRIDING (Dynamic Method Dispatch)
[Link](); // Calls the child method
}
}
Step-by-Step Explanation
1. Inheritance (extends)
Before you can override, you must have Inheritance. The EnglishMessenger class "extends" the
Messenger class, meaning it inherits everything the parent has.
2. The @Override Annotation
While not strictly required, it is a Software Engineering best practice. It tells the Java compiler:
"I am intentionally changing the behaviour of a parent method." If you make a typo in the
method name, the compiler will alert you.
3. Dynamic Method Dispatch
This is the most "magical" part of Java. Notice the line:
Messenger specialObj = new EnglishMessenger();
Here, the reference type is the Parent, but the object type is the Child. Java decides which
method to run at Runtime based on the actual object, not the reference.
In your Software Engineering syllabus (Unit 2: Modular Design) and Java syllabus (Unit 1:
Polymorphism), overriding allows for flexible code:
Generic Parent: User class with a accessPortal() method.
Overridden Child 1: Student class overrides it to show "Library Books."
Overridden Child 2: Librarian class overrides it to show "Issue/Return Panel."
By using overriding, you can write one line of code ([Link]()) and Java will
automatically show the correct screen depending on who is logged in.
Method Overloading is another fundamental pillar of Polymorphism found in Unit 1 of your
Java syllabus. While Overriding is about "Redefining" a parent's method, Overloading is about
"Reusing" the same method name with different behaviours based on the inputs.
The Java Code (Simple Hello World Example)
Java
class Messenger {
// Version 1: Method with no parameters
void displayMessage() {
[Link]("Hello World!");
}
// Version 2: Overloaded method with one String parameter
void displayMessage(String name) {
[Link]("Hello World to " + name + "!");
}
// Version 3: Overloaded method with two parameters
void displayMessage(String name, int times) {
for(int i = 0; i < times; i++) {
[Link]("Hello " + name + " (Message " + (i+1) + ")");
}
}
}
public class Main {
public static void main(String[] args) {
Messenger myMessenger = new Messenger();
// Java decides which version to run based on the arguments you pass
[Link](); // Calls Version 1
[Link]("Students"); // Calls Version 2
[Link]("Java Class", 3); // Calls Version 3 }}
Step-by-Step Explanation
1. Same Name, Different Parameters
Notice that all three methods are named displayMessage. Java allows this as long as the
parameter list is different (either a different number of parameters or different types of data).
2. Compile-Time Polymorphism
Overloading is also called Static Polymorphism. Why? Because the Java compiler knows exactly
which method to call the moment you write the code, based on what you put inside the
parentheses ().
3. Why use Overloading?
It makes your code cleaner. Instead of having messy names like printHello(),
printHelloWithName(), and printHelloMultipleTimes(), you just have one intuitive name:
displayMessage().
Key Differences: Overloading vs. Overriding
This is a very common question in the SEE (Semester End Examination) for this syllabus.
Feature Method Overloading Method Overriding
Syllabus Unit Unit 1 (Polymorphism) Unit 1 (Inheritance/Polymorphism)
Occurs between Parent and Child
Classes Occurs within the same class.
classes.
Parameters Must be different. Must be the same.
Binding Compile-time (Static). Runtime (Dynamic).
add(int, int) and add(double,
Example [Link]() becomes [Link]()
double)
Software Engineering Connection (Modular Design)
In Unit 2 of your SE Syllabus, we talk about "Modular Software Design." Overloading is a
perfect example of this. It allows a module (like a "Messenger") to be flexible. It provides a
simple interface for simple tasks, but remains powerful enough to handle complex tasks without
confusing the user.
Now combine Method Overloading and Method Overriding into a single program.
To make this simple for beginners, we will use the concept of a "Printer." We have a basic
printer that prints text, and a modern "Smart Printer" that overrides the basic printing but
also adds overloaded features like printing multiple copies.
The Java Lab Exercise
// Parent Class
class Printer {
// Method to be Overridden
void print() {
[Link]("Printer: Printing a standard document...");
}
}
// Child Class
class SmartPrinter extends Printer {
// 1. METHOD OVERRIDING (Unit 1: Polymorphism)
// We redefine the parent's print method
@Override
void print() {
[Link]("SmartPrinter: Printing high-quality digital document...");
}
// 2. METHOD OVERLOADING (Unit 1: Polymorphism)
// Same name 'print', but different parameters (int instead of none)
void print(int copies) {
[Link]("SmartPrinter: Printing " + copies + " copies...");
}
// 3. ANOTHER OVERLOADED METHOD
// Different parameters (String instead of int)
void print(String color) {
[Link]("SmartPrinter: Printing in " + color + " color mode...");
}
}
public class LabExercise {
public static void main(String[] args) {
// Create an object of the SmartPrinter
SmartPrinter myPrinter = new SmartPrinter();
// Testing Overriding
[Link]();
// Testing Overloading
[Link](5); // Calls the int version
[Link]("Red"); // Calls the String version
}
}
Step-by-Step Explanation for the Lab
1. Inheritance (extends): SmartPrinter is a child of Printer. It "takes" all the base features
but wants to improve them.
2. The @Override Line: When we call [Link](), Java sees that the SmartPrinter
has its own version of print(). It ignores the parent's version and runs the child's
version. This is Overriding.
3. The "Same Name" Logic: Notice we have three methods named print inside
SmartPrinter.
One takes no arguments.
One takes an integer.
One takes a String.
Java isn't confused because the "signature" (the stuff inside the brackets) is different. This is
Overloading.
Mapping to your Syllabus
Java Syllabus
Task in Code Software Engineering Concept
Concept
class SmartPrinter Reusability: Using existing code to
Inheritance (Unit 1)
extends Printer build new features.
Dynamic
@Override void Maintainability: Changing behaviour
Polymorphism (Unit
print() without changing the method name.
1)
Static Polymorphism User Interface Design: Providing
void print(int copies)
(Unit 1) multiple ways to use a feature.
Experiment 1: Create a class Animal with a method makeSound() that outputs a generic [Link]
class should further contain derived classes Dog and Cat that override the makeSound() method to
output specific sounds for each animal. Demonstrate polymorphism by creating an Animal reference
that can hold objects of both Dog and Cat, and call the overridden makeSound() method at runtime.
Java program to understand inheritance, method overriding, and runtime polymorphism:
// Base class
class Animal {
// Method to be overridden
void makeSound() {
[Link]("The animal makes a sound");
}
}
// Derived class Dog
class Dog extends Animal {
// Overriding makeSound()
void makeSound() {
[Link]("The dog barks");
}
}
// Derived class Cat
class Cat extends Animal {
// Overriding makeSound()
void makeSound() {
[Link]("The cat meows");
}
}
// Main class to demonstrate polymorphism
public class PolymorphismDemo {
public static void main(String[] args) {
// Animal reference holding Dog object
Animal a1 = new Dog();
[Link](); // Calls Dog's makeSound()
// Animal reference holding Cat object
Animal a2 = new Cat();
[Link](); // Calls Cat's makeSound()
}
}
Explanation:
Animal is the base class containing the method makeSound().
Dog and Cat are derived classes that override the makeSound() method.
The Animal reference (a1, a2) holds objects of different subclasses.
At runtime, Java decides which makeSound() method to execute.
This behavior is called runtime polymorphism (method overriding).
Polymorphism is an object-oriented concept where a single reference variable can refer to objects of
different classes. In Java, runtime polymorphism is achieved through method overriding and
inheritance. A base class reference can hold the object of a derived class. When an overridden
method is called using the base class reference, the method of the actual object is executed at runtime.
This enables dynamic method dispatch and improves code flexibility and reusability.
UML Class Diagram
+------------------+
| Animal |
+------------------+
| + makeSound() |
+------------------+
▲
|
-------------------------
| |
+--------------+ +--------------+
| Dog | | Cat |
+--------------+ +--------------+
| + makeSound()| | + makeSound()|
+--------------+ +--------------+
UML Explanation:
Animal is the superclass.
Dog and Cat are subclasses.
The arrow (▲) represents inheritance (IS-A relationship).
makeSound() is overridden in both child classes.
UML: UML stands for Unified Modelling Language. It is a standard visual language used to
design, describe, and document the structure and behaviour of software systems. UML uses
diagrams to represent classes, objects, relationships, workflows, and interactions in an easy-to-
understand graphical form before actual coding begins.
Importance of UML
Clear System Design: UML helps developers visualize the system architecture, making
complex systems easier to understand.
Better Communication: It provides a common language for developers, designers, testers,
and clients to communicate ideas clearly.
Reduces Development Errors: By identifying design issues early, UML minimizes mistakes
during implementation.
Improves Planning and Documentation: UML diagrams serve as permanent documentation
for future maintenance and upgrades.
Supports Object-Oriented Concepts: UML effectively represents inheritance,
encapsulation, abstraction, and polymorphism.
Saves Time and Cost: Proper design using UML reduces rework, development time, and
project cost.
UML is a standardized graphical language used to visualize, design, and document software systems,
improving clarity, communication, and development efficiency.
Experiment 2: Write a program that takes two strings representing numbers, converts them to
wrapper classes, and performs basic arithmetic operations (addition, subtraction, multiplication,
division).
In Java, a Wrapper class is a class that encapsulates (wraps) a primitive data type within an object.
While Java is an object-oriented language, it includes primitive data types like int and double for high
performance. In some problems these values need to be used as objects, and that is where Wrapper
classes are essential.
The 8 Primitive Types and Their Wrapper Classes
Every primitive type in Java has a corresponding Wrapper class located in the [Link] package.
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Need of Wrapper Classes
1. Collections Framework: Java Collections like ArrayList, HashSet, and HashMap can only
store objects. You cannot create an ArrayList<int>, but you can create an ArrayList<Integer>.
2. Utility Methods: Wrapper classes provide powerful static methods for data conversion. For
example, [Link]("123") allows you to convert a String into a numeric integer.
3. Null Values: Unlike primitives, Wrapper objects can be null. This is useful in databases or
web applications to represent "no data" or an optional field.
4. Generics Support: Java Generics require objects as type parameters; they do not support
primitives directly.
5. Synchronization: In multithreading, synchronisation only works with objects, not primitives.
Key Concepts: Autoboxing and Unboxing
Java automatically converts between primitives and their corresponding Wrapper objects to simplify
your code.
Autoboxing: The automatic conversion of a primitive to an object.
Example: Integer myObj = 5; (Java automatically treats the primitive 5 as an Integer
object).
Unboxing: The automatic conversion of a Wrapper object back to a primitive.
Example: int myNum = myObj; (Java extracts the primitive int from the Integer
object).
The Java Program
import [Link];
public class BasicArithmetic {
public static void main(String[] args) {
// Step 1: Create a Scanner to take input from the keyboard
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
String str1 = [Link](); // Reads "10" as a String
[Link]("Enter second number: ");
String str2 = [Link](); // Reads "5" as a String
try {
// Step 2: Convert Strings to Wrapper Class objects (Double)
Double num1 = [Link](str1);
Double num2 = [Link](str2);
// Step 3: Perform arithmetic operations
Double addition = num1 + num2;
Double subtraction = num1 - num2;
Double multiplication = num1 * num2;
// Step 4: Display the results
[Link]("Addition: " + addition);
[Link]("Subtraction: " + subtraction);
[Link]("Multiplication: " + multiplication);
// Step 5: Division with a check for zero
if (num2 != 0) {
Double division = num1 / num2;
[Link]("Division: " + division);
} else {
[Link]("Division: Error! Cannot divide by zero.");
}
} catch (NumberFormatException e) {
// Step 6: Handle the case where the user types letters instead of numbers
[Link]("Invalid input! Please enter valid numeric strings.");
} finally {
[Link](); // Close the scanner to free up resources
}
}
}
Step-by-Step Explanation
1. Importing and Initializing Scanner
We use import [Link]; to bring in a tool that allows the computer to listen to what you type.
[Link]() captures your input as a String. Even if you type 10, Java sees it as text (like a word)
and not a number you can do math with yet.
2. Converting String to Wrapper ([Link])
This is the most important step. We use the Wrapper Class Double instead of the primitive double.
[Link](str1): This method takes the text "10" and converts it into a Double Object.
Why a Wrapper? In advanced Java, objects are often required for things like lists
(ArrayList) or working with databases, where simple primitives won't work.
3. Autoboxing and Arithmetic
Notice we used the +, -, and * symbols directly on the objects. Normally, you can't do math on objects
(you can't add two "Cars"), but Java has a feature called Unboxing. It automatically "unwraps" the
value inside the Double object, does the math, and "boxes" the result back into a new object.
4. The try-catch Block
As a software engineer, you must assume the user might make a mistake.
If a user types "Ten" instead of "10", the program will try to convert it and fail.
Instead of the program "crashing" with a red error, the catch block catches the
NumberFormatException and prints a nice message to the user.
5. Safety Check (Division)
Dividing by zero is a common way to crash a program. We use a simple if statement to check if the
second number is zero before we attempt the division. This is called defensive programming.
Comparison: Primitive vs. Wrapper
Feature Primitive (double) Wrapper (Double)
Type Basic data type Object
Memory Very low Slightly higher
Methods None Has helpful methods like .valueOf()
Feature Primitive (double) Wrapper (Double)
Null Cannot be null Can be null (useful for missing data)
Implementation in your Project
In the Library Management System you are developing, Wrapper classes are vital for:
Calculating Fines: Converting a String from a "Fines" text field into a Double for
calculation.
Storing Records: Using an ArrayList<Book> where the Book object might contain an Integer
for the ID to allow for null checks if a record is missing.
To implement this, we will use Java Wrapper Classes (like Integer or Double). In Java, wrapper
classes provide a way to use primitive data types as objects.
This program follows the logic needed for the Library & Resource Management System project
(e.g., converting a String input from a UI text field into a numeric "Book ID" or "Fine Amount").
Java Program: String to Numeric Wrapper Arithmetic
Java
import [Link];
public class LibraryArithmetic {
public static void main(String[] args) {
// Step 1: Initialize Scanner for input
Scanner sc = new Scanner([Link]);
[Link]("Enter first number (as a string): ");
String str1 = [Link]();
[Link]("Enter second number (as a string): ");
String str2 = [Link]();
try {
// Step 2: Convert Strings to Double Wrapper Objects
// valueOf() returns a Wrapper Object (Double), not a primitive
Double num1 = [Link](str1);
Double num2 = [Link](str2);
// Step 3: Perform Arithmetic Operations
// Java automatically unboxes the Wrapper objects to primitives to do math
double sum = num1 + num2;
double diff = num1 - num2;
double prod = num1 * num2;
// Step 4: Division with zero check
if (num2 != 0) {
double div = num1 / num2;
[Link]("Division: " + div);
} else {
[Link]("Division: Cannot divide by zero.");
}
// Output results
[Link]("Addition: " + sum);
[Link]("Subtraction: " + diff);
[Link]("Multiplication: " + prod);
} catch (NumberFormatException e) {
// Step 5: Handle non-numeric string inputs
[Link]("Error: Invalid input. Please enter valid numbers.");
} finally {
[Link]();
}
}
}
Step-by-Step Explanation
1. Input Handling (Scanner)
In Software Engineering, we rarely hardcode values. We use the Scanner class to simulate a user
entering data into our Library System (like entering a fine amount). The inputs are initially treated as
String because data from text fields or files is usually text-based.
2. Using Wrapper Classes ([Link])
The Java Syllabus emphasizes Wrapper classes.
We use [Link](str1) instead of [Link](str1).
Difference: parseDouble returns a primitive double, but valueOf returns a Double Object. In
an Object-Oriented system, we often prefer objects so we can store them in Collections (like a
list of book prices).
3. Autoboxing and Unboxing
Notice that we wrote double sum = num1 + num2;.
num1 and num2 are Objects.
Java performs Auto-unboxing, where it automatically extracts the primitive value from the
wrapper object to perform the addition. This is a key feature of Java 5 and later.
4. Exception Handling (try-catch)
According to Unit 2 of your Java Syllabus, a robust program must handle errors.
If a user enters "ABC" instead of "123", [Link]() throws a NumberFormatException.
Our try-catch block ensures the program doesn't crash, which is a core Software Engineering
requirement for "Reliability."
5. Arithmetic Logic
The program performs the four basic operations. In the context of your Library Project:
Addition: Adding a new fine to an existing balance.
Subtraction: Deducting a discount or a payment.
Multiplication: Calculating total fine (Days Overdue × Daily Rate).
Division: Calculating average books issued per month.
How this relates to your Project:
When you build the Library Management System, the Librarian will type a "Book Price" into a
GUI. That price comes into Java as a String. You will use this exact logic to convert that String into a
Double or Integer wrapper before saving it to your Database (JDBC).
What is a Wrapper Class in Java?
A Wrapper Class is a class that converts a primitive data type into an object.
Java is mostly object-oriented, but it also has primitive types like int, char, and double.
Wrapper classes wrap these primitives into objects so Java can treat them like objects when needed.
Primitive Types vs Wrapper Classes
Primitive Type Wrapper Class
Int Integer
Char Character
Byte Byte
Short Short
Long Long
Float Float
double Double
boolean Boolean
Why Do We Need Wrapper Classes?
Primitive types are fast, but they are not objects.
Some Java features only work with objects, not primitives.
Wrapper classes are needed for:
1. Collections Framework (ArrayList, HashMap, etc.)
2. Generics
3. Synchronization
4. Utility methods (parseInt(), valueOf())
5. Null values handling
Simple Real-World Example
Think of a gift:
Primitive data = item (chocolate)
Wrapper class = gift box
You can’t send just a chocolate by courier — you need a box.
Similarly, Java collections can’t store primitives, only objects.
ArrayList list = new ArrayList();
[Link](10);
[Link]("Hello");
int x = (int) [Link](0); // type casting required (Risk of ClassCastException)
ArrayList<Integer> list = new ArrayList<>();
[Link](10);
// [Link]("Hello"); // Compile-time error
Example Without Wrapper (Not Allowed)
ArrayList<int> list = new ArrayList<>(); // Error
Example With Wrapper (Correct)
ArrayList<Integer> list = new ArrayList<>();
[Link](10);
[Link](20);
Here, int → Integer automatically.
Autoboxing & Unboxing
Autoboxing
Automatic conversion of primitive → object
int a = 10;
Integer b = a; // Autoboxing
Unboxing
Automatic conversion of object → primitive
Integer x = 50;
int y = x; // Unboxing
Real-Life Analogy
Primitive data = raw item
Wrapper class = packed item (box)
Generics = storage system that accepts only boxes
Using Wrapper Class Methods
String s = "123";
int num = [Link](s); // String → int
Integer i = [Link](100); // int → Integer object
Key Points for Exams
Wrapper classes are in [Link] package
They convert primitive data into objects
Needed for collections, generics, and APIs
Support autoboxing and unboxing
Each primitive has one wrapper class
One-Line Definition: A wrapper class in Java converts primitive data types into objects so they
can be used where objects are required.
Java Program: String → Wrapper Class → Arithmetic Operations
public class WrapperArithmetic {
public static void main(String[] args) {
// Two strings representing numbers
String s1 = "20";
String s2 = "5";
// Converting strings to wrapper class objects
Integer num1 = [Link](s1);
Integer num2 = [Link](s2);
// Arithmetic operations
int addition = num1 + num2;
int subtraction = num1 - num2;
int multiplication = num1 * num2;
int division = num1 / num2;
// Display results
[Link]("Addition: " + addition);
[Link]("Subtraction: " + subtraction);
[Link]("Multiplication: " + multiplication);
[Link]("Division: " + division);
}
}
Output
Addition: 25
Subtraction: 15
Multiplication: 100
Division: 4
Explanation
1. Strings as input
2. String s1 = "20";
3. String s2 = "5";
4. Conversion to Wrapper Class
5. Integer num1 = [Link](s1);
6. Integer num2 = [Link](s2);
7. Arithmetic operations
Java performs unboxing automatically
Integer → int
8. Results printed
One-Line Concept to Remember: Strings are converted to wrapper class objects using valueOf()
and arithmetic is performed using autounboxing.
Write a Java program to create an Employee class where an Overloaded constructor
initializes employee [Link] default constructor should Initialize name as
"Unknown" and salary as 0 and the second constructor initializes the name and sets a
default [Link] a method DisplayEmployeeDetails() to display employee
information.
Java Program: Using Constructor Chaining
class Employee {
String name;
double salary;
// Default constructor
Employee() {
[Link] = "Unknown";
[Link] = 0;
}
// Overloaded constructor (constructor chaining)
Employee(String name) {
this(); // calls default constructor
[Link] = name; // updates name
[Link] = 15000; // default salary
}
// Method to display employee details
void DisplayEmployeeDetails() {
[Link]("Employee Name: " + name);
[Link]("Employee Salary: " + salary);
[Link]("--------------------------");
}
public static void main(String[] args) {
Employee emp1 = new Employee();
Employee emp2 = new Employee("Anita");
[Link]();
[Link]();
}
}
Output
Employee Name: Unknown
Employee Salary: 0.0
--------------------------
Employee Name: Anita
Employee Salary: 15000.0
--------------------------
Demonstrates constructor overloading
Uses this() constructor chaining (important concept)
Avoids code duplication
Clean and professional structure
One-Line Exam Answer: Constructor overloading allows multiple constructors in a class, and this()
is used to call one constructor from another.
Now Understand: ArrayList<Integer> list = new ArrayList<>();
ArrayList
ArrayList is a class
It belongs to [Link] package
It implements the List interface
It stores elements in a resizable array
It is a dynamic array that can grow and shrink.
<Integer>: This is Generics syntax.
What does <Integer> mean?
It tells Java:
“This ArrayList will store only Integer objects.”
Important:
int not allowed
Integer allowed (wrapper class)
Because generics work only with objects, not primitives.
Example:
[Link](10); // allowed (auto-boxing int → Integer)
[Link]("Hi"); // compile-time error
list
This is a reference variable
It holds the address of the ArrayList object
Not the data itself
Similar to: list is a remote control, not the TV.
= Assignment operator
Assigns the ArrayList object to the variable list
Copies reference, not object
New Java keyword
Used to create an object in heap memory
Allocates memory dynamically
Without new, no object is created.
ArrayList<> : This is the constructor call.
Creates a new empty ArrayList object
() → calls the default constructor
<> (Diamond Operator): Introduced in Java 7.
What does it do?
Tells compiler:
“Infer the generic type from the left-hand side.”
So this:
new ArrayList<>();
Is equivalent to:
new ArrayList<Integer>();
INTERNAL MEMORY VIEW
Stack Heap
---------------- ------------------
list ───────────▶ ArrayList Object
(empty)
list → stored in stack
Actual ArrayList → stored in heap
WHAT REALLY HAPPENS STEP-BY-STEP
1. JVM sees new
2. Memory allocated in heap
3. ArrayList constructor runs
4. Generic type is set to Integer
5. Reference returned
6. Assigned to list
COMMON INTERVIEW TRAPS
This is invalid: ArrayList<int> list = new ArrayList<>();
This causes a warning: ArrayList list = new ArrayList(); // raw type
Correct: ArrayList<Integer> list = new ArrayList<>();
ONE-LINE INTERVIEW ANSWER
This statement declares a generic ArrayList that stores Integer objects, creates an empty list in heap
memory using the ArrayList constructor, and assigns its reference to the variable list.
Why Integer Not int?
Because:
Collections store objects
Auto-boxing converts int → Integer
Experiment 4: To implement different types of Inheritance in
Java
Creating relationships between classes where one class acquires the properties and methods of
another class, using Java’s inheritance rules.
Inheritance is implemented using the keyword:
Extends: (and implements for interfaces).
What is Inheritance in Java?
Inheritance allows:
Code reuse
Method overriding
Runtime polymorphism
Logical hierarchy
Basic Syntax
class Parent {
void show() {
[Link]("Parent");
}}
class Child extends Parent {
}
Types of Inheritance in Java: Java supports 5 conceptual types, but not all through classes.
Single Inheritance: One child → one parent
Parent
↑
Child
Example
class Animal {
void eat() {
[Link]("Eating");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking");
}
}
Multilevel Inheritance
Chain of inheritance
Grandparent
↑
Parent
↑
Child
Example
class A {
void showA() {}
}
class B extends A {
void showB() {}
}
class C extends B {
void showC() {}
}
Hierarchical Inheritance:
Multiple children → one parent
Parent
↑ ↑
Child1 Child2
Example
class Shape {
void draw() {}
}
class Circle extends Shape {}
class Square extends Shape {}
Multiple Inheritance (NOT supported with classes)
One child → multiple parents
Parent1 Parent2
↖ ↗
Child
Why not supported?
To avoid Diamond Problem ambiguity.
class A { void show() {} }
class B { void show() {} }
// class C extends A, B (ERROR)
Multiple Inheritance via Interface (Supported)
Java solves this using interfaces.
Example
interface A {
void show();
}
interface B {
void display();
}
class C implements A, B {
public void show() {
[Link]("A");
}
public void display() {
[Link]("B");
}
}
Hybrid Inheritance: Combination of two or more types.
Achieved using interfaces, not classes.
Keywords Used
Keyword Purpose
extends Class inheritance
implements Interface inheritance
super Access parent members
@Override Ensure correct overriding
Important Rules (EXAM GOLD)
Java supports single inheritance with classes
Java supports multiple inheritance using interfaces
Constructors are not inherited
private members are not inherited
final class cannot be inherited
final method cannot be overridden
One-Line Interview Answer
Java implements inheritance using extends and implements keywords, supporting single, multilevel,
and hierarchical inheritance with classes, and multiple inheritance through interfaces.
Real-Life Example
Animal → Dog → Puppy
Account → SavingsAccount / CurrentAccount
super Keyword in Java: super is a reference keyword used to refer to the
immediate parent class object. It is used only inside a child class.
Uses of super Keyword:
super to Access Parent Class Variables
Example
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void show() {
[Link](x); // Child variable
[Link](super.x); // Parent variable
}
}
Output
20
10
Used when child and parent have same variable names.
super to Call Parent Class Method
Example
class Parent {
void display() {
[Link]("Parent method");
}
}
class Child extends Parent {
void display() {
[Link](); // calls Parent's method
[Link]("Child method");
}
}
Output
Parent method
Child method
Useful when:
You override a method
Still want parent behavior
super() to Call Parent Class Constructor
Rule (VERY IMPORTANT)
super() must be the first statement in the constructor.
Example
class Parent {
Parent() {
[Link]("Parent constructor");
}
}
class Child extends Parent {
Child() {
super(); // calls Parent constructor
[Link]("Child constructor");
}
}
Output
Parent constructor
Child constructor
If you don’t write super(), Java automatically inserts it.
Important Rules of super
Refers to immediate parent only
Cannot access private members
Cannot be used in static context
Constructor call must be first line
super and this cannot be used together in constructor
One-Line Interview Answer: The super keyword is used to access parent class
variables, methods, and constructors from a child class.
Diamond Problem in Java (WITH DIAGRAM)
What is the Diamond Problem?
The diamond problem occurs when:
A class inherits from two classes
Both parent classes have same method
Java cannot decide which one to use
Diamond Structure Diagram
Class A
|
-------------
| |
Class B Class C
| |
-------------
|
Class D
Diamond Problem with Classes (NOT ALLOWED)
class A {
void show() {
[Link]("A");
}
}
class B extends A {
void show() {
[Link]("B");
}
}
class C extends A {
void show() {
[Link]("C");
}
}
// class D extends B, C ERROR
Java says: Ambiguity! Which show() should be called — B or C?
Therefore, Java does NOT support multiple inheritance using classes.
How Java SOLVES Diamond Problem (Using Interfaces)
Interfaces provide default methods.
Example with Interface
interface A {
default void show() {
[Link]("A");
}
}
interface B extends A {
default void show() {
[Link]("B");
}
}
interface C extends A {
default void show() {
[Link]("C");
}
}
class D implements B, C {
@Override
public void show() {
[Link](); // explicitly choosing B
}
}
Output
B
How Ambiguity is Resolved?
Java forces the child class to override the method
You must explicitly specify which interface method to use
Key Difference (VERY IMPORTANT)
Feature Classes Interfaces
Multiple inheritance No Yes
Diamond problem Not allowed Resolved
Method choice Compiler confused Programmer decides
One-Line Interview Answer (Diamond Problem): The diamond problem occurs
when a class inherits from multiple classes with the same method, causing
ambiguity. Java avoids it by not supporting multiple inheritance with classes
and resolves it using interfaces.
FINAL TAKEAWAY
super → access parent
Diamond problem → ambiguity
Java chooses safety over confusion
Interfaces + override = solution
Lab Experiment 4: Design a program for a basic banking system that
calculates the average account balance by dividing the total balance by the
number of account holders and verifies transaction IDs from an array. The
program should demonstrate robust exception handling using multiple try-
catch blocks to manage two specific scenarios: an ArithmeticException for
division by zero when there are no account holders and an
ArrayIndexOutOfBoundsException for accessing invalid indices in the
transaction ID array. in java
Java Program: Basic Banking System with Exception Handling
class BankingSystem {
public static void main(String[] args) {
// Total balance in the bank
double totalBalance = 50000.0;
// Number of account holders (change to 0 to see ArithmeticException)
int numberOfAccountHolders = 0;
// Transaction IDs array
int[] transactionIds = {101, 102, 103, 104};
/* -------- Handling ArithmeticException -------- */
try {
double averageBalance = totalBalance / numberOfAccountHolders;
[Link]("Average Account Balance: " + averageBalance);
} catch (ArithmeticException e) {
[Link]("Error: Cannot calculate average balance. No account holders present.");
}
/* -------- Handling ArrayIndexOutOfBoundsException -------- */
try {
int index = 5; // Invalid index
[Link]("Transaction ID: " + transactionIds[index]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Invalid transaction index accessed.");
}
[Link]("Banking system execution completed safely.");
}
}
Explanation (Step-by-Step)
ArithmeticException Handling
double averageBalance = totalBalance / numberOfAccountHolders;
If numberOfAccountHolders = 0
Division by zero occurs
Java throws ArithmeticException
Caught in the first catch block
ArrayIndexOutOfBoundsException Handling
transactionIds[index];
Array size = 4 (indices 0–3)
Accessing index 5
Causes ArrayIndexOutOfBoundsException
Handled in second catch block
Why Multiple Try-Catch Blocks?
Each block handles one specific risk
Improves clarity and robustness
Follows best coding practices
Output (When Errors Occur)
Error: Cannot calculate average balance. No account holders present.
Error: Invalid transaction index accessed.
Banking system execution completed safely.
Exam / Interview One-Liner: This program demonstrates robust exception handling by using
separate try–catch blocks to manage ArithmeticException and ArrayIndexOutOfBoundsException,
ensuring safe execution of banking operations.