Java Unit–2 and Unit–3 Detailed University Notes
These notes cover all topics visible in your syllabus image. The explanation style is kept suitable for long
10-mark answers, with simple language, proper definitions, syntax, key points and easy examples for every
topic.
UNIT–2: Introduction to Classes
1. Class Fundamentals
Definition: A class in Java is a user-defined blueprint or template used to create objects. It contains data
members (variables) and member functions (methods). A class helps in combining data and behavior in
one unit. Need of Class: 1. To represent real-world entities such as Student, Car, Book etc. 2. To support
object oriented programming. 3. To improve code organization and reusability. General Syntax:
class ClassName {
// variables
// methods
} Important points: 1. A class does not occupy memory until its object is created. 2. Variables declared
inside a class are called instance variables. 3. Functions declared inside a class are called methods. Easy
Example: A Student class can store name and roll number and can also display them. Conclusion: Class is
the foundation of Java programming because every Java program is built using classes and objects.
2. Declaring a Class
Definition: Declaring a class means defining its name, variables and methods. Syntax:
class Student {
String name;
int roll;
void display() {
[Link](name + " " + roll);
}
} Explanation: - Student is the class name. - name and roll are data members. - display() is a member
method. Points for 10 marks: 1. Class name should begin with a capital letter by convention. 2. A class can
contain variables, constructors, methods and nested classes. 3. A class can be public or default. Use: Used
to define the structure and behavior of objects.
3. Creating Objects
Definition: An object is an instance of a class. It is a real memory-based entity created from the blueprint of
the class. Syntax:
ClassName objectName = new ClassName(); Example:
Student s1 = new Student(); Explanation: - Student is the class name. - s1 is the object reference. - new
allocates memory for the object. Why objects are needed: 1. To access class variables and methods. 2. To
represent different values for the same class. 3. To store real-world data separately. Example in words: If
class is Student, then Rahul and Priya are two different objects of the same class. Conclusion: Object is the
actual working entity in Java.
4. Introducing Methods and Method Declaration
Definition: A method is a block of code that performs a specific task. It is used to improve readability,
reusability and modularity of the program. General Syntax:
returnType methodName(parameterList) {
// body
} Example: int add(int a, int b) { return a + b; } Parts of Method Declaration: 1. Access modifier – public,
private etc. 2. Return type – int, void, String etc. 3. Method name – meaningful name 4. Parameters – input
values 5. Method body – actual logic Advantages: 1. Reusability 2. Better testing 3. Easy debugging 4.
Reduces repetition Conclusion: Methods divide a program into smaller manageable units.
5. Method Overloading
Definition: Method overloading means defining multiple methods with the same name but with different
parameter lists in the same class. Conditions for overloading: 1. Same method name 2. Different number
or type of parameters 3. Return type alone cannot overload a method Example: int sum(int a, int b) double
sum(double a, double b) int sum(int a, int b, int c) Advantages: 1. Improves readability 2. Same action can be
performed for different data types 3. Supports compile-time polymorphism Conclusion: Overloading provides
flexibility in method usage.
6. Using Objects as Parameters
Definition: In Java, an object can be passed as an argument to a method. This allows one object to interact
with another. Syntax: void show(Student s) { ... } Use: 1. To pass complete data together 2. To compare
objects 3. To update object values inside methods Example idea: A method can receive a Student object and
print its details. Important point: Java passes object references by value, not the actual object itself.
Conclusion: Passing objects as parameters increases flexibility and object interaction.
7. Recursion
Definition: Recursion is a process in which a method calls itself again and again until a stopping condition is
reached. Syntax: returnType methodName() { if(base condition) return value; else return
methodName(smaller problem); } Important terms: 1. Base case – stops recursion 2. Recursive case –
method calls itself Advantages: 1. Easy solution for mathematical problems 2. Useful in factorial, Fibonacci,
tree traversal etc. Disadvantage: Too much recursion can use more memory. Conclusion: Recursion is
powerful but must always include a stopping condition.
8. Constructors
Definition: A constructor is a special member of a class used to initialize objects. It has the same name as
the class and no return type. Features: 1. Called automatically when object is created 2. Used for initialization
3. Can be overloaded Types of Constructors: 1. Default constructor 2. Parameterized constructor Syntax:
class Student { Student() { } } Conclusion: Constructors are used to assign initial values to objects.
9. this Keyword
Definition: this is a reference variable that refers to the current object. Uses of this keyword: 1. To refer
current class instance variables 2. To call current class methods 3. To invoke current class constructor 4. To
pass current object as parameter Example: [Link] = name; Why needed: When local variable and
instance variable have same name, this removes confusion. Conclusion: this keyword helps identify the
current object clearly.
10. Garbage Collection
Definition: Garbage collection is the process of automatically destroying unused objects to free memory.
Why required: When objects are no longer referenced, they waste memory if not removed. Features: 1.
Automatic memory management 2. Reduces programmer burden 3. Prevents memory leakage to some
extent How it works: JVM finds unreachable objects and removes them. Ways to make object eligible: 1.
Assign null 2. Reassign reference 3. Anonymous object Conclusion: Garbage collection improves memory
efficiency in Java.
11. Finalization
Definition: Finalization is a process in which the finalize() method may be called by garbage collector before
destroying an object. Purpose: Used to perform cleanup activities like closing resources. Important note: In
modern Java, finalization is not preferred because it is unpredictable and outdated for practical use. Still, it is
often asked in exams. Syntax idea: protected void finalize() { // cleanup code } Conclusion: Finalization is an
old cleanup mechanism related to object destruction.
Easy Programs for Unit–2
// 1. Class, Object and Method
class Student {
String name;
int roll;
void display() {
[Link](name + " " + roll);
}
public static void main(String[] args) {
Student s1 = new Student();
[Link] = "Rahul";
[Link] = 101;
[Link]();
}
}
// 2. Method Overloading
class Demo {
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
}
// 3. Object as Parameter
class Test {
void show(Student s) {
[Link]([Link]);
}
}
// 4. Recursion - Factorial
class Rec {
int fact(int n) {
if(n == 1) return 1;
return n * fact(n - 1);
}
}
// 5. Constructor and this keyword
class Book {
String name;
Book(String name) {
[Link] = name;
}
}
UNIT–3: Inheritance, Interface, Package and Exception Handling
1. Inheritance Basics
Definition: Inheritance is the process by which one class acquires the properties and methods of another
class. Parent class / Superclass: Existing class
Child class / Subclass: Derived class Syntax:
class A { }
class B extends A { } Advantages: 1. Code reusability 2. Better organization 3. Easy maintenance 4.
Supports hierarchical classification Types in Java: 1. Single inheritance 2. Multilevel inheritance 3.
Hierarchical inheritance Conclusion: Inheritance is one of the most important OOP features in Java.
2. Using super Keyword
Definition: super refers to the immediate parent class object. Uses of super: 1. To access parent class
variable 2. To call parent class method 3. To call parent class constructor Example: [Link](); super(x);
Need: Used when child and parent members have same names. Conclusion: super is useful for reusing and
accessing parent class members.
3. final Keyword
Definition: final is used to restrict modification. Uses: 1. final variable – value cannot be changed 2. final
method – cannot be overridden 3. final class – cannot be inherited Examples: final int x = 10; final class
Demo { } Conclusion: final provides security and fixed behavior.
4. Method Overriding
Definition: Method overriding occurs when child class provides its own implementation of a method already
defined in parent class. Conditions: 1. Same method name 2. Same parameters 3. Parent-child relationship
Use: To change or specialize inherited behavior. Benefit: Supports runtime polymorphism. Conclusion:
Overriding is a very important OOP concept in Java.
5. Dynamic Method Dispatch
Definition: Dynamic method dispatch is the process by which a call to an overridden method is resolved at
runtime rather than compile time. Meaning: Parent reference can refer to child object. Syntax: A obj = new
B(); Importance: 1. Supports runtime polymorphism 2. Makes Java flexible and extensible Conclusion: It
helps Java decide which method version should run during execution.
6. Abstract Class
Definition: An abstract class is a class declared with the abstract keyword. It may contain abstract methods
and normal methods. Abstract method: A method without body. Syntax: abstract class Shape { abstract
void draw(); } Key points: 1. Object of abstract class cannot be created 2. Child class must implement
abstract methods 3. Used for partial abstraction Conclusion: Abstract class provides common design for
subclasses.
7. Interface
Definition: Interface is a blueprint of a class that contains abstract methods and constants. Syntax: interface
Demo { void show(); } Important points: 1. Methods are public and abstract by default 2. Variables are
public, static and final by default 3. A class uses implements keyword to use interface Conclusion: Interface
is used to achieve full abstraction and multiple inheritance of type.
8. Variables and Extending Interfaces
Interface Variables: Variables inside interface are automatically public static final. Example: interface Test
{ int x = 10; } Extending Interfaces: One interface can inherit another interface using extends. Syntax:
interface A { void show(); } interface B extends A { void print(); } Conclusion: Interfaces can be combined to
design flexible systems.
9. Package: Creating and Importing Packages
Definition: A package is a group of related classes and interfaces. Advantages: 1. Avoids name conflict 2.
Provides access protection 3. Organizes files Creating package: package mypack; Importing package:
import [Link]; or import mypack.*; Conclusion: Packages improve code management in Java.
10. Package Access Protection
Java provides access protection through access modifiers. Types: 1. private 2. default 3. protected 4. public
Use: Controls visibility of classes, methods and variables. Conclusion: Access protection improves data
security and modularity.
11. Exception Handling Fundamentals
Definition: Exception handling is a mechanism to handle runtime errors so that normal flow of program
continues. Exception: An unwanted event that interrupts normal program execution. Why needed: 1.
Prevents program crash 2. Makes program reliable 3. Helps in error reporting Conclusion: Exception
handling is essential for writing safe Java programs.
12. Exception Types
Main types: 1. Checked exceptions – checked at compile time (IOException, SQLException) 2. Unchecked
exceptions – occur at runtime (ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException) Errors vs Exceptions: Errors are serious system problems, exceptions
are program-related issues. Conclusion: Understanding exception types helps in proper error handling.
13. Uncaught Exceptions
If an exception is not handled, it is called an uncaught exception. Result: 1. Program terminates abnormally
2. JVM prints exception name, message and line number Example: int a = 10 / 0; Conclusion: Uncaught
exceptions should be avoided using proper handling.
14. try and catch
Definition: try contains risky code and catch handles the exception. Syntax: try { // risky code }
catch(ExceptionType e) { // handling code } Benefit: Program continues normally even after error.
Conclusion: try-catch is the most basic and important exception handling mechanism.
15. Multiple catch Clauses
A single try block can have multiple catch blocks to handle different exception types. Syntax: try { }
catch(ArithmeticException e) { } catch(ArrayIndexOutOfBoundsException e) { } Rule: Specific exceptions
should be written before general exceptions. Conclusion: Multiple catch blocks improve precise exception
handling.
16. Nested try Statements
A try block inside another try block is called nested try. Use: Helpful when different parts of program need
separate exception handling. Conclusion: Nested try gives more detailed and structured control over errors.
17. throw Keyword
Definition: throw is used to explicitly throw an exception. Syntax: throw new ArithmeticException("Error");
Use: 1. To create custom error conditions 2. To manually generate exceptions Conclusion: throw gives
programmer direct control over exceptions.
18. Java’s Built-in Exceptions
Common built-in exceptions: 1. ArithmeticException 2. NullPointerException 3.
ArrayIndexOutOfBoundsException 4. NumberFormatException 5. ClassNotFoundException 6. IOException
Importance: These are already provided by Java and commonly asked in exams. Conclusion: Built-in
exceptions help identify standard runtime and compile-time errors.
Easy Programs for Unit–3
// 1. Inheritance
class Animal {
void eat() {
[Link]("Animal eats");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}
}
// 2. super keyword
class A {
A() {
[Link]("Parent constructor");
}
}
class B extends A {
B() {
super();
[Link]("Child constructor");
}
}
// 3. Method Overriding and Dynamic Dispatch
class Parent {
void show() {
[Link]("Parent method");
}
}
class Child extends Parent {
void show() {
[Link]("Child method");
}
}
class Test {
public static void main(String[] args) {
Parent p = new Child();
[Link]();
}
}
// 4. Abstract Class
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
[Link]("Drawing circle");
}
}
// 5. Interface
interface Demo {
void display();
}
class Sample implements Demo {
public void display() {
[Link]("Interface method");
}
}
// 6. Exception Handling
class Ex1 {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
}
}
// 7. throw
class Ex2 {
public static void main(String[] args) {
throw new ArithmeticException("Manual exception");
}
}
These notes are written in easy language but with enough depth to be used directly in university long answers
of 10 marks. You can also convert these into handwritten-style answers for exam preparation.