0% found this document useful (0 votes)
4 views96 pages

Java Course - File (1-5 Units)

The document provides a comprehensive overview of Object-Oriented Programming (OOP) principles using Java, covering key concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also includes Java programming fundamentals, the history of Java, its features, and the execution procedure of Java programs, along with examples of applets and data types. Additionally, it highlights the benefits of OOP and the evolution of Java versions.

Uploaded by

sayansongs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views96 pages

Java Course - File (1-5 Units)

The document provides a comprehensive overview of Object-Oriented Programming (OOP) principles using Java, covering key concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also includes Java programming fundamentals, the history of Java, its features, and the execution procedure of Java programs, along with examples of applets and data types. Additionally, it highlights the benefits of OOP and the evolution of Java versions.

Uploaded by

sayansongs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Oop’s Using Java (Subject Code- PC302CS)

UNIT-1

Object Oriented Programming: Principles, Benefits of Object-Oriented Programming.


Introduction to Java: Java buzzwords, bytecode.
Java Programming Fundamentals: Applet and Application program using simple java program.
Data types, variables, arrays, operators, expressions, control statements, type conversion and
casting.
Concepts of classes, objects, constructors, methods, access control, this keyword, garbage
collection.
Overloading methods and constructors.
Introducing access control, static, final, nested and inner classes, exploring string class, using
command-line arguments.

OOPs (Object Oriented Programming System):

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts they are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Object:

Any entity that has state and behaviour is known as an object.

For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.

Class:
Collection of objects is called class. It is a logical entity.

Inheritance:

When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

A Simple inheritance program

public class SimpleInheritanceDemo {


public static void main(String[] args) {
// 1. Create an object of the derived class (Car)

Car myCar = new Car();

[Link]("--- Car Details ---");

// 2. Access the inherited property from the Vehicle class

[Link]("Brand (Inherited): " + [Link]);

// 3. Access the Car's own property

[Link]("Model (Own): " + [Link]);

// 4. Call the inherited method from the Vehicle class


[Link]("Action (Inherited): ");

[Link]();

// 5. Call the Car's own method

[Link]("Action (Own): ");

[Link]();

}
}

Polymorphism:

When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc. In java, we use
method overloading and method overriding to achieve polymorphism. Another example can be to
speak something

e.g. cat speaks meow, dog barks woof etc.


A simple polymorphism program

// 1. Compile-Time Polymorphism (Method Overloading)

class Calculator {
// Method to add two integers

public int add(int a, int b) {

return a + b;

// Overloaded method to add three integers (same name, different parameters)

public int add(int a, int b, int c) {

return a + b + c;

// Overloaded method to add two doubles (same name, different data types)
public double add(double a, double b) {
return a + b;

// 2. Run-Time Polymorphism (Method Overriding)

class Vehicle {

// Base class method


public void run() {

[Link]("Vehicle is running.");

class Car extends Vehicle {

// Derived class method Overriding the base class method


@Override

public void run() {


[Link]("Car is running safely on the road.");
}

class Bike extends Vehicle {


// Derived class method Overriding the base class method

@Override

public void run() {

[Link]("Bike is running on two wheels.");

public class PolymorphismDemo {

public static void main(String[] args) {

// --- A. Compile-Time Polymorphism Demo (Method Overloading) ---

Calculator calc = new Calculator();

[Link]("--- Overloading Demo (Compile-Time) ---");

// Calls the add(int, int) method

[Link]("Addition of 10 and 20: " + [Link](10, 20));

// Calls the add(int, int, int) method

[Link]("Addition of 10, 20, and 30: " + [Link](10, 20, 30));

// Calls the add(double, double) method

[Link]("Addition of 10.5 and 20.5: " + [Link](10.5, 20.5));


[Link]("---------------------------------------");

// --- B. Run-Time Polymorphism Demo (Method Overriding) ---

[Link]("--- Overriding Demo (Run-Time) ---");

// The object type determines which run() method is called at run-time.

Vehicle v1 = new Vehicle(); // Reference and Object are Vehicle

Vehicle v2 = new Car(); // Reference is Vehicle, but Object is Car (Polymorphic call)

Vehicle v3 = new Bike(); // Reference is Vehicle, but Object is Bike (Polymorphic call)

[Link](); // Calls Vehicle's run()

[Link](); // Calls Car's run() (Dynamic Method Dispatch)

[Link](); // Calls Bike's run() (Dynamic Method Dispatch)

[Link]("----------------------------------");

}
Abstraction:

Hiding internal details and showing functionality is known as abstraction.


For example: phone call, we don’t know the internal processing. In java, we use abstract class
and interface to achieve abstraction.

A simple abstraction program


// 1. Abstract Class: Defines the blueprint and essential contract

abstract class Vehicle {

// Abstract method: A method without a body (implementation).

// Subclasses MUST override and implement this method.


public abstract void start();
// Concrete method: A regular method with a body that all subclasses can use.

public void stop() {

[Link]("Vehicle stopped safely.");


}

// 2. Concrete Subclass 1: Implements the abstract method

class Car extends Vehicle {

// Providing the specific implementation for the abstract start() method


@Override
public void start() {

[Link]("Car started with a key ignition.");

// 3. Concrete Subclass 2: Implements the abstract method differently

class Motorcycle extends Vehicle {

// Providing a different, specific implementation for the abstract start() method

@Override

public void start() {

[Link]("Motorcycle started with a kick pedal.");

// 4. Main Class to demonstrate Abstraction


public class AbstractionDemo {
public static void main(String[] args) {

// We can create objects of the concrete classes

Car myCar = new Car();


Motorcycle myMotorcycle = new Motorcycle();

[Link]("--- Starting Car ---");

// User calls the start() method without needing to know

// if it's a key or a kick start (implementation is hidden).

[Link]();

[Link](); // Uses the common stop() method

[Link]("\n--- Starting Motorcycle ---");

[Link]();

[Link]();

Encapsulation:

Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines. A java class is the example of
encapsulation. Java bean is the fully encapsulated class because all the data members are private
here.

A simple encapsulation program

class Student {

// 1. Private variables (data hiding)

private String name;


private int id;

// Constructor to initialize the object


public Student(String name, int id) {
[Link] = name;

[Link] = id;

// 2. Public Getter method for 'name' (Read access)

public String getName() {

return name;

// 2. Public Setter method for 'name' (Write access)

public void setName(String newName) {


// Optional: We can add validation logic here (e.g., check if newName is not empty)
if (newName != null && ![Link]().isEmpty()) {

[Link] = newName;

} else {

[Link]("Error: Name cannot be empty.");

// 2. Public Getter method for 'id' (Read access)

public int getId() {

return id;

// Note: We deliberately do NOT provide a public 'setter' for the 'id'

// to make it read-only once the object is created. This demonstrates


// the control encapsulation gives over access levels.

}
public class EncapsulationDemo {

public static void main(String[] args) {

// Create a new Student object


Student student1 = new Student("Alice", 101);

// --- Demonstrating Access ---

// 1. Read data using the public getter method

[Link]("Initial Student Name: " + [Link]()); // Output: Alice

// 2. Modify data using the public setter method


[Link]("Bob");

[Link]("Updated Student Name: " + [Link]()); // Output: Bob

// 3. Attempt to change the ID (which has no public setter)

[Link]("Student ID: " + [Link]()); // Output: 101

// If we tried this, it would cause a COMPILE ERROR because 'id' is private:


// [Link] = 102;

// [Link]("Attempted Direct ID Change (Compile Error): " + [Link]);

Benefits of Object-Oriented Programming:

1. Code Reusability like inheritance.


2. Modularity and Easy Troubleshooting like encapsulation.
3. Data Security and Integrity like encapsulation, abstraction.
4. Flexibility and Scalability like inheritance, polymorphism.
5. Maintainability.
6. Effective problem solving.
Introduction to Java:

The history of java starts from Green Team. Java team members (also known as Green Team),
initiated a revolutionary task to develop a language for digital devices such as set-top boxes,
televisions etc. For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by Netscape.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
There are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set top boxes.

3) Firstly, it was called "Green talk" by James Gosling and file extension [Link].

4) After that, it was called Oak and was developed as a part of the green project.

Java Version History:

There are many java versions that has been released. Current stable release of Java is Java SE 8.

1. JDK Alpha and Beta (1995)

2. JDK 1.0 (23rd Jan, 1996)


3. JDK 1.1 (19th Feb, 1997)

4. J2SE 1.2 (8th Dec, 1998)

5. J2SE 1.3 (8th May, 2000)

6. J2SE 1.4 (6th Feb, 2002)

7. J2SE 5.0 (30th Sep, 2004)

8. Java SE 6 (11th Dec, 2006)

9. Java SE 7 (28th July, 2011)

10. Java SE 8 (18th March, 2014)


Java Buzzwords Features:

There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.

1. Simple

2. Object-Oriented

3. Portable
4. Platform independent
5. Secured

6. Robust

7. Architecture neutral

8. Dynamic
9. Interpreted

10. High Performance

11. Multithreaded

12. Distributed

Bytecode:

• Java (Java Bytecode): Compiled into .class files, which are executed by the Java Virtual
Machine (JVM). This is the most famous example of bytecode in OOP.
• C# and other .NET languages (Common Intermediate Language - CIL): Compiled
into CIL (sometimes called MSIL), which is executed by the Common Language
Runtime (CLR).
• Python: Source code is compiled into CPython bytecode (stored in .pyc files) before
being interpreted by the Python Virtual Machine.
• Other languages: Many other object-oriented or multi-paradigm languages like Ruby and
Kotlin also use a bytecode/VM model.

Execution Procedure:

1. Compilation: The OOP source code (e.g., a Java .java file) is compiled into bytecode
(e.g., a Java .class file).
2. Loading: The VM loads the bytecode.
3. Execution: The VM executes the bytecode. This can happen in two primary ways:

• Interpretation: The VM reads and executes each bytecode instruction sequentially.

• Just-in-Time (JIT) Compilation: For better performance, modern VMs often compile
frequently executed parts of the bytecode into native machine code at runtime and then
cache and execute this faster native code.
Java Comments:

The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.
Types of Java Comments

There are 3 types of comments in java.


1. Single Line Comment- (The single line comment is used to comment only one line.)
2. Multi Line Comment- (The multi-line comment is used to comment multiple lines of code.)

3. Documentation Comment- (The documentation comment is used to create documentation API.


To create documentation API, you need to use Javadoc tool.)

Applet and Application program using simple java program:

An Applet was a small Java program designed to be embedded within an HTML web page and
executed by a browser's Java plugin.

Characteristics:

• Execution: Runs within a web browser and is launched via the <applet> (or <object>) tag
in HTML.

• Access: Operated in a highly restrictive security "sandbox," meaning it had limited or no


access to the user's local hard drive or system resources.

• Entry Point: Used specific methods like init(), start(), and paint(), inheriting from the
[Link] class.

A simple java program;

// Import the necessary Applet and GUI components

import [Link];
import [Link];

// The class must extend [Link]

public class SimpleApplet extends Applet {

// The init() method is called when the applet is first loaded

public void init() {

// Initialization code here


}

// The paint() method is called to draw on the applet's area

public void paint(Graphics g) {

// Draw the message at coordinates (20, 20)

[Link]("Hello, I was a simple Java Applet!", 20, 20);

}
}
Data Types:

Data types represent the different values to be stored in the variable. In java, there are two types
of data types:

1. Primitive data types


2. Non-primitive data types

A Simple Primitive datatype program:


public class PrimitiveDataTypesDemo {

public static void main(String[] args) {

// 1. Integer Types (Whole numbers)

int age = 30; // Standard integer (32-bit)

long worldPopulation = 8_000_000_000L; // Long integer for large numbers (64-bit). The 'L'
suffix is required.

// 2. Floating-Point Types (Decimal numbers)

double price = 19.99; // Standard floating-point (64-bit), most commonly used for decimals

float temperature = 98.6f; // Smaller floating-point (32-bit). The 'f' suffix is required.

// 3. Character Type (Single characters)


char firstInitial = 'J'; // Single 16-bit Unicode character, enclosed in single quotes.

// 4. Boolean Type (True/False values)

boolean isJavaFun = true; // Used for conditional logic.

// Print the stored primitive values

[Link]("--- Primitive Data Types ---");

[Link]("Age (int): " + age);


[Link]("World Population (long): " + worldPopulation);

[Link]("Price (double): " + price);

[Link]("Temperature (float): " + temperature);

[Link]("First Initial (char): " + firstInitial);

[Link]("Is Java Fun? (boolean): " + isJavaFun);

}
A Simple Non-Primitive datatype:

public class ReferenceDataTypesDemo {

public static void main(String[] args) {

// 1. String (Sequence of characters)

// String is a class in Java, so it's a reference type.

String greeting = "Hello, World!";

// 2. Array (Collection of values of the same type)

// An array is an object, making it a reference type.


int[] scores = {95, 88, 92};
// 3. Custom Class (Creating an object of a class)

// 'obj' is a reference to a new object created from the 'Object' class.

Object obj = new Object();

// Print the stored reference values

[Link]("\n--- Non-Primitive (Reference) Data Types ---");

[Link]("Greeting (String): " + greeting);

// Accessing the array elements

[Link]("First Score (int[]): " + scores[0]);

// Printing the object reference (This typically prints the object's hash code)

[Link]("Object Reference: " + obj);

}
}

Variables in Java:
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.

Types of Variables:

There are three types of variables in java:

1. local variable
2. instance variable
3. static variable

1) Local Variable:

A variable which is declared inside the method is called local variable.

2) Instance Variable:

A variable which is declared inside the class but outside the method, is called instance variable. It
is not declared as static.

3) Static variable:

A variable that is declared as static is called static variable. It cannot be local. We will have detailed
learning of these variables in next chapters.

Arrays:
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.

Operators in java:
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in java which are given below:

1. Unary Operator
2. Arithmetic Operator
3. Shift Operator
4. Relational Operator
5. Bitwise Operator
6. Logical Operator
7. Ternary Operator
8. Assignment Operator.

A Simple Operator java program:

public class OperatorDemo {

public static void main(String[] args) {

// Declare initial variables

int a = 15;

int b = 4;

boolean condition1 = true;

boolean condition2 = false;

[Link]("--- 1. Arithmetic Operators ---");

// Used for mathematical calculations

// Addition (+)

int sum = a + b;

[Link]("a + b = " + sum); // Output: 19

// Subtraction (-)
int difference = a - b;
[Link]("a - b = " + difference); // Output: 11
// Multiplication (*)

int product = a * b;

[Link]("a * b = " + product); // Output: 60

// Division (/) - Returns the integer quotient

int quotient = a / b;

[Link]("a / b (Integer Division) = " + quotient); // Output: 3 (15 / 4 = 3 with


remainder 3)

// Modulus (%) - Returns the remainder

int remainder = a % b;

[Link]("a % b (Remainder) = " + remainder); // Output: 3

[Link]("\n--- 2. Relational Operators ---");

// Used to compare two values, resulting in a boolean (true/false)

// Equal to (==)

boolean isEqual = (a == 15);

[Link]("a == 15? " + isEqual); // Output: true

// Greater than (>)

boolean isGreater = (a > b);

[Link]("a > b? " + isGreater); // Output: true

// Not Equal to (!=)

boolean isNotEqual = (a != b);

[Link]("a != b? " + isNotEqual); // Output: true


// Less than or Equal to (<=)

boolean isLessOrEqual = (a <= 15);

[Link]("a <= 15? " + isLessOrEqual); // Output: true

[Link]("\n--- 3. Logical Operators ---");

// Used to combine or modify boolean values

// Logical AND (&&) - True only if BOTH conditions are true

boolean resultAND = condition1 && condition2;

[Link]("condition1 && condition2: " + resultAND); // Output: false

// Logical OR (||) - True if AT LEAST ONE condition is true


boolean resultOR = condition1 || condition2;

[Link]("condition1 || condition2: " + resultOR); // Output: true

// Logical NOT (!) - Reverses the boolean state

boolean resultNOT = !condition1;

[Link]("!condition1: " + resultNOT); // Output: false

[Link]("\n--- 4. Assignment Operator (Bonus) ---");

// The simple assignment operator (=) assigns a value to a variable.

// Compound assignment operators combine an operation with assignment.

int c = 10;

[Link]("Initial c: " + c); // Output: 10

// Compound Assignment (c = c + 5)

c += 5;
[Link]("c after c += 5: " + c); // Output: 15
}

Expressions:

Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are
built using values, variables, operators and method calls.

Control Statements:

The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.

Java Type casting and Type conversion:

Widening or Automatic Type Conversion

Widening conversion takes place when two data types are automatically converted.

 The two data types are compatible.

 When we assign value of a smaller data type to a bigger data type.

For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or Boolean. Also, char and Boolean are not
compatible with each other.
Narrowing or Explicit Conversion:

If we want to assign a value of larger data type to a smaller data type, we perform explicit type
casting or narrowing.

 This is useful for incompatible data types where automatic conversion cannot be done.

 Here, target-type specifies the desired type to convert the specified value to.

A Simple java program:


public class TypeConversionCastingDemo {

public static void main(String[] args) {

[Link]("--- 1. Automatic Type Conversion (Widening) ---");

// Widening Conversion: Smaller type to Larger type

// Java does this automatically, as there is no loss of data.

int myInt = 100; // 32-bit integer

long myLong = myInt; // Automatic conversion from int to 64-bit long

double myDouble = myLong; // Automatic conversion from long to 64-bit double

[Link]("Original int value: " + myInt);

[Link]("Converted long value: " + myLong);


[Link]("Converted double value: " + myDouble);

[Link]("\n--- 2. Explicit Type Casting (Narrowing) ---");


// Narrowing Conversion: Larger type to Smaller type
// Java requires explicit casting because data loss is possible.

double bigDouble = 9.87;

int smallInt = (int) bigDouble; // Explicitly cast double to int. Decimal part (.87) is lost.

long bigLong = 2500000000L; // 2.5 billion

int smallerInt = (int) bigLong; // Explicitly cast long to int. This will cause data
corruption/overflow

// because 2.5 billion is too large for an int.

byte myByte = 127;

byte myNewByte = (byte) (myByte + 1); // Arithmetic operation on byte/short returns an int.

// Must explicitly cast back to byte. This also causes overflow.

[Link]("Original double value: " + bigDouble);

[Link]("Casted int value (Decimal lost): " + smallInt);

[Link]("Original long value: " + bigLong);

[Link]("Casted int value (Data overflow/loss): " + smallerInt);

[Link]("Original byte (127): " + myByte);

[Link]("Casted byte (127 + 1 overflows): " + myNewByte); // Output: -128

}
}

Concept of classes and Objects:

Class:

A class is a blueprint or a template for creating objects. It defines the common properties
(data/fields) and behaviors (methods) that all objects of that class will possess. A class is a logical
construct and does not occupy memory until an object is created from it.

Object:
An object is a real-world entity and an instance of a class. When you create an object, you are
creating a concrete instance based on the blueprint defined by the class. Each object has its own
unique state (values for its fields) and can perform the behaviours defined by its class's
methods. Objects are runtime entities and occupy memory.

Constructors:

Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name

2. Constructor must have no explicit return type.

Types of java constructors:

There are two types of constructors:


1. Default constructor (no-arg constructor)

2. Parameterized constructor

Default Constructor:

A constructor that has no parameter is known as default constructor.

Java -Methods:

A Java method is a collection of statements that are grouped together to perform an operation.
When you call the [Link]() method, for example, the system actually executes several
statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.

Access Control:

Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.
There are 4 types of java access modifiers:
1. Public- (The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.)
2. Private- (The private access modifier is accessible only within class.)
3. Protected- (The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor.
It can't be applied on the class.)
4. Default- (If you don't use any modifier, it is treated as default bydefault. The default
modifier is accessible only within package.)
this keyword in java:

Here is given the 6 usages of java this keyword.

1. this can be used to refer current class instance variable.

2. this can be used to invoke current class method (implicitly)

3. this() can be used to invoke current class constructor. JAVA PROGRAMMING Page 30 Java
Constructor Java Method

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.

6. this can be used to return the current class instance from the method.

Java Garbage Collection:


In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free () function in C language and delete () in C++. But, in java it is
performed automatically. So, java provides better memory management.
Overloading Methods:

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by taking
into account the number of parameters in the list and their type.

If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Constructors:
A simple combination Constructor program:

class Car {

String model;

int year;

// 1. No-Argument Constructor (Initializes with fixed or default values)

// This is often used when a programmer needs a constructor but wants to

// perform specific initialization logic, making it different from the

// implicit Java Default Constructor.

public Car() {

[Link] = "Unknown Model";


[Link] = 2024;
[Link]("No-Argument Constructor called: Default Car created.");

// 2. Parameterized Constructor (Initializes with values passed during object creation)

public Car(String model, int year) {

[Link] = model;

[Link] = year;
[Link]("Parameterized Constructor called: " + model + " (" + year + ") created.");

// Method to display car details

public void displayDetails() {

[Link]("Model: " + [Link] + ", Year: " + [Link]);

}
}

public class ConstructorDemo {


public static void main(String[] args) {

// A. Using the No-Argument Constructor

Car car1 = new Car();


[Link]();

// Output: Model: Unknown Model, Year: 2024

[Link]("---");

// B. Using the Parameterized Constructor

Car car2 = new Car("Tesla Model Y", 2023);

[Link]();
// Output: Model: Tesla Model Y, Year: 2023
[Link]("---");

// C. The Implicit Default Constructor (Concept only)

// If we had NOT defined any constructors in the Car class,

// Java would automatically provide a *Default Constructor* like this:

// public Car() {} // It would do nothing but create the object.

// Once you define ANY constructor (like the two above), the
// Java default constructor is NO longer provided.

[Link]("Note: The implicit Java Default Constructor is only created if you don't
define any constructor.");

Static, Final, Nested and inner classes:

1. The static Keyword

The static keyword means that the member (variable, method, or nested class) belongs to the class
itself, rather than to any specific object instance of that class.
• Static Variables (Class Variables): A single copy of the variable is shared among all
objects of the class. Changes made by one object are visible to all others.

• Static Methods (Class Methods): These methods can be called directly using the class
name, without creating an object. They can only access static data members and cannot
use the this or super keywords.

• Static Blocks: Used to initialize static variables. They execute only once when the class is
loaded into memory.
2. The final Keyword

The final keyword is used to restrict the user. It can be applied to variables, methods, and classes.

• Final Variables: The value can be assigned only once and cannot be changed afterward
(making it a constant). If the variable is a reference to an object, the reference cannot be
changed, but the object's contents can still be modified (unless the object itself is
immutable).

• Final Methods: Cannot be overridden by subclasses. This is often used for security or
performance reasons.

• Final Classes: Cannot be subclassed (inherited from). Examples include String, Integer,
and most wrapper classes.

3. Nested and Inner Classes

A Nested Class is any class declared inside another class. It helps to logically group classes that
are only used in one place and increases encapsulation.

There are four main types:


A. Inner Class (Non-Static Nested Class)
• Definition: A nested class that is not declared static.

• Access: It has direct access to all members (static and non-static, including private ones)
of its enclosing class.

• Instantiation: It requires an instance of the outer class to be created.

B. Static Nested Class

• Definition: A nested class declared with the static keyword.

• Access: It cannot directly access the non-static (instance) members of the outer class. It
can only access the static members of the outer class.

• Instantiation: It does not require an instance of the outer class to be created.

C. Local Inner Class


• A class defined inside a method or a scope block. It can only be instantiated and used
within that block.

D. Anonymous Inner Class

• A class without a name, used to implement an interface or extend a class in a single


statement. Often used for event handling (e.g., button listeners).

String Class:

String is basically an object that represents sequence of char values. An array of characters works
same as java string. For example:

1. char [] ch={'j','a','v','a','t','p','o','i','n','t'};

2. String s=new String(ch);

ssame as:
1. String s="javatpoint";

2. Java String class provides a lot of methods to perform operations on string such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

3. The [Link] class implements Serializable, Comparable and CharSequence interfaces.

The CharSequence interface is used to represent sequence of characters. It is implemented by


String, StringBuffer and StringBuilder classes. It means, we can create string in java by using
these 3 classes.
A simple String method program using string name: KPRITCOE

public class StringMethodsDemo {

public static void main(String[] args) {

// The original String

String str = "KPRITCOE";

[Link]("Original String: " + str);

[Link]("-------------------------");

// 1. Length Method: Getting the length of the string


int length = [Link]();

[Link]("1. Length: " + length); // Output: 8

// 2. charAt() Method: Accessing a character at a specific index (index starts at 0)

char firstChar = [Link](0);

char sixthChar = [Link](5);

[Link]("2. Character at index 0: " + firstChar); // Output: K


[Link]("3. Character at index 5: " + sixthChar); // Output: C

// 4. toLowerCase() Method: Converting the string to lowercase

String lowerCaseStr = [Link]();

[Link]("4. Lowercase: " + lowerCaseStr); // Output: kpritcoe

// 5. toUpperCase() Method: Converting the string to uppercase


String upperCaseStr = [Link]();

[Link]("5. Uppercase: " + upperCaseStr); // Output: KPRITCOE (No change


since it was already upper)
// 6. substring() Method: Extracting a part of the string

// From index 3 (inclusive) to the end

String sub1 = [Link](3);


[Link]("6. Substring from index 3: " + sub1); // Output: ITCOE

// From index 1 (inclusive) to index 4 (exclusive)

String sub2 = [Link](1, 4);

[Link]("7. Substring from 1 to 4: " + sub2); // Output: PRI

// 8. contains() Method: Checking if the string contains a specific sequence


boolean containsIT = [Link]("IT");
boolean containsZ = [Link]("Z");

[Link]("8. Contains 'IT'? " + containsIT); // Output: true

[Link]("9. Contains 'Z'? " + containsZ); // Output: false

// 10. equals() Method: Comparing content equality (case-sensitive)

boolean isEqual = [Link]("KPRITCOE");

boolean isNotEqual = [Link]("kpritcoe");


[Link]("10. Equals 'KPRITCOE'? " + isEqual); // Output: true

[Link]("11. Equals 'kpritcoe'? " + isNotEqual); // Output: false (Case sensitive)

// 12. replace() Method: Replacing all occurrences of a character/sequence

String replacedStr = [Link]('O', 'X');

[Link]("12. Replaced 'O' with 'X': " + replacedStr); // Output: KPRITCXE

}
}
UNIT-2

Inheritance: Inheritance concept, types of inheritance, Member access rules, use of super and
final.

Polymorphism - dynamic binding, method overriding, abstract classes and methods.

Interfaces: Defining an interface, implementing interfaces, extending interface.

Packages: Defining, Creating and Accessing a Package, importing packages

Inheritance in Java:

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. Inheritance represents the IS-A relationship, also known as parentchild
relationship

Why use inheritance in java


1. For Method Overriding (so runtime polymorphism can be achieved).

2. For Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

}
All inheritance program:

// Base class (superclass for single, multilevel, and hierarchical inheritance)

class Animal {

public void eat() {


[Link]("The animal is eating.");

// Intermediate class for single, multilevel, and hierarchical inheritance

class Mammal extends Animal { // Single inheritance from Animal

public void breathe() {

[Link]("The mammal is breathing.");

}
// Subclass for multilevel inheritance (Mammal -> Animal)

class Dog extends Mammal { // Multilevel: Inherits from Mammal (which inherits from Animal)

public void bark() {

[Link]("The dog is barking.");


}

// Another subclass for hierarchical inheritance (shares Mammal as parent with Dog)

class Cat extends Mammal { // Hierarchical: Both Dog and Cat extend Mammal

public void meow() {

[Link]("The cat is meowing.");


}
}

// Interface for multiple and hybrid inheritance simulation

interface Flyable {

void fly();

// Another interface for multiple and hybrid inheritance

interface Swimmable {

void swim();

// Class for multiple inheritance simulation (extends one class + implements multiple interfaces)

class Bird extends Animal implements Flyable, Swimmable { // Multiple: Implements 2 interfaces
+ single from Animal

public void chirp() {


[Link]("The bird is chirping.");
}

@Override

public void fly() {


[Link]("The bird is flying.");

@Override

public void swim() {

[Link]("The bird is swimming.");

}
}

// Class for hybrid inheritance (multilevel/hierarchical + multiple via interfaces)

class Bat extends Mammal implements Flyable { // Hybrid: Extends Mammal


(multilevel/hierarchical from Animal) + implements Flyable

public void screech() {

[Link]("The bat is screeching.");

@Override
public void fly() {

[Link]("The bat is flying.");

// Main class to demonstrate all inheritance types

public class AllInheritanceDemo {


public static void main(String[] args) {
[Link]("=== Single Inheritance (Mammal extends Animal) ===");

Mammal mammal = new Mammal();

[Link](); // Inherited from Animal

[Link](); // Own method

[Link]("\n=== Multilevel Inheritance (Dog extends Mammal extends Animal)


===");
Dog dog = new Dog();

[Link](); // From Animal (via Mammal)

[Link](); // From Mammal

[Link](); // Own method

[Link]("\n=== Hierarchical Inheritance (Dog and Cat both extend Mammal)


===");

Cat cat = new Cat();

[Link](); // From Animal (via Mammal)


[Link](); // From Mammal

[Link](); // Own method

// Demonstrate shared parent

[Link]("Dog and Cat share Mammal's method:");

[Link](); // Dog accesses Mammal

[Link](); // Cat accesses Mammal

[Link]("\n=== Multiple Inheritance Simulation (Bird extends Animal +


implements Flyable & Swimmable) ===");

Bird bird = new Bird();


[Link](); // From Animal

[Link](); // From Flyable

[Link](); // From Swimmable


[Link](); // Own method
[Link]("\n=== Hybrid Inheritance (Bat extends Mammal
[multilevel/hierarchical] + implements Flyable) ===");

Bat bat = new Bat();

[Link](); // From Animal (via Mammal)

[Link](); // From Mammal

[Link](); // From Flyable


[Link](); // Own method

Member Access Rules:

A subclass includes all of the members of its super class but it cannot access those members of the
super class that have been declared as private. Attempt to access a private variable would cause
compilation error as it causes access violation. The variables declared as private, is only accessible
by other members of its own class. Subclass have no access to it.

1. private:

• Rule: Members declared private are the most restrictive. They are only visible and
accessible within the class where they are defined.

• Purpose: Enforces encapsulation (data hiding) by shielding the internal state of an object
from the outside world.

2. default (Package-Private):

• Rule: If you don't use any modifier, the member has default (or package-private) access.
It is accessible within its own class and all other classes within the same Java package.
• Purpose: Allows tight coupling and cooperation between classes that are logically grouped
together in the same package, but keeps them hidden from classes outside that package.
3. protected:

• Rule: Members declared protected are accessible:

1. Within the same package (like default).

2. By subclasses (direct or indirect) in any package.


• Purpose: Designed for inheritance. It allows derived classes, even if they are in a
completely different library or package, to access and build upon the protected
functionality of their parent class.

4. public:

• Rule: Members declared public are the least restrictive. They are accessible from any
class in the Java application, regardless of the package.

• Purpose: Used for methods and variables that represent the intended interface or public
contract of a class.

The above rules apply to members, but the access modifiers also control the visibility of the class
itself:

• public Class: Can be accessed by any other class.

• default Class: Can only be accessed by classes within the same package.
• private and protected modifiers cannot be applied to top-level classes (classes that are
not nested). They can only be applied to nested or inner classes.

Super keyword in java:


The super keyword in java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Usage of java super Keyword:

1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

Final Keyword in Java:

The final keyword in java is used to restrict the user. The java final keyword can be used in many
contexts. Final can be:
1. variable 2. method 3. Class

The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only.

Method Overriding in Java:

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.

Usage of Java Method Overriding:

Method overriding is used to provide specific implementation of a method that is already provided
by its super class.

Method overriding is used for runtime polymorphism

Rules for Java Method Overriding:

1. method must have same name as in the parent class

2. method must have same parameter as in the parent class.


3. must be IS-A relationship (inheritance).

Abstract class in Java:

A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented. It cannot be instantiated.

Interface in Java:
An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance in
Java.

Java Interface also represents IS-A relationship.


It cannot be instantiated just like abstract class.
There are mainly three reasons to use interface. They are given below.

1. It is used to achieve abstraction.


2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.

Multiple interfaces:

Implementing interfaces:

1. The Interface Definition

First, you need an interface to define the contract. An interface can contain abstract methods
(which are implicitly public and abstract), default methods, static methods, and constant fields
(which are implicitly public, static, and final).
2. Implementing the Interface in a Class

A class that implements an interface must provide a concrete implementation for all of the
interface's abstract methods.
3. Using the Implemented Class

You can treat an object of the implementing class as its interface type, which is key to
polymorphism.

A Simple program:

// 1. Define the Interface (The Contract)

interface Vehicle {

// Abstract method: All implementing classes must define this.

// Methods in an interface are implicitly public and abstract.

void startEngine();

// Abstract method: Returns the number of wheels.

int getWheelCount();

// Constant: Variables in an interface are implicitly public, static, and final.

String FUEL_TYPE = "Petrol/Electric";

// 2. Implement the Interface: Car class

class Car implements Vehicle {

// Must implement startEngine()

@Override

public void startEngine() {

[Link]("Car engine starts with a quiet hum.");

// Must implement getWheelCount()


@Override
public int getWheelCount() {

return 4;

// 2. Implement the Interface: Bicycle class

class Bicycle implements Vehicle {

// Must implement startEngine() - A bicycle doesn't have an engine, so we define a custom


action.

@Override

public void startEngine() {

[Link]("Bicycle starts moving by pedaling.");

// Must implement getWheelCount()

@Override

public int getWheelCount() {

return 2;

// 3. Demonstration Class

public class InterfaceDemo {

public static void main(String[] args) {

[Link]("--- Demonstrating Polymorphism with Interface ---");

// Declare variables using the INTERFACE type (Vehicle)


Vehicle object1 = new Car();

Vehicle object2 = new Bicycle();

[Link]("\n--- Object 1: Car ---");

// Call the method, the JVM decides which implementation (Car's or Bicycle's) to use at
runtime.
[Link](); // Calls Car's implementation

[Link]("Wheels: " + [Link]());

[Link]("Fuel Type: " + Vehicle.FUEL_TYPE); // Accessing interface constant

[Link]("\n--- Object 2: Bicycle ---");

[Link](); // Calls Bicycle's implementation


[Link]("Wheels: " + [Link]());

[Link]("Fuel Type: " + Vehicle.FUEL_TYPE); // Accessing interface constant

Extending interface:

You use the extends keyword, just like with classes, but interfaces can extend multiple other
interfaces. This is known as multiple inheritance of type.

1. Simple Interface Extension

A new interface can extend a single existing interface to add more specific functionality.
// 1. Base Interface

public interface Animal {

void eat();

// 2. Extending Interface
public interface Pet extends Animal {

// Inherits void eat()

void play(); // Adds a new abstract method

// 3. Implementing Class must fulfill all methods from the chain (Animal + Pet)

public class Cat implements Pet {

@Override

public void eat() {

[Link]("Cat is eating.");

@Override

public void play() {

[Link]("Cat is playing with a toy.");

2. Extending Multiple Interfaces

A key feature of interfaces is that they can extend more than one interface simultaneously. This
allows you to combine contracts from different sources.

Packages:

A java package is a group of similar types of classes, interfaces and sub-packages. Package in java
can be categorized in two form, built-in package and user-defined package. There are many built-
in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.


3) Java package removes naming collision
1. Organization and Encapsulation

Packages act like folders in a file system, grouping related types (classes, interfaces, enums, etc.).
This makes large projects easier to manage and navigate.

2. Naming Conflict Prevention

Since types are grouped by package, two different classes can have the same name as long as they
belong to different packages.

• Example: You can have a List class in the [Link] package and another List
class in the standard [Link] package. When using them, you specify which one you mean
(e.g., [Link]).

3. Access Control (Visibility)

Packages define a layer of access control known as package-private or default access.

• A member (class, method, or field) declared without any access modifier (public, private,
or protected) is only accessible within its own package.

Types of Packages:

• Built-in Packages:

These are packages provided by the Java API, offering a wide range of functionalities. Examples
include [Link] (fundamental-classes), [Link] (utility-classes
like Scanner, ArrayList), [Link] (input/output operations), and [Link] (networking).

• User-defined Packages:

Developers can create their own packages to organize their application's classes and interfaces
according to their specific needs.
Working with Packages:

CREATING A PACKAGE:

1. Creating a Package
You define a package at the very top of a Java source file using the package keyword.

// File: com/example/utils/[Link]

package [Link];

public class Helper {

// Class contents
}

• Naming Convention: Packages are typically named using a reverse internet domain
name to ensure uniqueness (e.g., [Link], [Link]). All package
names should be in lowercase.

ACCESSING A PACKAGE:

2. Accessing a Package (Importing)

To use a class from another package, you have two main options:

A. Fully Qualified Name

You can use the complete path every time you reference the class. This is rarely used but avoids
the need for an import statement.

// In a different package (e.g., [Link])

public class Main {


public static void main(String[] args) {

[Link]<String> list = new [Link]<>();

}
}
IMPORTING A PACKAGE:

B. The ‘import’ Statement (Recommended)


You use the ‘import’ keyword to bring a specific class or all classes from a package into your file,
allowing you to use the simple class name.6

Import Type Syntax Description

Single Class import Imports only the ArrayList class.


[Link];

All-Classes import [Link].*; Imports all classes from the [Link] package
(Wildcard) (but not sub-packages).

package [Link];

import [Link]; // Imports only ArrayList

// import [Link].*; // Alternative: Imports all classes in [Link]

public class Main {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<>(); // Use simple name

3. The Default Package


If you create a Java file without a package statement, the class is considered part of the default
package. While quick for small tests, it's generally discouraged in production code because types
in the default package cannot be imported into a named package.
Unit-3

Exception handling: Benefits of exception handling, classification, checked exceptions and


unchecked exceptions, usage of try, catch, throw, throws and finally, re-throwing exceptions,
built in exceptions, creating own exception sub classes.

Multithreading: Java Thread Model, The Main Thread, creating a Thread, creating multiple
threads, using isAlive() and join(), thread priorities, synchronization, inter thread
communication, deadlock.

Exception Handling:

Exception handling in Java is the mechanism of detecting runtime errors (exceptions) and
handling them gracefully so that the program does not crash and can continue or exit in a
controlled way.

In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Benefits of exception handling:

Here are the main benefits of exception handling you can explain to [Link] students:

1. Maintains normal program flow

• Instead of crashing on errors, the program can catch exceptions and continue or shutdown
gracefully.

• This is crucial in real applications (banking, e-commerce) where abrupt termination can cause
data loss or a bad user experience.

2. Separates logic from error handling

• Business logic goes in the normal code; error-handling logic goes in catch blocks.

• This separation makes code cleaner, easier to read, and easier to maintain.

3. Better error information

• Exception objects carry details: type, message, and stack trace (which line and which method).
• This helps developers quickly find and fix bugs.

4. Structured and object-oriented

• Exceptions are classes; different types represent different problems (e.g., IOException,
SQLException, NullPointerException).

• Using specific exception types makes handling precise and robust.

5. Error propagation (don’t handle everywhere)


• Using throws, a method can pass an exception to its caller instead of handling it locally.
• This allows handling errors at a central place (for example, near main or controller layer),
reducing duplication.

6. Resource cleanup

• With try-catch-finally (or try-with-resources), you can ensure that files, database connections,
and network resources are always closed, even when errors occur.

• This prevents resource leaks and improves performance and reliability.

Classification:

User-Defined Exception: if you want, you can create your Exceptions with messages and
conditions for JVM to understand when to throw them. User-defined Exceptions are also called
custom exceptions since they are not predefined and can be altered by the programmer.

To create a user-defined exception in Java:

Create a new class that extends the Exception class:


class MyException extends Exception {

// Constructors can be added here

}
Built-in Exception: Built-in Exceptions are those exceptions that are pre-defined in Java
Libraries. These are the most frequently occurring Exceptions. An example of a built-in exception
can be Arithmetic Exception;

It is a pre-defined exception in the Exception class of [Link] package. These can be further
divided into two types:

1. Checked Exception

2. Unchecked Exception

Checked Exception:

Checked exceptions are caught at compile time, indicating potentially recoverable errors. The
compiler enforces handling them before runtime. For instance, accessing a missing file like
"[Link]" can throw a FileNotFoundException, which can be handled using the throws keyword
to specify potential exceptions at compile time.
1. Class Not Found Exception: The ClassNotFoundException occurs when the Java Virtual
Machine (JVM) cannot locate a required class, typically triggered by functions
like [Link]() or [Link]().

Sample Code
public class classNotFound

static String classname = "missingClass";

public static void main() throws ClassNotFoundException

{
[Link](classname);

}
}

Expected output:

[Link]: missingClass

Explanation: The [Link]() function returns the object of the class or interface whose
name is passed in the parameter as a string. Now, if there is no class with the given name, then
this will cause the ClassNotFoundException and terminate the execution of our code.

2. Interrupted Exception: Interrupted Exception is raised when a thread is interrupted while


waiting, sleeping, or processing. In Java, threads are used to enhance code efficiency by
executing multiple tasks concurrently. This exception occurs when a thread's execution is
disrupted while it's paused or waiting.
3. IO Exception: The IO Exception is a frequently encountered exception in programming,
typically arising from input or output discrepancies. It indicates a failure or interruption in
input-output operations and can be handled using "throws" or will result in a compile-time error
if not addressed.
4. Instantiation Exception: Instantiation Exception occurs when attempting to create an
instance of a class that cannot be instantiated, such as abstract classes or interfaces, using the
newInstance method. This exception is thrown at compile time, often encountered when
instantiating abstract classes.

5. SQL Exception: SQL Exception is thrown if there is an error in database access or other
database errors.

6. FileNotFoundException: FileNotFoundException is thrown when we try to access a file in a


directory and the file is not found.

Unchecked Exceptions:

An Unchecked Exception is an exception that occurs during runtime, often due to logical errors
or improper usage of functions. These exceptions, also known as Runtime Exceptions, don't
require explicit declaration using the throws keyword and can lead to bugs or unexpected behavior
in code. Arithmetic Exception, such as division by zero, is a typical example of an unchecked
exception.

Arithmetic Exceptions: An ArithmeticException is thrown when the code does the wrong
arithmetic or mathematical operation while executing. Divide by 0 is the most common type
of wrong mathematical operation.

Class Cast Exception: Type casting involves changing the type of a variable or object. A
ClassCastException occurs when attempting to cast an object to an incompatible type, such as
trying to cast a String array to a List.
Null Pointer Exception: NullPointerException is thrown by the JVM when we try to access a
pointer pointing to Null (or Nothing). Pointing to Null means that no memory is allocated to
that specific object.

ArrayIndexOutOfBounds Exception: ArrayIndexOutOfBounds is thrown when we try to access


an array index that does not exist. Let us say that we have an array of size 10, and we try to
access the 15th element. Then, JVM will throw an ArrayIndexOutOfBounds exception.

ArrayStoreException: ArrayStoreException is thrown by JVM when we try to store the wrong


type of object in the array of objects. Let us say we have an object array of double, and we try
to store an integer. This will cause an exception at run time since a type mismatch exists.

IllegalThreadState Exception: The IllegalThreadStateException occurs when a thread is not in


the appropriate state for specific operations, such as giving commands while it's sleeping. To
handle potential InterruptExceptions.
Checked exceptions and Unchecked exceptions:

Checked Exceptions

Checked exceptions are checked by the compiler at compile-time. The programmer must either
handle these exceptions using a try-catch block or declare them with the throws keyword in the
method signature. These exceptions usually occur due to external factors beyond the program’s
control, such as file I/O errors or database access.

Example of Checked Exception:

import [Link].*;

public class CheckedExceptionExample {

public static void main(String[] args) {

try {
FileReader file = new FileReader("[Link]");

BufferedReader fileInput = new BufferedReader(file);

[Link]([Link]());

[Link]();

} catch (IOException e) {

[Link]("Exception caught: " + [Link]());

}
}

This program tries to read a file that doesn’t exist, causing a FileNotFoundException (which
is a checked exception) that must be handled explicitly, or the program will not compile.

Unchecked Exceptions

Unchecked exceptions are not checked at compile-time but occur at runtime. They are
subclasses of RuntimeException and represent bugs or logical errors, such as division by zero
or null pointer access. There is no requirement to handle or declare unchecked exceptions,
although you can catch them if desired.
Example of Unchecked Exception:
public class UncheckedExceptionExample {
public static void main(String[] args) {

int a = 10;

int b = 0;

int result = a / b; // This throws ArithmeticException at runtime


[Link]("Result: " + result);

This program compiles fine but throws an ArithmeticException (unchecked) at runtime


because division by zero is invalid.

Checked exception Unchecked exception

Predicted exceptions that are handled Unpredicted exceptions that are thrown at the
before execution of the code run time due to logical errors.

It does not include the run-time exceptions It includes the run-time exceptions.

We must address checked exceptions by


We need to address unchecked exceptions, and
the throws keyword or try-catch block(s).
the code will compile just fine.
Otherwise, it will not compile.

Examples: ArithmeticException,
Examples: ClassNotFoundException,
ClassCastException, NullPointerException,
InterruptedException, IOException,
ArrayIndexOutOfBounds Exception,
InstantiationException, SQLException,
ArrayStoreException,
FileNotFoundException
IllegalThreadStateException

Usage of try, catch, throw, throws and finally:

In Java, try, catch, throw, throws, and finally are fundamental keywords for exception handling,
enabling robust and error-tolerant applications.

1. try block:
• Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
• It Encloses the code segment where an exception might occur.

• If an exception is thrown within the try block, the program's control immediately
transfers to the corresponding catch block.

Sample code:

try {

// Code that might throw an exception

int result = 10 / 0; // This will throw an ArithmeticException


}

Or

Syntax of java try-catch

1. try{

2. //code that may throw exception

3. }catch(Exception_class_Name ref){}

Syntax of try-finally block


1. try{

2. //code that may throw exception

3. }finally{}

2. catch block:

• Follows a try block and handles specific types of exceptions.

• Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.

• It executes only if an exception matching its declared type is thrown in the


preceding try block.

• Multiple catch blocks can be used to handle different exception types.

Sample code:

catch (ArithmeticException e) {
// Handle the ArithmeticException

[Link]("Cannot divide by zero: " + [Link]());

} catch (Exception e) {
// Handle any other generic exception
[Link]("An unexpected error occurred: " + [Link]());

Or

public class Testtrycatch1{


public static void main(String args[]){

int data=50/0;//may throw exception

[Link]("rest of the code...");

}}

3. throw keyword:

• Used to explicitly throw an exception within a method or block of code.

• It can throw both predefined Java exceptions and custom exceptions created by the
programmer.

• The Java throw keyword is used to explicitly throw an exception. We can throw either
checked or uncheked exception in java by throw keyword. The throw keyword is mainly
used to throw custom exception.

Sample code:

if (age < 0) {

throw new IllegalArgumentException("Age cannot be negative.");

}
4. throws keyword:

• Declared in a method signature to indicate that the method might throw one or more
specified checked exceptions.

• It informs the caller of the method that these exceptions need to be handled.

Sample code:

public void readFile(String filePath) throws IOException {

// Code that might throw an IOException

// ...

5. finally block:
• Follows a try-catch block and guarantees the execution of its code regardless of
whether an exception occurred or was handled.
• Typically used for cleanup operations, such as closing resources (files, database
connections).

Sample code:

finally {

// Code that will always execute, regardless of exception or return statement

[Link]("Cleanup operations completed.");

All Combination Program:

import [Link].*;

public class ExceptionDemo {

public static void readFile(String fileName) throws IOException {

if (fileName == null) {
throw new IllegalArgumentException("File name cannot be null");

FileReader file = new FileReader(fileName);

BufferedReader reader = new BufferedReader(file);

[Link]([Link]());

[Link]();

public static void main(String[] args) {

try {

readFile(null); // throws IllegalArgumentException

} catch (IllegalArgumentException e) {

[Link]("Exception caught: " + [Link]());

} catch (IOException e) {
[Link]("IO exception: " + [Link]());
} finally {

[Link]("Finally block executed");

[Link]("Rest of the program continues...");


}

Here:

• try encloses code which may throw exceptions.

• throw explicitly throws an exception if input is invalid.

• throws declares the checked IOException in the method signature.


• Multiple catch blocks handle different exceptions.
• finally executes always for cleanup or final steps.

Re-throwing exceptions, Built in exceptions:

Re-throwing exceptions in Java involves catching an exception in a catch block and then
throwing the same exception again to be handled at a higher level in the call stack. This is
useful when you want to perform some intermediate steps like logging or cleanup before
passing the exception up the chain.
Reasons for Re-throwing:

• Partial Handling and Propagation:

A method might need to log an exception or perform some cleanup before allowing a calling
method to handle the core issue.

• Exception Chaining (Wrapping):

You can wrap a caught exception within a new, more specific exception type (e.g., a custom
exception) to provide more context or maintain abstraction, passing the original exception as the
"cause."

• Refined Error Handling:

A lower-level method might catch a general exception and re-throw a more specific one that
better describes the error in the context of its operation.
Code:
public class RethrowException {

public static void test1() throws Exception {

[Link]("Inside test1()");

throw new Exception("Exception thrown from test1()");


}

public static void test2() throws Throwable {

try {

test1();

} catch (Exception e) {

[Link]("Exception caught in test2(), rethrowing...");


throw e; // re-throwing the caught exception
}

public static void main(String[] args) {

try {

test2();

} catch (Exception e) {
[Link]("Exception caught in main: " + [Link]());

Here,

test1() throws an exception, test2() catches it but re-throws it, and finally main() catches and
handles it.

Built-in Exceptions in Java


Built-in exceptions are predefined exception classes provided by Java in the [Link] and other
packages. These are used to signal common error conditions in Java programs. They include:
• ArithmeticException: e.g., division by zero.

• NullPointerException: dereferencing a null object.

• ArrayIndexOutOfBoundsException: accessing invalid array indexes.

• ClassCastException: invalid type casting.


• IOException: Input/output related exceptions for files and streams.

• FileNotFoundException: when a file is not found (subclass of IOException).

• SQLException: errors related to database operations.

• And many others.

These exceptions fall into checked and unchecked categories, and Java runtime automatically
throws them in appropriate situations.

Creating own exception sub classes:

Creating your own exception subclasses in Java allows you to define custom behavior and error
messages specific to your application’s domain.

How to create a custom exception subclass:

Extend an existing exception class


• To create a checked exception, extend Exception class.

• To create an unchecked exception, extend RuntimeException.

Define constructors

• Provide constructors that call the superclass constructor with custom messages.

• You can optionally add more constructors or methods for additional context.

Throw and catch your custom exception

• Use throw to signal the exception in your code.

• Catch it with catch blocks or declare it with throws in method signature.

Code: Custom checked exception

// Custom checked exception class

class InsufficientBalanceException extends Exception {

public InsufficientBalanceException(String message) {


super(message);
}

// Class using the custom exception


class BankAccount {

private double balance;

public BankAccount(double balance) {

[Link] = balance;

public void withdraw(double amount) throws InsufficientBalanceException {


if (amount > balance) {

throw new InsufficientBalanceException("Insufficient balance for withdrawal!");

balance -= amount;

[Link]("Withdrawal successful. Remaining balance: " + balance);

// Main class to test

public class TestCustomException {

public static void main(String[] args) {

BankAccount account = new BankAccount(1000);

try {

[Link](1500);
} catch (InsufficientBalanceException e) {

[Link]("Caught exception: " + [Link]());


}
}

Code: Custom Unchecked exception


// Custom unchecked exception class

class InvalidAgeException extends RuntimeException {

public InvalidAgeException(String message) {

super(message);

public class AgeValidator {


public static void validateAge(int age) {
if (age < 18) {

throw new InvalidAgeException("Age must be at least 18");

[Link]("Age is valid");

public static void main(String[] args) {

validateAge(15);
}

Multithreading:

A Thread in java is a separate path of execution inside a program and multithreading means
having multiple threads running ‘independently but together’ within the same process and
sharing the same memory.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking. But we use multithreading than
multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process. Java Multithreading is mostly used in games, animation etc.
Every java program starts with at least one thread called as Main Thread.

This is the process of smallest unit of execution in JVM like stack & heap.

NEW RUNNABLE BLOCKED/WAITING TERMINATED.

(new MyThread()) (Start()) (wait()) (run())


New MyThread- It’s just a thread created but not runnable state.

Start()- it requests JVM to start a new thread and internally calls run() in that new thread.

Run()- The code representing the threads job, if you can run() directly. It runs in the current
thread not a new one.

Sleep()- It makes the current thread pause for a given time moving to timed waiting.

Join()- The current thread waits until another thread finishes.

Java Thread Model:


In java the thread model defines how the java represents Creates, Schedules and Coordinates
the multiple threads of execution inside a single program.

It is a shared memory, multithreaded model where many threads run in one JVM process.

What is Stack and Heap Memory:

Stack: The Primary work is used for storing local variables, function parameters and return
addresses during function calls. It manages the flow of program execution.

- Each thread (main thread, working thread etc,.) gets it’s own stack.
- The Stack Stores:
- Methods call frames (Which method is running, return address/path)

- Local variables and parameters of methods

- References (pointer) to objects in the heap.

Basically, it works in LIFO (Last-In-First-Out) order.

Heap: It is used for dynamic memory allocation, storing objects and data structures whose
size or lifetime is not known at compile time.

- The heap is a large shared area when all the objects created with ‘new’.

- Instance variables (fields) of objects and arrays are stored in the heap.

- It is managed by the Garbage Collector which frees objects that are no longer reachable.

The Main Thread and Creating a Thread:

In java the main thread is the first thread that starts when a program begins, And creating a
thread means adding more threads alongside this main thread to run code concurrently.

Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.

Main Thread:

- When ‘java thread’ runs the JVM automatically creates a thread called the main thread and
calls the main method ‘main (String[] args)’.

- This main thread can execute all the codes alone.

Creating a Thread:
Creating a thread means defining a separate path of execution and then starting it so, it runs
independently of the main method.
1. creating a thread using extend thread.

2. Implement runnable your thread to execute that.

Commonly used Constructors of Thread class:

1. Thread ()
2. Thread (String name)

3. Thread (Runnable r)

4. Thread (Runnable r,String name)

There are few more they are:

1. public void run(): is used to perform action for a thread.

2. public void start(): starts the execution of the [Link] calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.

4. public void join(): waits for a thread to die.

5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

6. public int getPriority(): returns the priority of the thread.

7. public int setPriority(int priority): changes the priority of the thread.


8. public String getName(): returns the name of the thread.

9. public void setName(String name): changes the name of the thread.

10. public Thread currentThread(): returns the reference of currently executing thread.

11. public int getId(): returns the id of the thread.

12. public [Link] getState(): returns the state of the thread.

13. public boolean isAlive(): tests if the thread is alive.

14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.

15. public void suspend(): is used to suspend the thread(depricated).

16. public void resume(): is used to resume the suspended thread(depricated).


17. public void stop(): is used to stop the thread(depricated).

18. public boolean isDaemon(): tests if the thread is a daemon thread.

19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.

22. public static boolean interrupted (): tests if the current thread has been interrupted.

Creating multiple threads:


Creating multiple threads in java means starting several independent paths of execution so that
different tasks can run concurrently in the same program.

So, you can create multiple threads either by the extending ‘thread’ or by implementing
‘runnable’ often using a loop or multiple thread objects.

-Multiple thread by extending Thread:


For each object of your ‘Thread’ subclass represents a separate thread, calling ‘start()’ on each
object create another concurrent flow.

In this you use t1, t2, t3… like this.


-Multiple threads by implementing Runnable:

Here with ‘Runnable’ you separate the task (what to do) from the thread (who runs it), which is
better OOPs deisgn and allows sharing one task between many threads if needed.

Using isAlive() and join():

isAlive() and join() are two thread methods is used to check and control whether another
thread has finished it’s work.

isAlive():

isAlive() tells whether a thread has been started and has not yet finished. It returns ‘true’ if the
thread is still running (or runnable), and ‘false’ if it has never been started or has already
completed.

Example:

class MyThread extends Thread {

public void run() {

[Link]("Child running...");

try {

[Link](1000); // simulate work


} catch (InterruptedException e) {
[Link]("Interrupted");
}

[Link]("Child finished");

public class IsAliveDemo {

public static void main(String[] args) throws InterruptedException {

MyThread t = new MyThread();

[Link]("Before start: " + [Link]()); // false

[Link](); // thread starts

[Link]("After start: " + [Link]()); // likely true

[Link](1500); // wait a bit

[Link]("After sleep: " + [Link]()); // now false

}
}

Join():

Join() makes the current thread wait until another thread finishes.

If ‘main’ calls ‘[Link]()’ the main thread pauses and only continues after ‘t’ has completed it’s
run() method.

This is used for coordination, Don’t continue until this worker thread is done.

Example:

class Worker extends Thread {


public void run() {
[Link]("Worker starting");

try {

[Link](2000); // simulate time-consuming task

} catch (InterruptedException e) {
[Link]("Worker interrupted");

[Link]("Worker done");

public class JoinDemo {


public static void main(String[] args) throws InterruptedException {
Worker w = new Worker();

[Link](); // start worker thread

[Link]("Main waiting for worker...");

[Link](); // main waits here

[Link]("Main continues after worker");


}

NOTE:

isAlive()- Ask a thread, Are you still running..? (It returns true/false)

join()- It Wait for this thread to finish before moving on.

Thread Priorities:

In java this thread priority is a number (1-10) that tells the JVM scheduler how important a thread
is relative to other threads.
Higher priority threads are more likely to get CPU time before lower priority once when several
threads are ready to run.

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority (known as preemptive
scheduling).

But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

Priority range and constants:

Priorities are integers from 1 to 10.

The ‘thread’ class defines three standard constants:

1) Thread.MIN_PRIORITY= 1 lower

2) Thread.NORM_PRIORITY= 5 Default for new threads

3) Thread.MAX_PRIORITY= 10 highest

These threads as by default inherit the priority of the thread that created them (Basically the
main thread with priority have 5) Unless you change it.

Example:

class MyThread extends Thread {

public MyThread(String name) {

super(name);

public void run() {


[Link](getName() + " with priority " + getPriority());

public class ThreadPriorityDemo {

public static void main(String[] args) {

MyThread t1 = new MyThread("Low");

MyThread t2 = new MyThread("Normal");

MyThread t3 = new MyThread("High");


[Link](Thread.MIN_PRIORITY); // 1

[Link](Thread.NORM_PRIORITY); // 5

[Link](Thread.MAX_PRIORITY); // 10

[Link]();

[Link]();

[Link]();

NOTE:
The schedular should favor High Normal and Normal Low, but the exact execution order
is not assured and also depends on OS and JVM.

Synchronzation:
Thread synchronization in java ensures that multiple threads accessing shared resources do so
in a controlled manner, Here main thing is only one thread can execute a synchronized section
at a time.

If you declare any method as synchronized, it is known as synchronized method. Synchronized


method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.

Why synchronization is need:

Without this synchronization, threads reading/writing shared data can interleave operations,
causing data corruption.

Synchronized methods:

Add ‘Synchronized’ to a method then the thread acquires the object’s intrinsic lock before
entering.

Only one thread can execute any ‘synchronized’ method on the same object instance at a time.

Other threads wait until the lock is realised (method ends normally).
• Mutual exclusion: Only one thread holds the lock at a time; others wait.
• Lock release: Automatic when synchronized block/method ends (normal exit or
exception).
• Object-level: Synchronization is per-object; different objects can run concurrently.

• static synchronized: Locks on the Class object itself (for static methods).

Inter thread communication:


Inter-thread communication in java allows multiple threads to coordinate and exchange
information by using the ‘wait()’, ‘notify()’ and ‘notifyAll()’ methods of the Object class.

These methods must called from within a synchronized block or a method on the same object
to enable one thread to pause (wait for a condition) while another signals (notifies) when it
ready.

There are three key methods:

• wait(): it Releases the lock and suspends the current thread until another thread calls notify()
or notifyAll() on the same object.

• notify(): it Wakes up one waiting thread (arbitrary choice by JVM).

• notifyAll(): Wakes up all waiting threads on the same object.


Example program is ProducerConsumerDemo progam.

DeadLock:

Deadlock in java it oocurs when 2 or more threads are permanently blocked, each waiting
indefinitely for the other to release a resource (lock) that it holds the other to circular dependency
with no progress possible.
Deadlock Scenario:

Two threads (t1 and t2) and two shared objects(A and B).

1. T1 accquires lock on A, then Waits for lock on B.

2. T2 accquires lock on B, then Waits for lock on A.

3. Both threads are stuck forever.

In deadlock all these four must be true:


1. Mutual Exclusion: The resource can’t be shared, only one thread holds at a time.

2. Hold and Wait: The thread holds at least one resource while waiting for another.

3. Circular Wait: Thread t1 waits for t2→t2 waits for t1 (like chain).

4. No Preemption: The resource can’t be forcibly taken from a thread.


UNIT- 4
Collections: Overview of Java Collection frame work, Commonly used Collection classes
Array List, Linked List, Hash Set, Tree Set, Collection Interfaces Collection, List, Set,
Accessing Collection via iterator, working with Map, Legacy classes and interfaces Vector,
Hashtable, Stack, Dictionary, Enumeration interface.

OtherUtilityclasses: String Tokenizer, Date, Calendar, Gregorian calendar, Scanner


Java Input/Output: Exploring [Link], Java I/O classes and interfaces: File, Stream classes,
byte stream, character stream, serialization.

Overview of java collection framework:

Collections:
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

Java defines common collection interfaces like collections, list, set, and queue, which specify
operations such as add(), remove(), size() and iterator().

Collection: Root interface that describes a group of objects and basic operations on them
(List, set, queue).
Collections: The utility class with static methods like (sort(), reverse(), shuffle() and
binarysearch()) to operate on collection objects.

Framework: It provides a readymade architecture to represent set of classes and interface.


Collection Framework: The collection framework represents a unified architecture for
storing and manipulating group of objects effectively (classes, interface and algorithms).
Java’s Collections Framework is a powerful set of classes and interfaces that provides a
foundation for working with groups of objects.
Whether you are dealing with lists, sets, maps, or queues, the Collections Framework offers
a rich set of tools to manipulate and organize data efficiently.

Commonly used Collection classes ArrayList:


ArrayList is the most commonly used implementation of the List interface in java collectios
framework, acting as a resizable array for dynamic storage of object.
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.
▪ Java ArrayList class can contain duplicate elements.
▪ Java ArrayList class maintains insertion order.
▪ Java ArrayList class is non synchronized.
▪ Java ArrayList allows random access because array works at the index basis.
▪ In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.

Sample code of ArrayList:


import [Link];
import [Link];

public class ArrayListDemo {


public static void main(String[] args) {
// Create ArrayList (generic type safety)
List<String> languages = new ArrayList<>(); // or ArrayList<String>

// Add elements
[Link]("Java");
[Link]("Python");
[Link](1, "C++"); // insert at index 1

// Access and iterate


[Link]("Element at 0: " + [Link](0));
for (String lang : languages) {
[Link](lang);
}

// Modify and remove


[Link](2, "YourName");
[Link]("Python");
[Link]("After changes: " + languages);
[Link]("Size: " + [Link]());
}
}
Output:
Element at 0: Java
Java
C++
Python
After changes: [Java, C++, YourName]

Size: 3

LinkedList:
A linked list is a dynamic data structure where elements (nodes) are connected using
references (links) instead of being stored in a continuous block of memory like an array.
In java the main readymade implementation is the ‘ [Link] ’ class, which is
represents a doubly linked list that also implements the List and Deque interfaces.

Actual Concept:
1. Each node typically contains two parts that is 1. Data (values) and 2. One or more links
(references) to other nodes.
2. In a single linked list, each node points to the next node only.
But here, in doubly linked list each node points to both the next and the previous nodes.
Which is done in internally.

Java Linked List class overview:

• Package we’re using [Link]


• The internal implemented as a doubly linked list (both next and previous).
• It Implements like: List<E>, Deque<E>, Queue<E>, then it will behave like: A linear
list( with indexes), A Queue(FIFO: addLast, removeFirst), A Stack(LIFO: push,
pop).
Basic program on insertion, index, iteration and deletion:
import [Link];
import [Link];

public class LinkedListDemo {


public static void main(String[] args) {
// Create LinkedList as a List
List<String> students = new LinkedList<>();

// Add elements
[Link]("A"); // index 0
[Link]("B"); // index 1
[Link](1, "C"); // insert at index 1

// Access by index
[Link]("First student: " + [Link](0));

// Iterate
for (String s : students) {
[Link](s);
}

// Remove
[Link]("C");
[Link]("After removal: " + students);
}
}

Output: First student: A


A
C
B
After removal: [A, B]

Another Program using LinkedList: (FIFO, LIFO, Deque)

1. import [Link];

public class QueueDemo {


public static void main(String[] args) {
LinkedList<String> queue = new LinkedList<>();

// Queue operations (FIFO)


[Link]("Task1");
[Link]("Task2");
[Link]("Task3");

[Link]("Front: " + [Link]()); // see head


while (![Link]()) {
[Link]("Processing: " + [Link]());
}
}
}
Output:
Front: Task1
Processing: Task1
Processing: Task2
Processing: Task3

So, here the methods we’re using is ‘addFirst(E,e)’, ‘addLast(E,e)’, ‘removeFirst()’,


‘removeLast()’, ‘peekFirst()’, ‘peekLast()’.
‘push(E,e)’, ‘pop()’ is used only when it as a stack.

2. import [Link];

public class StackDemo {


public static void main(String[] args) {
// Create a stack of integers
Stack<Integer> stack = new Stack<>();

// Push = insert at top


[Link](10);
[Link](20);
[Link](30);

[Link]("Initial Stack: " + stack);

// Peek = see top element without removing


[Link]("Top element (peek): " + [Link]());

// Pop = remove from top


int popped = [Link]();
[Link]("Popped element: " + popped);

[Link]("Stack after pop: " + stack);

// Check empty
[Link]("Is stack empty? " + [Link]());
}
}
Output:
Initial Stack: [10,20,30]
Top element (peek): 30
Popped element: 30
Stack after pop: [10,20]
Is stack empty? False
3. import [Link];
import [Link];

public class DequeDemo {


public static void main(String[] args) {
// Create a deque of integers
Deque<Integer> deque = new ArrayDeque<>();

// Add at both ends


[Link](10); // same as offerLast
[Link](20);
[Link](5); // add at front

[Link]("Initial Deque: " + deque); // [5, 10, 20]

// Access ends without removing


[Link]("First element: " + [Link]());
[Link]("Last element: " + [Link]());

// Remove from both ends


int firstRemoved = [Link]();
int lastRemoved = [Link]();

[Link]("Removed first: " + firstRemoved);


[Link]("Removed last: " + lastRemoved);
[Link]("Deque after removals: " + deque);

// Use as stack (LIFO) with push/pop


[Link](100); // push at front
[Link](200);
[Link]("Deque as stack: " + deque);
[Link]("Popped: " + [Link]());
[Link]("After pop: " + deque);
}
}
Output:
Initial Deque: [5, 10, 20]
First element: 5
Last element: 20
Removed first: 5
Removed last: 20
Deque after removals: [10]
Deque as stack: [200, 100, 10]
Popped; 200
After pop: [100, 10]

Hash Set and Tree Set:


This Hash Set and Tree set in java, both are used in implementations to store unique
elements (no-duplicates) but they differ mainly in the ordering, performance in use case.
Before understanding the Hashset and Treeset first know about HashMap and HashTable.
HashMap and HashTable:
In java both are key-value storage implementation that using hashing for fast lookups, but
HashMap is the modern preferred choice while Hashtable is a legacy synchronized version.

HashMap:
Hashmap implements the Map interface and stores entries in a hash table using an array
of buckets/blocks with chaining (linked lists or trees for collisions).
It allows only One Null key and Multiple Null values, then it permits duplicates and it doesn’t
guarantee iteration order.
HashMap Program:
import [Link];
import [Link];

public class HashMapDemo {


public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
[Link]("ABC", 01);
[Link]("DEF", 02);
[Link](null, 0); // null key allowed
[Link]("ABC", 01); // overwrites previous

[Link]("ABC: " + [Link]("ABC"));


[Link]("Map: " + map);
}
}
Output:
ABC: 01
Map: {null=0, ABC=01, DEF=02}

HashTable:
Hashtable is an older class that also implements Map but is fully synchronized (thread safe)
by default, making it slower for single-threaded use.
It doesn’t allow null keys or values and uses Enumeration for legacy iteration.

HashTable Program:
import [Link];
import [Link];

public class HashtableDemo {


public static void main(String[] args) {
Hashtable<String, Integer> table = new Hashtable<>();
[Link]("ABC", 01);
[Link]("DEF", 02);
// [Link](null, 0); // NullPointerException!

Enumeration<String> keys = [Link]();


while ([Link]()) {
String key = [Link]();
[Link](key + ": " + [Link](key));
}
}
}
Output:
ABC: 01
DEF: 02

Hash Set and Tree Set:

HashSet:

It is backed by a hash table (internally uses a hashmap) and doesn’t maintain any order of
elements.
It allows at most one null element and doesn’t permit duplicates.
The average time complexity for add, remove and contains O1 due to hashing, so it is
generally faster than TreeSet for basic operations.

HashSet Program:
import [Link];
import [Link];

public class HashSetDemo {


public static void main(String[] args) {
Set<String> set = new HashSet<>();

[Link]("Banana");
[Link]("Apple");
[Link]("Mango");
[Link]("Apple"); // duplicate, ignored
[Link](null); // allowed once

[Link]("HashSet: " + set);


[Link]("Contains 'Apple'? " + [Link]("Apple"));
}
}
Output:
HashSet: [null, Apple, Mango, Banana]
Contains ‘Apple’? true
Note: Here order doesn’t matter.

TreeSet:

It implements NavigableSet / SortedSet and is backed by a self-balancing tree like (Red-


Black tree) internally using TreeSet.
It stores elements in Sorted order and doesn’t allow null elements (if added it throws
NullPointerException).
The time complexity for add, remove and contains is O(log n) , slower than HashSet for basic
operations but provides extra navigation methods like higher(), lower(), ceiling(), floor().

TreeSet Program:
import [Link];
import [Link];

public class TreeSetDemo {


public static void main(String[] args) {
Set<String> set = new TreeSet<>();

[Link]("Banana");
[Link]("Apple");
[Link]("Mango");
[Link]("Apple"); // duplicate, ignored

[Link]("TreeSet (sorted): " + set);

// Cast to TreeSet/NavigableSet to use navigation methods


TreeSet<String> tset = (TreeSet<String>) set;
[Link]("Higher than 'Apple': " + [Link]("Apple"));
[Link]("Ceiling of 'Ball': " + [Link]("Ball"));
}
}
Output:
TreeSet (sorted): [Apple, Banana, Mango]
Higher than ‘Apple’: Banana
Ceiling of ‘Ball’: Banana

List and Set:


In java List and Set are the core interface collections framework for storing groups of objects,
but it serves different purposes based on the ordering and duplication rules.

List interface:
List represent an ordered collection that maintains insertion sequence and allows duplicate
elements with positional (index-based) access.

Key terms:
1. It allows duplicates.
2. It maintains insertion order.
3. It access using indexed values.
4. It implements ArrayList, LinkedList, Vector.

List Sample program:


import [Link].*;

public class ListDemo {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("Apple"); // index 0
[Link]("Banana"); // index 1
[Link]("Apple"); // duplicate allowed, index 2

[Link]("List: " + list); // [Apple, Banana, Apple]


[Link]("Element at 1: " + [Link](1)); // Banana
}
}
Output:
List: [Apple, Banana, Apple]
Element at 1: Banana
Set interface:
The set represents a collection of unique elements with no duplicates (it uses ‘equals()’ for
comparison).
Key terms:
1. No duplicates allowed.
2. No guaranteed order (except TreeSet, LinkedHashSet).
3. No index value based access.
4. It implements HashSet, TreeSet, LinkedHashSet.

Set sample program:


import [Link].*;

public class SetDemo {


public static void main(String[] args) {
Set<String> set = new HashSet<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Apple"); // ignored - duplicate

[Link]("Set: " + set); // [Banana, Apple] (order unpredictable)


[Link]("Contains Apple? " + [Link]("Apple")); // true
}
}
Output:
Set: [Apple, Banana]
Contains Apple? True

Vector:
ArrayList and Vector both implements List interface and maintains insertion order.
Enumeration:
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time)
the elements in a collection of objects.
It will implement one after one object which we pass in the code.

Iterator:
It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can
perform both read and remove operations. It is improved version of Enumeration with
additional functionality of remove-ability of a element.
Iterator must be used whenever we want to enumerate elements in all Collection framework
implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of
Map interface. Iterator is the only cursor available for entire collection framework. Iterator
object can be created by calling iterator() method present in Collection interface.

Java Utility Classes:

StringTokenizer in Java:
The ‘[Link]’ class allows you to break a string into tokens. It is simple
way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
Example: “Oop’s using java is a programming language”
So, here the character’s that separate tokens (space “ ”, comma “,”, etc..)
That the output will be the sequence of tokens (“Oop’s”, “using”, “java”, “is”, “a”,
“programming”, “language”).

Common Key methods are:


1. Boolean hasMoreTokens()- It returns true if there is atleast one more token.
2. String nextToken()- It returns the next token.
3. String nextToken(String delim)- It changes delimiter for this call and returns next token.
4. int countToken()- The [Link] token remaining.
5. Boolean hasMoreElements()/Object nextElement()- The same as above but for
Enumeration compatibility.
Date and Calendar:
The Date and Calendar are java utility classes in [Link] used for representing and
manipulating dates and times.

Date class ([Link]):


It represents a specific instant in time with millisecond precision since 01Jan1970.
The earlier version of date had many methods (getYear, setMonth,etc..) but most are now
deprecated modern code uses date mostly as a timestamp object and delegates
formatting/manipulation to other classes.

Sample program:
import [Link];

public class DateDemo {


public static void main(String[] args) {
Date now = new Date(); // current date-time
[Link]("Now: " + now);
}
}

Output: It will the present live date and time with the format (Day Year Time [Link])

Calendar class ([Link]):


The calendar is an abstract class that lets you work with separate date/time fields (YEAR,
MONTH, DAY_OF_MONTH, HOUR, etc.) and it perform arithmetic like 7 days or 3 months.
Here you can’t initiate it with ‘new’ instead of that use [Link]() which returns
a GregorianCalendar object by default.

Sample program:
import [Link];

public class CalendarDemo1 {


public static void main(String[] args) {
Calendar cal = [Link](); // current date-time

int year = [Link]([Link]);


int month = [Link]([Link]) + 1; // 0-based, so +1
int day = [Link](Calendar.DAY_OF_MONTH);

int hour = [Link](Calendar.HOUR_OF_DAY);


int minute = [Link]([Link]);
int second = [Link]([Link]);

[Link]("Date: " + day + "-" + month + "-" + year);


[Link]("Time: " + hour + ":" + minute + ":" + second);
}
}

Output:
Date: It shows Current date format (DD-MM-YYYY)
Time: It will show current time format (Hr:Min:Sec)

Another program to Set a specific date:


import [Link];

public class CalendarDemo2 {


public static void main(String[] args) {
Calendar cal = [Link]();

// 25 December 2025
[Link]([Link], 2025);
[Link]([Link], [Link]); // or 11
[Link](Calendar.DAY_OF_MONTH, 25);

[Link]("Christmas 2025: " + [Link]());


}
}
Output:
Christmas 2025: Thu Dec 25 04:32:41pm

Gregorian Calendar:
It is a concrete subclass of the abstract Calendar class that implements the standard
Gregorian calendar system which is used worldwide today, with leap year rules every 4
years except century years not divisible by 400.

Key terms:
1. [Link]()- It returns a GregorianCalendar by default in most locales.
2. You can explicitly create it with ‘new GregorianCalendar() or with specific date/time
values.
3. It handles Gregorian calendar rules: Leap years, months lengths etc., automatically.

Features of this calendar:


1. isLeapYear(int year)- It checks if year is leap year or not.
2. It transition from ‘Julian calendar’ to ‘Gregorian calendar’ 15Oct1582.
Scanner:
Scanner is a utility class in [Link] package designed to parse primitive types and strings
using regular experssions.
It reads input from various sources like [Link], file, strings, etc., making it ideal for console
applications and input processing.
Key features:
1. It breaks input into tokens using whitespace delimiter by default (space, ta, newline).
2. It provides type-safe methods: nextInt(), nextDouble(), nextLine(), next(), etc.,
3. It supports custom delimiters via ‘useDelimiter()’
4. It implements ‘Iterator<string>’ for token-by-token reading.
5. It always calls ‘[Link]’ to prevent resource leak.
6. ‘nextLine() after nextInt() can cause issues (leftover newline) then use [Link]().
7. Exception handling: It wrap in try-catch for ‘InputMismatchException’.
8. We can use scanner for all operations in modern java program.

Java input/output:
Exploring [Link]:
[Link] is java’s core package for input/output operations, it providing a hierarchy of stream
classes to read from and write to various sources like files, console, network sockets and
memory buffers.

Core I/O concepts:


1. Input stream: It reads data from source to program (files, keyboard, network).
2. Output stream: Program to write data to destination (files, screen, network).
Stream category mainly two types:
1. Byte Streams- Raw binary data (images, audio, executable)
2. Character Streams- Text data (handle encoding automatically)

Stream Hierarchy Overview:

InputStream (abstract)
├── FileInputStream
├── ByteArrayInputStream
└── BufferedInputStream

OutputStream (abstract)
├── FileOutputStream
├── ByteArrayOutputStream
└── BufferedOutputStream

Reader (abstract)
├── FileReader
├── BufferedReader
└── InputStreamReader

Writer (abstract)
├── FileWriter
├── BufferedWriter
└── PrintWriter
Java I/O Classes and Interfaces:
Java’s ‘[Link]’ package contains a comprehensive hierarchy of abstract classes, concrete
classes and interfaces for input/output operations, it is organized into byte streams and
character streams.

The [Link] package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination.
The stream in the [Link] package supports many data such as primitives, object, localized
characters, etc.
Stream:
A stream can be defined as a sequence of data. There are two kinds of Streams –
• InPutStream − The InputStream is used to read data from a source.
• OutPutStream − The OutputStream is used for writing data to a destination.

Byte Stream Classes:


Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream.

InputStream
├── FileInputStream // Read from file
├── BufferedInputStream // Buffered reading
├── DataInputStream // Read primitives (int, double)
└── ObjectInputStream // Read serialized objects

Character Stream Classes:


Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here the major difference is that FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.

We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −

Reader
├── FileReader // Read text file
├── BufferedReader // Efficient line-by-line reading
└── InputStreamReader // Convert byte to char

Writer
├── FileWriter // Write text file
├── BufferedWriter // Efficient buffered writing
└── PrintWriter // Formatted output (println, printf)

Note:
1. Byte Streams= Binary, Charater Streams=Text
2. Always use try with resources+Buffered streams
3. The most BufferedReader+PrintWriter for the files.
4. The exception handle is IOException.

Serialization:
The serialization in java is the process of converting an object state (it’s fields and values)
into a byte stream that can be saved to a file, sent over a network or stored in a database.
The reverse process de-serialization reconstructs the object from the byte stream.
Concept:
To serialize a class, it must implement the ‘[Link]’ maker interface (contain no
methods).
During serialization follow this:
1. Object’s class name
2. Object’s field values (non-transient)
3. Class metadata (serialVersionUID)

Key terms:
1. ObjectOutputStream: Serializes objects to OutStream
2. ObjectInputStream: Deserializes objects from InputStream

Serialization= Object-> bytes.


Serialization class+[Link]()

Sample Serialization Program: (Object->File)

import [Link].*;

public class SerializeDemo {


public static void main(String[] args) {
Student student = new Student("Rahul", 101, "secret123");

try (ObjectOutputStream oos = new ObjectOutputStream(


new FileOutputStream("[Link]"))) {
[Link](student);
[Link]("Student serialized to [Link]");
} catch (IOException e) {
[Link]();
}
}
}

Sample De-serialization Program: (File->Object)

import [Link].*;

public class DeserializeDemo {


public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("[Link]"))) {
Student student = (Student) [Link]();
[Link]("Deserialized: " + student);
// password will be null (transient)
} catch (IOException | ClassNotFoundException e) {
[Link]();
}
}
}
Unit-5
GUI Programming with java: The AWT class hierarchy, MVC architecture.
Event Handling: Delegation Event Model, Event Classes, Source of Events, Event Listener
Interfaces, Handling mouse and keyboard events, Adapter classes.

The AWT class hierarchy:


AWT is about to creating windows, adding visual components (buttons, text fields, labels, etc.),
arranging them using layout managers and reacting to user events with the event delegation
model.
AWT library provides a class hierarchy that organizes all these GUI objects.
AWT (Abstract Window Toolkit) is the original GUI toolkit in java, in the [Link] package
used to build desktop windows, dialog boxes and simple 2D interface.
Tip: Every GUI element is an object, the window is an object, the layout is an object, the event
listener is an object.

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications
in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of
OS.
The [Link] package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

AWT class hierarchy:

The AWT hierarchy starts from [Link] and becomes specialized step by step, at the
high level.
`[Link]`
`[Link]` (root for all AWT visual components)
`[Link]` (a component that can contain other components)
`[Link]` (a top-level window with no borders/menu by itself).
`[Link]` (a normal application window with title bar, border, etc.)
`[Link]` (a popup dialog window, often dependent on a `Frame`)
`[Link]` (a rectangular area inside a window used for grouping components)
`[Link]` (a clickable button).
`[Link]` (non-editable text).
`[Link]` (abstract base for text input).
`[Link]` (single-line text box)
`[Link]` (multi-line text box)
`[Link]` (check box)
`[Link]`, `Choice`, `Scrollbar`, etc..

`Container` “is-a” `Component` and “has” other `Component` children; that is classic OOP
inheritance and composition together.

MVC Architecture:

MVC (Model View Controller) is an architectural pattern that splits an application into three
cooperating parts so that data, user interface and input logic are kept separate and easier to
maintain.
It is widely used in java GUI and Web frameworks and connects very well with Oop’s
Principles.
Three parts of MVC:

1. View: It asks the model for data and displays it, it avoids business logic and focuses on
rendering and basic interaction. It is the responsible for presentation and user interface what the
user sees (Windows, HTMl pages, forms, tables, labels, etc.,)

2. Controller: It acts as a coordinator between model and view so they stay loosely coupled. It
handles user input (button clicks, menu actions, HTTPS requests) interprets it and decides which
model operations to call and which view to show.
3. Model: It doesn’t know how data is shown on the screen, it just exposes methods to get and
update state and may notify observers (views/controllers) when it’s state changes. It holds
application data and business rules, it represents the ‘real world’ objects of the problems
(Students, Accounts, Products etc.,)

NOTE: Model= Data+rules, View= Screen, Controller= Decision maker.

USER VIEW CONTROLLER MODEL

USER VIEW CONTROLLER

Benefits:

1. Separate of concerns: UI code, Business logic, different classes etc.

2. Maintainability and Scalability: You can change the user interface based on our requirement.
3. Reusability and Testability: Reusing means you can change, swap or extend with minimal
impact on the others.

Event Handling: (Event= Something happened, Handler= What to do when it happens).

The event handling in java is the process of which a program detects that something happened
like button clicking or key pressing and it runs specific code in response to that occurrence.

In AWT and Swing this is implemented using the ‘delegation event model’ where a source
component sends an event object to one or more registered listener objects.
Delegation Event Model:

The delegation event model in java is a modern approach to event handling, where event sources
delegate responsibility for processing events to separate listener objects rather than handling
them internally.
Three main concepts:

1. Event Source: GUI components like buttons, textfield and frame that detects user action and
generates the event.

2. Event Object: Subclass of ‘[Link]’ like ‘ActionEvent’, ‘MouseEvent’ it carries


event details like source timestamp etc.

3. Event Listener: Object implementing a listener interface eg. ActionListener with handler
methods like ‘actionPerformed(ActionEvent e).

Event Classes, Source of Events and Event Listener Interface:

Event classes, event sources, and listener interfaces form the backbone of Java's delegation event
model in AWT, enabling components to notify registered objects about user interactions.

Event Classes (hierarchy)

All AWT events derive from [Link] → [Link].

Event Class Description Common Triggers

Button clicks, double-clicks on lists, menu Button, List,


ActionEvent
selections. MenuItem

Checkbox, Choice,
ItemEvent Checkbox/choice/list selection changes
List

Any Component with


KeyEvent Keyboard input (press/release/typed)
focus

MouseEvent Mouse actions (click/move/enter/exit) Any Component

Frame, Dialog,
WindowEvent Window state changes (open/close/iconify)
Window

AdjustmentEvent Scrollbar adjustments Scrollbar, ScrollPane

TextEvent Text content changes TextField, TextArea

ComponentEvent Component resize/move/show/hide Any Component

Each event object carries details: getSource(), getID(), coordinates, modifiers, etc.
Event Sources

Sources are AWT components that detect user actions and generate events. They
provide addXXXListener() methods for registration:

Source Component Generates These Events

Button ActionEvent

Checkbox, Choice, List ItemEvent, ActionEvent

TextField, TextArea ActionEvent, TextEvent, KeyEvent

Scrollbar AdjustmentEvent

Frame, Dialog WindowEvent

Any Component MouseEvent, KeyEvent, ComponentEvent, FocusEvent

Registration example: [Link](listenerObj) links source to listener.

Event Listener Interfaces


Listeners are interfaces in [Link] defining handler methods. Implementing classes
override these methods.

Event Type Listener Interface Key Method(s)

Action ActionListener actionPerformed(ActionEvent)

Item ItemListener itemStateChanged(ItemEvent)

keyPressed(KeyEvent), keyReleased(KeyEvent),
Key KeyListener
keyTyped(KeyEvent)

mouseClicked(MouseEvent),
Mouse MouseListener
mousePressed(MouseEvent), etc.
Event Type Listener Interface Key Method(s)

Mouse mouseMoved(MouseEvent),
MouseMotionListener
Motion mouseDragged(MouseEvent)

windowClosing(WindowEvent),
Window WindowListener
windowClosed(WindowEvent), etc.

Adjustment AdjustmentListener adjustmentValueChanged(AdjustmentEvent)

Text TextListener textValueChanged(TextEvent)

Component ComponentListener componentResized(ComponentEvent), etc.

Adapter classes (e.g., MouseAdapter) provide empty implementations for interfaces with
multiple methods, letting students override only needed ones.
Adapter classes:

Adapter classes in Java AWT are abstract classes that provide empty (no-op) implementations
for all methods of listener interfaces, making it easier to implement event handling without
overriding every method in multi-method interfaces.

Why adapter classes exist

Many listener interfaces have multiple methods (e.g., MouseListener has 5


methods: mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited).
Implementing the interface directly requires overriding all methods, even if you only need one.

Adapter classes solve this: extend the adapter, override only the methods you care about, and the
rest stay empty.

Common AWT adapter classes

All adapters are in [Link] package and named *Adapter:

Listener Interface Adapter Class Methods in Adapter

MouseListener MouseAdapter 5 mouse event methods

MouseMotionListener MouseMotionAdapter mouseMoved, mouseDragged

KeyListener KeyAdapter 3 key event methods

WindowListener WindowAdapter 7 window event methods

ComponentListener ComponentAdapter 4 component resize/move methods

FocusListener FocusAdapter 2 focus gain/loss methods

Adapter = convenience wrapper around multi-method listener interfaces.

Extend adapter → override only needed methods (inheritance + polymorphism)

Handling mouse and keyboard events:


Mouse and keyboard events in Java AWT are handled through low-level listener interfaces that
capture precise user input details like coordinates, key codes, and modifiers (Shift, Ctrl, etc.).
These events work on any Component with focus and are essential for games, drawing apps, and
interactive UI’s.
Mouse Events

Interfaces: MouseListener (clicks) + MouseMotionListener (movement).

Interface Methods Trigger

mouseClicked(), mousePressed(),
Mouse button actions,
MouseListener mouseReleased(), mouseEntered(),
hover in/out.
mouseExited()

Mouse movement, drag


MouseMotionListener mouseMoved(), mouseDragged()
(with button down) .

MouseEvent details: getX(), getY(), getButton(), getClickCount(), isShiftDown(), etc.

Keyboard Events
Interface: KeyListener with 3 methods.

Method Trigger

keyPressed(KeyEvent e) Any key goes down (best for games/arrows)

keyReleased(KeyEvent e) Key comes up

keyTyped(KeyEvent e) Complete keystroke (press+release, ignores modifiers)

KeyEvent details: getKeyCode(), getKeyChar(), getModifiers().

--------------------------------THE END------------------------------
THANK YOU

You might also like