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

Java Unit Notes

This document provides comprehensive exam-oriented notes on Java programming, specifically focusing on classes, objects, and inheritance. It covers key concepts such as control statements, methods, constructors, access control, and inheritance basics, along with examples and syntax. The notes are structured in a way that facilitates understanding and retention for exam preparation.

Uploaded by

Avdhesh Dadhich
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 views19 pages

Java Unit Notes

This document provides comprehensive exam-oriented notes on Java programming, specifically focusing on classes, objects, and inheritance. It covers key concepts such as control statements, methods, constructors, access control, and inheritance basics, along with examples and syntax. The notes are structured in a way that facilitates understanding and retention for exam preparation.

Uploaded by

Avdhesh Dadhich
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

JAVA PROGRAMMING

Classes, Objects & Inheritance

Complete Exam-Oriented Notes | Unit II

TABLE OF CONTENTS
# Topic Key Concepts

1 Control Statements if, switch, while, do-while, for, break, continue, return

2 Methods & Constructors constructors, this, finalize, overloading, recursion

3 Objects as Parameters pass by value, returning objects, stack class

4 Access Control & Modifiers public/private/protected, static, final

5 Nested & Inner Classes static nested, inner, anonymous, local

6 Command Line Arguments args[], parsing, usage

7 Inheritance Basics extends, super, method overriding, polymorphism

8 Abstract & Final abstract class/method, final with inheritance

9 Dynamic Method Dispatch runtime polymorphism, upcasting

Java Programming | Classes, Objects & Inheritance Page 1


1 CONTROL STATEMENTS

DEFINITION
Formal: Control statements in Java are programming constructs that alter the sequential flow of execution.
They determine the order in which instructions are executed based on conditions, repetitions, or jumps to
other parts of the code.

Simple: By default, Java runs code line by line. Control statements let you say 'run this block ONLY IF…',
'repeat this block WHILE…', or 'skip to here'. Without them, programs cannot make decisions.

Why they exist: Real programs must respond to different inputs and repeat tasks. Control statements make
programs intelligent and dynamic.

1.1 Selection Statements – if / if-else / if-else-if


The if statement evaluates a boolean expression. If true, the block executes; if false, it is skipped. The else clause
handles the false branch. The else-if ladder chains multiple conditions.

Syntax Forms:

if (condition) { ... } | if (condition) { ... } else { ... } | if (c1) { } else if (c2) { } else { }

// if-else-if example

// Example: Grade Calculator using if-else-if ladder

int marks = 78;

String grade;

if (marks >= 90) {

grade = "A+";

} else if (marks >= 75) {

grade = "A";

} else if (marks >= 60) {

grade = "B";

} else {

grade = "C";

[Link]("Grade: " + grade);

OUTPUT:

Grade: A

1.2 Switch Statement


The switch statement is a multi-way branch. It compares one variable against multiple case values and jumps to
the matching case. The break keyword prevents fall-through (executing the next case automatically). default runs
when no case matches — it's like the final else.

Java Programming | Classes, Objects & Inheritance Page 2


■ EXAM TRAP: Forgetting break causes fall-through — all subsequent cases execute. This is a very
common MCQ/code-trace question.

■ switch works with: int, char, byte, short, String (Java 7+), and enum.

// switch statement

int day = 3;

switch (day) {

case 1: [Link]("Monday"); break;

case 2: [Link]("Tuesday"); break;

case 3: [Link]("Wednesday"); break;

default: [Link]("Other day");

OUTPUT:

Wednesday

1.3 Iteration Statements – while, do-while, for


while loop: Checks the condition BEFORE executing the body. If the condition is false at the start, the body never
executes (zero or more iterations).

do-while loop: Executes the body FIRST, then checks the condition. The body always runs at least once (one or
more iterations). Use when you need at least one execution — e.g., menu-driven programs.

for loop: Best when the number of iterations is known. It combines initialization, condition, and update in one line.

■ Memory Trick: while = 'while condition holds'; do-while = 'do it, THEN check'; for = 'for a fixed count'

// Loop Comparisons

// while loop — sum 1 to 5

int i = 1, sum = 0;

while (i <= 5) { sum += i; i++; }

[Link]("Sum = " + sum); // 15

// do-while — runs at least once

int x = 10;

do {

[Link]("x = " + x); // prints even though x>5

} while (x < 5);

// for loop — print even numbers

for (int j = 2; j <= 10; j += 2)

[Link](j + " ");

OUTPUT:

Sum = 15

x = 10

Java Programming | Classes, Objects & Inheritance Page 3


2 4 6 8 10

1.4 Nested Loops


A loop placed inside another loop is called a nested loop. The inner loop completes ALL its iterations for EACH
iteration of the outer loop. Commonly used for patterns, matrices, and 2D arrays.

// Nested Loop Pattern

// Print a 3x3 star pattern

for (int r = 1; r <= 3; r++) {

for (int c = 1; c <= 3; c++)

[Link]("* ");

[Link]();

OUTPUT:

* * *

* * *

* * *

1.5 Jump Statements – break, continue, return


Statement What it does Use case

break Exits the current loop or switch immediately Stop loop early when target found

continue Skips the rest of current iteration, goes to next Skip odd numbers, skip errors

return Exits the current method, optionally returning a value Return result from a function

■ EXAM Q: Differentiate break vs continue with examples. | What is labeled break?

■ EXAM Q: Trace output of a nested loop with break/continue.

Java Programming | Classes, Objects & Inheritance Page 4


2 METHODS, CONSTRUCTORS & RELATED CONCEPTS

DEFINITION
Method (Formal): A method in Java is a named block of code that performs a specific task. It is defined inside
a class and can be called (invoked) whenever that task needs to be done. Methods promote code reusability
and modular design.

Constructor (Formal): A constructor is a special method that is automatically called when an object is
created using the new keyword. It initializes the object's fields. A constructor has the same name as the class
and no return type — not even void.

2.1 Constructors
Constructors set up an object's initial state. There are three types:

• Default Constructor: Provided by Java automatically if you don't write any constructor. Sets all fields to default
values (0, null, false).
• No-arg Constructor: Written by programmer, takes no parameters. Can set custom initial values.
• Parameterized Constructor: Takes arguments. Used to create objects with specific initial values.

// Constructor Example

class Student {

String name;

int roll;

// No-arg constructor

Student() {

name = "Unknown";

roll = 0;

// Parameterized constructor

Student(String n, int r) {

name = n;

roll = r;

void display() {

[Link](roll + " " + name);

class Main {

public static void main(String[] args) {

Student s1 = new Student();

Java Programming | Classes, Objects & Inheritance Page 5


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

[Link]();

[Link]();

OUTPUT:

0 Unknown

101 Alice

2.2 The 'this' Keyword


The keyword this refers to the current object — the object whose method or constructor is being executed. It
solves the problem of ambiguity when instance variables and parameters have the same name.

• [Link] — Distinguishes instance variable from local/parameter variable.


• this() — Calls another constructor of the same class (constructor chaining). Must be the FIRST statement.
• return this — Returns current object (used in method chaining).

// this keyword

class Box {

int width, height;

Box(int width, int height) {

[Link] = width; // [Link] = instance var

[Link] = height; // height = parameter

Box() {

this(10, 20); // Calls parameterized constructor

■ EXAM TRAP: this() must be the FIRST statement in a constructor. Placing it elsewhere is a compile
error.

■ EXAM Q: What is the purpose of 'this' keyword? Explain with example.

2.3 Method Overloading


Method overloading means defining multiple methods with the same name but different parameter lists within
the same class. Java determines which version to call based on the number, type, or order of arguments at
compile time — this is called compile-time polymorphism or static binding.

Methods can be overloaded by: (1) different number of parameters, (2) different data types of parameters,
(3) different order of parameters.

■ Return type alone is NOT sufficient for overloading — it causes a compile error.

// Method Overloading

Java Programming | Classes, Objects & Inheritance Page 6


class Calculator {

// Overloaded add methods

int add(int a, int b) { return a + b; }

double add(double a, double b) { return a + b; }

int add(int a, int b, int c) { return a + b + c; }

public static void main(String[] args) {

Calculator c = new Calculator();

[Link]([Link](5, 3)); // 8

[Link]([Link](2.5, 1.5)); // 4.0

[Link]([Link](1, 2, 3)); // 6

OUTPUT:

4.0

2.4 Stack Class Example – Overloading in Action


A Stack is a data structure that follows LIFO (Last In, First Out). The example below demonstrates how to build a
simple fixed-size stack and overload its push method for different types.

// Stack Class

class Stack {

int[] data;

int top;

Stack(int size) { data = new int[size]; top = -1; }

void push(int val) { // push integer

if (top == [Link] - 1) [Link]("Stack Full");

else data[++top] = val;

int pop() { // pop returns top element

if (top == -1) { [Link]("Empty"); return -1; }

return data[top--];

2.5 Objects as Parameters and Returning Objects


In Java, when you pass an object to a method, you pass a copy of the reference (not the actual object). This
means the method can modify the object's fields through the reference, but cannot make the original reference

Java Programming | Classes, Objects & Inheritance Page 7


point to a different object. This is sometimes called pass by value of the reference.

// Objects as Parameters

class Point {

int x, y;

Point(int x, int y) { this.x=x; this.y=y; }

// Returns a new object (midpoint)

Point midpoint(Point other) {

return new Point((x+other.x)/2, (y+other.y)/2);

Point p1 = new Point(2,4), p2 = new Point(6,8);

Point mid = [Link](p2);

[Link](mid.x + "," + mid.y); // 4,6

OUTPUT:

4,6

2.6 Recursion
Recursion is a technique where a method calls itself to solve a problem. Every recursive solution needs: (1) a
base case that stops recursion, and (2) a recursive case that moves toward the base case.

■ Think of it as: Solving a big problem by breaking it into a SMALLER version of the SAME problem.

■ Without a base case: StackOverflowError (infinite recursion).

// Recursion – Factorial

// Factorial: n! = n × (n-1)!, base: 0! = 1

int factorial(int n) {

if (n == 0) return 1; // base case

return n * factorial(n - 1); // recursive case

[Link](factorial(5)); // 120

OUTPUT:

120

Call chain: factorial(5)→5×factorial(4)→5×4×factorial(3)→…→5×4×3×2×1=120

2.7 finalize() Method


The finalize() method is called by the Garbage Collector just before an object is destroyed. It is used to perform
cleanup operations — like releasing resources. It is defined in the Object class and can be overridden.

■ finalize() is deprecated since Java 9 and removed in Java 18. Examiners still ask about it for older
syllabus. In real projects, use try-with-resources instead.

■ EXAM Q: What is the role of finalize()? Who calls it?

Java Programming | Classes, Objects & Inheritance Page 8


3 ACCESS CONTROL, STATIC & FINAL

DEFINITION
Access Control: Access modifiers control the visibility (accessibility) of class members (fields, methods,
constructors) from other classes or packages. They enforce encapsulation — a core OOP principle.

static: The static keyword means a member belongs to the CLASS itself, not to any specific object. It exists
even before any object is created.

final: The final keyword prevents modification — a final variable cannot be reassigned, a final method cannot
be overridden, a final class cannot be subclassed.

3.1 Access Modifiers


Modifier Same Class Same Package Subclass Everywhere

private ■ ■ ■ ■

default ■ ■ ■ ■

protected ■ ■ ■ ■

public ■ ■ ■ ■

■ Memory Trick: Private = Personal diary (only you). Default = Office notice board (same floor). Protected
= Family secret (kids can know). Public = Newspaper ad (everyone).

■ EXAM Q: Explain all access modifiers with visibility table.

3.2 static Keyword


Members declared static belong to the class, not instances. There is only ONE copy of a static variable shared
across ALL objects. Static methods can be called without creating an object.

• Static variable: Shared across all instances. E.g., a counter counting how many objects were created.
• Static method: Can only access static data directly. Cannot use 'this'.
• Static block: Runs once when the class is first loaded. Used for static initialization.

// static example

class Counter {

static int count = 0; // shared across all objects

Counter() { count++; }

static void showCount() { [Link]("Count: " + count); }

new Counter(); new Counter(); new Counter();

[Link](); // No object needed

OUTPUT:

Count: 3

Java Programming | Classes, Objects & Inheritance Page 9


3.3 final Keyword
• final variable: Becomes a constant. Must be initialized at declaration or in constructor. Cannot be changed later.
Naming convention: ALL_CAPS.
• final method: Cannot be overridden in subclasses. Used to prevent subclasses from changing critical behavior.
• final class: Cannot be extended (subclassed). Example: [Link] is a final class.

// final keyword

final class MathConstants {

static final double PI = 3.14159; // constant

final void show() { [Link]("PI = " + PI); }

// class SubMath extends MathConstants {} // ERROR! Can't extend final

■ EXAM Q: Write the differences between final variable, final method, and final class.

■ EXAM Q: Can a final method be overloaded? (YES — overloading ≠ overriding)

Java Programming | Classes, Objects & Inheritance Page 10


4 NESTED AND INNER CLASSES

DEFINITION
Formal: A nested class is a class defined within another class. The enclosing class is called the outer class.
Nested classes logically group classes that are only used in one place, increase encapsulation, and can lead
to more readable and maintainable code.

Types: (1) Static Nested Class, (2) Non-static Inner Class, (3) Local Inner Class, (4) Anonymous Inner Class

Type Where Defined Can Access Outer? Use Case

Static Nested Inside class, static Only static members Helper class, no outer instance needed

Inner Class Inside class, non-static All outer members Linked list node, iterator

Local Class Inside a method Local final variables Rarely used, limited scope

Anonymous Inline expression Outer members GUI handlers, Runnable

// Nested & Inner Classes

class Outer {

int outerVal = 10;

// Non-static inner class

class Inner {

void show() {

[Link]("Outer val: " + outerVal); // direct access

// Static nested class

static class StaticNested {

void hello() { [Link]("Static nested"); }

// Creating inner class object requires outer object:

Outer o = new Outer();

[Link] i = [Link] Inner();

[Link]();

// Static nested class — no outer object needed:

[Link] sn = new [Link]();

[Link]();

OUTPUT:

Java Programming | Classes, Objects & Inheritance Page 11


Outer val: 10

Static nested

■ EXAM Q: How to create an object of an inner class? | Difference between static nested and inner class.

■ EXAM Q: What is an anonymous inner class? Give example with Runnable.

Java Programming | Classes, Objects & Inheritance Page 12


5 COMMAND LINE ARGUMENTS

DEFINITION
Formal: Command line arguments are values passed to the main method of a Java program at runtime,
through the terminal/command prompt. They are received as a String array — the parameter String[] args —
where each element corresponds to one space-separated word typed after the program name.

Why: Allows the program to behave differently based on external input without recompiling. Used in tools,
utilities, and scripts.

// Command Line Arguments

class CmdDemo {

public static void main(String[] args) {

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

for (String arg : args)

[Link](arg);

// Numeric parsing: [Link](args[0])

if ([Link] > 0) {

int n = [Link](args[0]);

[Link]("Square: " + n*n);

// Run: java CmdDemo 5 Hello World

OUTPUT:

Arguments: 3

Hello

World

Square: 25

■ args[0] is the FIRST argument (NOT the program name, unlike C/C++). Program name is NOT part of
args.

■ All args are Strings. To use as numbers, parse them: [Link](), [Link](), etc.

■ EXAM Q: Write a program that adds two numbers passed as command line arguments.

Java Programming | Classes, Objects & Inheritance Page 13


6 INHERITANCE

DEFINITION
Formal: Inheritance is a fundamental mechanism of Object-Oriented Programming that allows a new class
(called the subclass, child class, or derived class) to acquire the properties and behaviors (fields and
methods) of an existing class (called the superclass, parent class, or base class). It promotes code reuse and
establishes an IS-A relationship between classes.

Simple: A Car IS-A Vehicle. A Dog IS-A Animal. The child class gets everything the parent has, PLUS it can
add new things or change existing things.

Keyword: extends. Java supports only single inheritance (one parent), but multilevel inheritance is allowed.

6.1 Types of Inheritance in Java


Type Description Supported?

Single One class inherits from one parent ■ Yes

Multilevel Chain: A → B → C ■ Yes

Hierarchical Multiple classes from one parent ■ Yes

Multiple One class inherits from two parents ■ Not via classes (use interfaces)

Hybrid Mix of above ■ Partial (via interfaces)

6.2 Basic Inheritance with extends


// Basic Inheritance

class Animal { // Parent / Superclass

String name;

void eat() { [Link](name + " eats"); }

class Dog extends Animal { // Child / Subclass

void bark() { [Link](name + " barks"); }

Dog d = new Dog();

[Link] = "Rex";

[Link](); // inherited from Animal

[Link](); // Dog's own method

OUTPUT:

Rex eats

Rex barks

Java Programming | Classes, Objects & Inheritance Page 14


6.3 The super Keyword
The keyword super is used in a subclass to refer to its immediate parent class. It has two main uses:

• [Link]() — Calls a method from the parent class. Used when the method is overridden in the child.
• super() — Calls the parent class constructor. MUST be the first statement in the child's constructor. If not written
explicitly, Java inserts super() automatically.

// super keyword

class Vehicle {

String brand;

Vehicle(String b) { brand = b; }

void info() { [Link]("Brand: " + brand); }

class Car extends Vehicle {

int speed;

Car(String b, int s) {

super(b); // calls Vehicle(b)

speed = s;

void info() {

[Link](); // calls Vehicle's info()

[Link]("Speed: " + speed);

new Car("Toyota", 180).info();

OUTPUT:

Brand: Toyota

Speed: 180

6.4 Method Overriding


Method overriding occurs when a subclass provides its OWN implementation of a method that is already defined in
the parent class. The method name, return type, and parameters must be IDENTICAL. The @Override annotation
(optional but recommended) helps the compiler verify the override.

Feature Overloading Overriding

Where Same class Different classes (parent-child)

Signature Must differ Must be same

Binding Compile-time Runtime

Polymorphism Static/Compile Dynamic/Runtime

Return type Can differ Must be same (or covariant)

Java Programming | Classes, Objects & Inheritance Page 15


■ You CANNOT override: static methods, final methods, or private methods. Static methods are HIDDEN,
not overridden.

■ EXAM Q: Difference between method overloading and method overriding — a VERY common exam
question!

6.5 Dynamic Method Dispatch (Runtime Polymorphism)


Dynamic Method Dispatch is the mechanism by which a call to an overridden method is resolved at runtime rather
than compile time. This is the foundation of runtime polymorphism. When a superclass reference holds a
subclass object, and an overridden method is called, Java executes the SUBCLASS version.

■ Key Rule: The reference type determines what methods are ACCESSIBLE. The object type determines
which overridden version is CALLED.

// Dynamic Method Dispatch

class Shape {

void draw() { [Link]("Drawing Shape"); }

class Circle extends Shape {

void draw() { [Link]("Drawing Circle"); }

class Square extends Shape {

void draw() { [Link]("Drawing Square"); }

// Dynamic Method Dispatch:

Shape s; // superclass reference

s = new Circle(); [Link](); // Circle's draw() called

s = new Square(); [Link](); // Square's draw() called

s = new Shape(); [Link](); // Shape's draw() called

OUTPUT:

Drawing Circle

Drawing Square

Drawing Shape

■ EXAM Q: What is dynamic method dispatch? How does it achieve runtime polymorphism?

■ EXAM Q: Trace the output of a dispatch example — very common in paper!

Java Programming | Classes, Objects & Inheritance Page 16


7 ABSTRACT CLASSES AND FINAL WITH INHERITANCE

DEFINITION
Abstract Class (Formal): An abstract class in Java is a class declared with the abstract keyword that cannot
be instantiated directly. It may contain abstract methods (methods without a body/implementation) that MUST
be overridden by its concrete subclasses, as well as regular (concrete) methods. It acts as a blueprint or
template for its subclasses.

Abstract Method: A method declared with abstract keyword, having no body. It defines only the signature —
'what to do', not 'how to do'. The subclass MUST provide the implementation.

Why: When you want to enforce that all subclasses implement certain behaviors, but you don't know the
implementation details at the parent level. E.g., all Shapes have area, but the formula differs.

// Abstract Class Full Example

abstract class Shape {

String color;

// Abstract method — no body, subclass MUST implement

abstract double area();

// Concrete method — normal, inherited

void displayColor() { [Link]("Color: " + color); }

class Circle extends Shape {

double radius;

Circle(double r) { radius = r; color = "Red"; }

double area() { return 3.14 * radius * radius; } // MUST override

class Rectangle extends Shape {

double l, w;

Rectangle(double l, double w) { this.l=l; this.w=w; color="Blue"; }

double area() { return l * w; }

Shape s1 = new Circle(5);

Shape s2 = new Rectangle(4,6);

[Link]([Link]()); // 78.5

[Link]([Link]()); // 24.0

[Link](); // Color: Red

OUTPUT:

Java Programming | Classes, Objects & Inheritance Page 17


78.5

24.0

Color: Red

7.1 Abstract Class vs Interface


Feature Abstract Class Interface

Methods Can have abstract + concrete All abstract (Java 7), default/static (Java 8+)

Variables Any type public static final only

Constructor Yes No

Inheritance Single (extends) Multiple (implements)

Speed Faster Slightly slower

Use when Partial implementation needed Pure contract, multiple inheritance

7.2 final with Inheritance


• final class: Cannot be extended. String, Integer, Math are all final in Java. Used for security and immutability.
• final method: Can be inherited but CANNOT be overridden. The parent's implementation is locked.
• Effect on polymorphism: final breaks runtime polymorphism for that specific method — no dynamic dispatch
occurs.

■ EXAM Q: Can an abstract class have a constructor? (YES — it is called via super())

■ EXAM Q: Can a class be both abstract and final? (NO — abstract needs subclassing; final prevents it)

■ EXAM Q: Can abstract class have non-abstract methods? (YES — both are allowed)

■ EXAM Q: Explain abstract class with a real-world example and code.

Java Programming | Classes, Objects & Inheritance Page 18


✦ QUICK REVISION CHEAT SHEET

Concept One-liner Summary Key Keyword

if-else Conditional execution if, else, else if

switch Multi-way branch; break stops fall-through switch, case, break, default

while Zero-or-more iterations; condition first while

do-while One-or-more iterations; condition last do...while

for Fixed-count loop with init/cond/update for

break Exit current loop/switch break

continue Skip current iteration continue

Constructor Same name as class, no return type, initializes object new

this Refers to current object; chains constructors this, this()

finalize() Called before GC destroys object; deprecated Java 9+ finalize

Overloading Same name, different parameters, compile-time same class

Recursion Method calls itself; needs base case base case

private Only accessible within same class private

static Belongs to class, not instance; one copy static

final No reassign / no override / no extend final

Inner class Class inside class; accesses outer members new Outer().new Inner()

static nested Class inside class but static; no outer instance new [Link]()

extends Inherit parent's members; IS-A relationship extends, super

super Reference to parent class constructor/method super(), [Link]()

Overriding Same signature in child class; runtime binding @Override

Dispatch Runtime polymorphism via parent reference Shape s = new Circle()

abstract Cannot instantiate; subclass must implement methods abstract

final class Cannot be subclassed String is final

END OF NOTES — Good Luck on Your Exam! ■

Java Programming | Classes, Objects & Inheritance Page 19

You might also like