Java Course - File (1-5 Units)
Java Course - File (1-5 Units)
UNIT-1
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:
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.
[Link]();
[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
class Calculator {
// Method to add two integers
return a + b;
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;
class Vehicle {
[Link]("Vehicle is running.");
@Override
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]("----------------------------------");
}
Abstraction:
@Override
[Link]();
[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.
class Student {
[Link] = id;
return name;
[Link] = newName;
} else {
return id;
}
public class EncapsulationDemo {
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.
There are many java versions that has been released. Current stable release of Java is Java SE 8.
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
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:
• 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
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.
• Entry Point: Used specific methods like init(), start(), and paint(), inheriting from the
[Link] class.
import [Link];
import [Link];
}
}
Data Types:
Data types represent the different values to be stored in the variable. In java, there are two types
of data types:
long worldPopulation = 8_000_000_000L; // Long integer for large numbers (64-bit). The 'L'
suffix is required.
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.
}
A Simple Non-Primitive datatype:
// Printing the object reference (This typically prints the object's hash code)
}
}
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:
1. local variable
2. instance variable
3. static variable
1) 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.
int a = 15;
int b = 4;
// Addition (+)
int sum = a + b;
// Subtraction (-)
int difference = a - b;
[Link]("a - b = " + difference); // Output: 11
// Multiplication (*)
int product = a * b;
int quotient = a / b;
int remainder = a % b;
// Equal to (==)
int c = 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.
Widening conversion takes place when two data types are automatically converted.
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.
int smallInt = (int) bigDouble; // Explicitly cast double to int. Decimal part (.87) is lost.
int smallerInt = (int) bigLong; // Explicitly cast long to int. This will cause data
corruption/overflow
byte myNewByte = (byte) (myByte + 1); // Arithmetic operation on byte/short returns an int.
}
}
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.
2. Parameterized constructor
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:
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:
3. this() can be used to invoke current class constructor. JAVA PROGRAMMING Page 30 Java
Constructor Java Method
6. this can be used to return the current class instance from the method.
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;
public Car() {
[Link] = model;
[Link] = year;
[Link]("Parameterized Constructor called: " + model + " (" + year + ") created.");
}
}
[Link]("---");
[Link]();
// Output: Model: Tesla Model Y, Year: 2023
[Link]("---");
// 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.");
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.
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.
• Access: It has direct access to all members (static and non-static, including private ones)
of its enclosing class.
• 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.
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'};
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.
[Link]("-------------------------");
}
}
UNIT-2
Inheritance: Inheritance concept, types of inheritance, Member access rules, use of super and
final.
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
}
All inheritance program:
class Animal {
}
// Subclass for multilevel inheritance (Mammal -> Animal)
class Dog extends Mammal { // Multilevel: Inherits from Mammal (which inherits from Animal)
// Another subclass for hierarchical inheritance (shares Mammal as parent with Dog)
class Cat extends Mammal { // Hierarchical: Both Dog and Cat extend Mammal
interface Flyable {
void fly();
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
@Override
@Override
}
}
@Override
public void fly() {
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:
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:
• 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.
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:
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.
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.
Method overriding is used to provide specific implementation of a method that is already provided
by its super class.
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.
Multiple interfaces:
Implementing interfaces:
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:
interface Vehicle {
void startEngine();
int getWheelCount();
@Override
return 4;
@Override
@Override
return 2;
// 3. Demonstration Class
// Call the method, the JVM decides which implementation (Car's or Bicycle's) to use at
runtime.
[Link](); // Calls Car's implementation
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.
A new interface can extend a single existing interface to add more specific functionality.
// 1. Base Interface
void eat();
// 2. Extending Interface
public interface Pet extends Animal {
// 3. Implementing Class must fulfill all methods from the chain (Animal + Pet)
@Override
[Link]("Cat is eating.");
@Override
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.
Packages act like folders in a file system, grouping related types (classes, interfaces, enums, etc.).
This makes large projects easier to manage and navigate.
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]).
• 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];
// 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:
To use a class from another package, you have two main options:
You can use the complete path every time you reference the class. This is rarely used but avoids
the need for an import statement.
}
}
IMPORTING A PACKAGE:
All-Classes import [Link].*; Imports all classes from the [Link] package
(Wildcard) (but not sub-packages).
package [Link];
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:
• 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.
• 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.
• Exception objects carry details: type, message, and stack trace (which line and which method).
• This helps developers quickly find and fix bugs.
• Exceptions are classes; different types represent different problems (e.g., IOException,
SQLException, NullPointerException).
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.
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.
}
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
{
[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.
5. SQL Exception: SQL Exception is thrown if there is an error in database access or other
database errors.
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.
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.
import [Link].*;
try {
FileReader file = new FileReader("[Link]");
[Link]([Link]());
[Link]();
} catch (IOException e) {
}
}
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;
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.
Examples: ArithmeticException,
Examples: ClassNotFoundException,
ClassCastException, NullPointerException,
InterruptedException, IOException,
ArrayIndexOutOfBounds Exception,
InstantiationException, SQLException,
ArrayStoreException,
FileNotFoundException
IllegalThreadStateException
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 {
Or
1. try{
3. }catch(Exception_class_Name ref){}
3. }finally{}
2. catch block:
• 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.
Sample code:
catch (ArithmeticException e) {
// Handle the ArithmeticException
} catch (Exception e) {
// Handle any other generic exception
[Link]("An unexpected error occurred: " + [Link]());
Or
}}
3. throw keyword:
• 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) {
}
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:
// ...
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 {
import [Link].*;
if (fileName == null) {
throw new IllegalArgumentException("File name cannot be null");
[Link]([Link]());
[Link]();
try {
} catch (IllegalArgumentException e) {
} catch (IOException e) {
[Link]("IO exception: " + [Link]());
} finally {
Here:
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:
A method might need to log an exception or perform some cleanup before allowing a calling
method to handle the core issue.
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."
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 {
[Link]("Inside test1()");
try {
test1();
} catch (Exception e) {
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.
These exceptions fall into checked and unchecked categories, and Java runtime automatically
throws them in appropriate situations.
Creating your own exception subclasses in Java allows you to define custom behavior and error
messages specific to your application’s domain.
Define constructors
• Provide constructors that call the superclass constructor with custom messages.
• You can optionally add more constructors or methods for additional context.
[Link] = balance;
balance -= amount;
try {
[Link](1500);
} catch (InsufficientBalanceException e) {
super(message);
[Link]("Age is valid");
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.
This is the process of smallest unit of execution in JVM like stack & heap.
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.
It is a shared memory, multithreaded model where many threads run in one JVM process.
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)
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.
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)’.
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.
1. Thread ()
2. Thread (String name)
3. Thread (Runnable r)
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.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
10. public Thread currentThread(): returns the reference of currently executing thread.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
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.
So, you can create multiple threads either by the extending ‘thread’ or by implementing
‘runnable’ often using a loop or multiple thread objects.
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.
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:
[Link]("Child running...");
try {
[Link]("Child finished");
}
}
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:
try {
} catch (InterruptedException e) {
[Link]("Worker interrupted");
[Link]("Worker done");
NOTE:
isAlive()- Ask a thread, Are you still running..? (It returns true/false)
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.
1) Thread.MIN_PRIORITY= 1 lower
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:
super(name);
[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.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
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).
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.
• wait(): it Releases the lock and suspends the current thread until another thread calls notify()
or notifyAll() on the same object.
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).
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).
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.
// Add elements
[Link]("Java");
[Link]("Python");
[Link](1, "C++"); // insert at index 1
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.
// 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);
}
}
1. import [Link];
2. import [Link];
// 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];
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];
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];
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];
[Link]("Banana");
[Link]("Apple");
[Link]("Mango");
[Link]("Apple"); // duplicate, ignored
[Link](null); // allowed once
TreeSet:
TreeSet Program:
import [Link];
import [Link];
[Link]("Banana");
[Link]("Apple");
[Link]("Mango");
[Link]("Apple"); // duplicate, ignored
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.
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.
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”).
Sample program:
import [Link];
Output: It will the present live date and time with the format (Day Year Time [Link])
Sample program:
import [Link];
Output:
Date: It shows Current date format (DD-MM-YYYY)
Time: It will show current time format (Hr:Min:Sec)
// 25 December 2025
[Link]([Link], 2025);
[Link]([Link], [Link]); // or 11
[Link](Calendar.DAY_OF_MONTH, 25);
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.
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.
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.
InputStream
├── FileInputStream // Read from file
├── BufferedInputStream // Buffered reading
├── DataInputStream // Read primitives (int, double)
└── ObjectInputStream // Read serialized objects
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
import [Link].*;
import [Link].*;
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.
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.,)
Benefits:
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.
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.
3. Event Listener: Object implementing a listener interface eg. ActionListener with handler
methods like ‘actionPerformed(ActionEvent e).
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.
Checkbox, Choice,
ItemEvent Checkbox/choice/list selection changes
List
Frame, Dialog,
WindowEvent Window state changes (open/close/iconify)
Window
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:
Button ActionEvent
Scrollbar AdjustmentEvent
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.
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.
Adapter classes solve this: extend the adapter, override only the methods you care about, and the
rest stay empty.
mouseClicked(), mousePressed(),
Mouse button actions,
MouseListener mouseReleased(), mouseEntered(),
hover in/out.
mouseExited()
Keyboard Events
Interface: KeyListener with 3 methods.
Method Trigger
--------------------------------THE END------------------------------
THANK YOU