BCA — Java Programming Unit II
BCA
Punjab Technical University
JAVA PROGRAMMING
Complete Notes — Unit II
Topic 1: Control Statements [CO1]
Topic 2: Classes and Objects [CO1]
Topic 3: Inheritance [CO1]
Covers: if-else, switch, loops, jump statements, OOP basics, classes/objects,
constructors, operator overloading, static members, garbage collection, and inheritance.
Page 1 of 19
BCA — Java Programming Unit II
Table of Contents
TOC \h \o "1-3"
Page 2 of 19
BCA — Java Programming Unit II
Topic 1: Control Statements [CO1]
Control statements are used to control the flow of execution of a Java program based on certain conditions
or repetitions. They are broadly classified into three categories: Decision-making statements, Looping
statements, and Jumping statements.
1.1 Decision Making Statements
Decision-making statements allow a program to execute different sets of statements based on whether a
given condition is true or false.
1.1.1 if Statement
if statement: Executes a block of code only if the given condition evaluates to true.
if (condition) {
// executes if condition is true
}
Example:
int age = 20;
if (age >= 18) {
[Link]("Eligible to vote");
}
1.1.2 if-else Statement
if-else statement: Executes one block if the condition is true, and another block if it is false.
if (condition) {
// executes if condition is true
} else {
// executes if condition is false
}
Example:
int num = 7;
if (num % 2 == 0) {
[Link]("Even");
} else {
[Link]("Odd");
}
1.1.3 Nested if Statement
Nested if: An if (or if-else) statement placed inside another if (or else) block. Used when multiple conditions
depend on each other.
int marks = 85;
if (marks >= 33) {
Page 3 of 19
BCA — Java Programming Unit II
if (marks >= 75) {
[Link]("Distinction");
} else {
[Link]("Pass");
}
} else {
[Link]("Fail");
}
1.1.4 else-if Ladder
else-if ladder: Used to test multiple conditions in sequence, executing the block of the first condition that
evaluates to true.
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else if (condition3) {
// block 3
} else {
// default block (none of the above true)
}
Example:
int marks = 72;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 50) {
[Link]("Grade C");
} else {
[Link]("Grade F");
}
1.1.5 switch Statement
switch statement: A multi-way branch statement that compares a single variable's value against multiple
case values, providing a cleaner alternative to a long else-if ladder.
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements if no case matches
}
Page 4 of 19
BCA — Java Programming Unit II
Example:
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}
// Output: Wednesday
Rules of switch Statement
• The expression can be of type byte, short, int, char, String, or an enum (since Java 7, String is allowed).
• The break statement is used to exit the switch block; without it, execution “falls through” to the next
case.
• The default case is optional and executes when no case matches; it can appear anywhere in the block.
• Duplicate case values are not allowed.
1.1.6 Conditional (Ternary) Operator
Ternary operator (? :): A shorthand for a simple if-else statement; it is the only operator in Java that takes
three operands.
variable = (condition) ? value_if_true : value_if_false;
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link](max); // 20
1.2 Looping Statements
Loops are used to execute a block of statements repeatedly as long as a given condition holds true, avoiding
repetitive code.
1.2.1 while Loop
while loop: An entry-controlled loop where the condition is checked before each iteration. If the condition is
false initially, the loop body never executes.
while (condition) {
// statements
}
Example:
int i = 1;
while (i <= 5) {
[Link](i);
i++;
Page 5 of 19
BCA — Java Programming Unit II
}
// Output: 1 2 3 4 5
1.2.2 do-while Loop
do-while loop: An exit-controlled loop where the condition is checked after the loop body executes.
Guarantees that the loop body runs at least once.
do {
// statements
} while (condition);
Example:
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
// Output: 1 2 3 4 5 (runs even if condition is initially false)
1.2.3 for Loop
for loop: A compact, entry-controlled loop ideal for situations where the number of iterations is known in
advance. It combines initialization, condition, and update in one line.
for (initialization; condition; update) {
// statements
}
Example:
for (int i = 1; i <= 5; i++) {
[Link](i);
}
// Output: 1 2 3 4 5
1.2.4 Nested Loops
Nested loop: A loop placed inside the body of another loop. The inner loop completes all its iterations for
each single iteration of the outer loop. Commonly used for patterns, matrices, and 2D data.
// Prints a right-angled triangle of stars
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}
/* Output:
*
* *
* * *
Page 6 of 19
BCA — Java Programming Unit II
* * * * */
Comparison of Loops
Loop Checking Minimum Executions
Condition checked before execution (entry- 0 times (if condition is false
while
controlled) initially)
Condition checked after execution (exit-
do-while At least 1 time
controlled)
Condition checked before execution (entry- 0 times (if condition is false
for
controlled) initially)
1.3 Jumping Statements
Jumping statements are used to transfer control unconditionally to another part of the program, altering the
normal flow of loops or switch blocks.
1.3.1 break Statement
break: Terminates the loop or switch statement immediately and transfers control to the statement
following it.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // loop terminates when i == 5
}
[Link](i);
}
// Output: 1 2 3 4
1.3.2 continue Statement
continue: Skips the current iteration of the loop and moves control directly to the next iteration (condition
check), without terminating the loop.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // skips printing 3, loop continues
}
[Link](i);
}
// Output: 1 2 4 5
Statement Effect
break Exits the loop/switch completely; control moves to the statement after the
Page 7 of 19
BCA — Java Programming Unit II
Statement Effect
loop.
Skips only the current iteration; control moves to the next iteration of the
continue
loop.
Page 8 of 19
BCA — Java Programming Unit II
Topic 2: Classes and Objects [CO1]
2.1 Basic Concepts of OOPs
Object-Oriented Programming System (OOPs) is a programming approach based on the concept of objects
that contain both data and behaviour. Java is built around the following core OOP principles:
Principle Description
A blueprint/template that defines the structure (fields) and behaviour
Class
(methods) of objects.
Object A runtime instance of a class having its own state and behaviour.
Wrapping data and methods together and restricting direct access to
Encapsulation
internal details using access modifiers.
Mechanism that allows one class to acquire properties and methods of
Inheritance
another class.
Ability of an entity to take multiple forms — via overloading and
Polymorphism
overriding.
Abstraction Hiding implementation details and exposing only essential features.
2.2 Classes and Objects
Class
Class: A user-defined blueprint/template from which objects are created. It defines fields (data members)
and methods (member functions) that describe the properties and behaviour shared by all its objects. A class
itself does not occupy memory until an object is created.
class Student {
// fields (data members)
String name;
int rollNo;
// method (member function)
void display() {
[Link](name + " - " + rollNo);
}
}
Object
Object: An instance of a class. It is created using the new keyword, which allocates memory for the object on
the heap. Each object has its own copy of instance variables.
public class Main {
Page 9 of 19
BCA — Java Programming Unit II
public static void main(String[] args) {
Student s1 = new Student(); // object creation
[Link] = "Raj";
[Link] = 101;
[Link](); // calling method using object
}
}
Note: An object has three key characteristics — State (values of its attributes), Behaviour (methods it can
perform), and Identity (a unique reference in memory).
2.3 Modifiers
Modifiers: Keywords added to classes, methods, and variables to define their accessibility (access modifiers)
or to specify special properties (non-access modifiers).
Access Modifiers
Modifier Same Class Accessibility
private Yes Accessible only within the same class.
default (no modifier) Yes Accessible within the same package only.
Accessible within the same package and by
protected Yes
subclasses in other packages.
public Yes Accessible from anywhere in the program.
Non-Access Modifiers
Modifier Purpose
Belongs to the class rather than any specific object; shared across all
static
instances.
Prevents modification — a final variable cannot be reassigned, a final
final
method cannot be overridden, and a final class cannot be inherited.
Used with classes/methods that must be implemented/extended by
abstract
subclasses; cannot be instantiated directly.
Restricts access to a method/block by only one thread at a time (used in
synchronized
multithreading).
2.4 Passing Arguments
Argument passing: Java passes all arguments to methods by value — a copy of the variable's value is passed,
not the original variable itself.
Page 10 of 19
BCA — Java Programming Unit II
Passing Primitive Types
Changes made to a primitive parameter inside a method do NOT affect the original variable, since only a
copy of the value is passed.
void modify(int x) {
x = x + 10;
}
int num = 5;
modify(num);
[Link](num); // 5 (unchanged)
Passing Objects (Reference Types)
When an object is passed, a copy of the reference (which still points to the same object in memory) is
passed. So changes made to the object's fields inside the method DO reflect in the original object.
class Box { int value = 5; }
void modify(Box b) {
[Link] = 50; // modifies the actual object's field
}
Box myBox = new Box();
modify(myBox);
[Link]([Link]); // 50 (changed)
Important: Java is strictly “pass by value” even for objects — what's passed by value is the reference
(memory address) itself, not the actual object.
2.5 Constructors
Constructor: A special method automatically invoked at the time of object creation, used to initialize the
object's state. A constructor has the same name as the class and no return type (not even void).
Types of Constructors
Type Description
Automatically provided by Java (if no constructor is defined) with no
Default Constructor
parameters; initializes fields to their default values.
No-arg Constructor Explicitly defined by the programmer with no parameters.
Accepts arguments to initialize fields with specific values at the time of
Parameterized Constructor
object creation.
class Student {
String name;
int rollNo;
Page 11 of 19
BCA — Java Programming Unit II
// Parameterized constructor
Student(String n, int r) {
name = n;
rollNo = r;
}
}
Student s1 = new Student("Raj", 101); // constructor called
automatically
Note: If a class has any user-defined constructor, Java does NOT provide the default constructor
automatically.
2.6 Overloaded Constructors
Constructor Overloading: Defining multiple constructors in the same class with different parameter lists
(different number or types of parameters). This allows objects to be created in different ways.
class Student {
String name;
int rollNo;
Student() { // no-arg constructor
name = "Unknown";
rollNo = 0;
}
Student(String n) { // one-argument constructor
name = n;
rollNo = 0;
}
Student(String n, int r) { // two-argument constructor
name = n;
rollNo = r;
}
}
Student s1 = new Student();
Student s2 = new Student("Amit");
Student s3 = new Student("Raj", 101);
this() keyword: Used inside one constructor to call another constructor of the same class, helping reduce
code duplication.
2.7 Overloaded Operators
Important: Unlike C++, Java does NOT support true operator overloading (programmers cannot redefine
operators like +, -, * for custom classes).
However, Java provides a few cases of built-in (compiler-level) operator overloading:
Page 12 of 19
BCA — Java Programming Unit II
• + operator: Overloaded to perform both numeric addition (5 + 3 = 8) and string concatenation ("Hi" +
"There" = "HiThere"), depending on operand types.
int a = 5 + 3; // 8 -> arithmetic addition
String s = "Hello" + "World"; // "HelloWorld" -> string concatenation
String mix = "Total: " + 10; // "Total: 10" -> int auto-converted to
String
Achieving similar behaviour in Java: Custom classes can simulate operator-like behaviour by defining
methods (such as add(), equals(), or using overloaded methods), but the actual operator symbols cannot be
redefined by the programmer.
2.8 Static Class Members
static keyword: Used to create members (variables, methods, blocks, nested classes) that belong to the class
itself, rather than to any individual object. Static members are shared across all instances of the class.
Static Variables
A single copy of a static variable is created and shared by all objects of the class. Useful for properties
common to all instances, like a counter.
class Counter {
static int count = 0; // static variable
Counter() {
count++; // shared across all objects
}
}
new Counter(); new Counter(); new Counter();
[Link]([Link]); // 3
Static Methods
Can be called directly using the class name, without creating an object. Static methods can access only static
data and cannot use the 'this' keyword.
class MathUtil {
static int square(int n) {
return n * n;
}
}
int result = [Link](5); // called without object: 25
Static Block
A block of code marked with the static keyword that executes only once, when the class is first loaded into
memory — typically used to initialize static variables.
class Config {
Page 13 of 19
BCA — Java Programming Unit II
static int version;
static {
version = 1; // executes once, at class loading time
[Link]("Static block executed");
}
}
2.9 Garbage Collection
Garbage Collection (GC): An automatic memory management process in Java (performed by the JVM) that
reclaims memory occupied by objects that are no longer reachable/referenced by any part of the program.
This prevents memory leaks and frees programmers from manual memory management.
How an Object Becomes Eligible for GC
• When a reference variable is reassigned to another object or set to null.
• When an object is created inside a method and the method finishes execution (local scope ends).
• When an object is only referenced by other objects that are themselves unreachable (island of
isolation).
Key Concepts
Term Description
A method that the JVM may call on an object just before it is garbage
finalize() method collected, allowing cleanup actions (deprecated since Java 9 in favour of
other mechanisms).
A request (not a guarantee) made to the JVM to run the garbage
[Link]()
collector.
An object with no live references pointing to it — eligible for garbage
Unreachable Object
collection.
Student s1 = new Student();
s1 = null; // object is now unreachable -> eligible for GC
[Link](); // requests JVM to run garbage collector
Advantage: Automatic garbage collection makes Java memory-safe and reduces the risk of memory leaks
and dangling pointers common in languages like C/C++.
Page 14 of 19
BCA — Java Programming Unit II
Topic 3: Inheritance [CO1]
3.1 Basics of Inheritance
Inheritance: An OOP mechanism in which one class (subclass/child class) acquires the fields and methods of
another class (superclass/parent class), promoting code reusability. In Java, inheritance is implemented using
the extends keyword.
class Animal { // superclass / parent class
void eat() {
[Link]("This animal eats food");
}
}
class Dog extends Animal { // subclass / child class
void bark() {
[Link]("Dog barks");
}
}
Dog d = new Dog();
[Link](); // inherited from Animal
[Link](); // defined in Dog
Types of Inheritance in Java
Type Description
Single Inheritance One subclass inherits from one superclass.
A class inherits from a class, which itself inherits from another class
Multilevel Inheritance
(chain: A → B → C).
Hierarchical Inheritance Multiple subclasses inherit from a single superclass.
Multiple Inheritance (of NOT supported directly in Java (to avoid ambiguity, e.g., the
classes) Diamond Problem) — achieved instead through interfaces.
3.2 Inheriting and Overriding Superclass Methods
A subclass automatically inherits all non-private fields and methods of its superclass. It can also redefine
(override) a method to provide its own specific implementation.
Method Overriding
Method Overriding: When a subclass provides its own implementation of a method that is already defined
in its superclass, using the same method name, return type, and parameters.
class Animal {
void sound() {
Page 15 of 19
BCA — Java Programming Unit II
[Link]("Animal makes a sound");
}
}
class Cat extends Animal {
@Override
void sound() { // overriding superclass method
[Link]("Cat meows");
}
}
Animal a = new Cat();
[Link](); // Output: Cat meows (runtime polymorphism)
Rules of Method Overriding
• Method name, return type, and parameter list must be the same as in the superclass.
• Access modifier in the subclass cannot be more restrictive than in the superclass.
• The @Override annotation is optional but recommended (helps the compiler catch errors).
• Static, final, and private methods cannot be overridden.
super Keyword
super: A reference used inside a subclass to access the superclass's members (fields, methods) or
constructor, especially useful when a method has been overridden.
class Cat extends Animal {
void sound() {
[Link](); // calls Animal's version first
[Link]("Cat meows");
}
}
3.3 Calling Superclass Constructor
super() call: Used to explicitly call the constructor of the immediate superclass from within a subclass
constructor. It must be the first statement in the subclass constructor.
class Animal {
String type;
Animal(String t) {
type = t;
[Link]("Animal constructor called");
}
}
class Dog extends Animal {
String breed;
Dog(String t, String b) {
super(t); // calls Animal's constructor; must be
Page 16 of 19
BCA — Java Programming Unit II
first line
breed = b;
[Link]("Dog constructor called");
}
}
Dog d = new Dog("Mammal", "Labrador");
// Output:
// Animal constructor called
// Dog constructor called
Note: If a subclass constructor does not explicitly call super(), Java automatically inserts a call to the
superclass's no-argument constructor as the first statement.
3.4 Polymorphism
Polymorphism: The ability of an object, method, or reference to take on multiple forms. The term comes
from Greek, meaning “many forms.” Java supports two types of polymorphism:
Type Description
Achieved through Method Overloading — multiple methods with
Compile-time Polymorphism
the same name but different parameter lists within the same
(Static binding)
class. Resolved by the compiler.
Achieved through Method Overriding — a subclass redefines a
Run-time Polymorphism
superclass method; the actual method called is determined at run
(Dynamic binding)
time based on the object's actual type.
Example: Method Overloading (Compile-time)
class Calculator {
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; }
}
Calculator c = new Calculator();
[Link]([Link](2, 3)); // calls int version -> 5
[Link]([Link](2.5, 3.5)); // calls double version -> 6.0
Example: Method Overriding (Run-time)
Animal a = new Cat(); // reference type Animal, object type Cat
[Link](); // Output: Cat meows (decided at run time)
Page 17 of 19
BCA — Java Programming Unit II
3.5 Abstract Classes
Abstract Class: A class declared with the abstract keyword that cannot be instantiated directly. It can contain
both abstract methods (without a body) and concrete methods (with a body). It is meant to be extended by
subclasses.
abstract class Shape {
abstract void draw(); // abstract method - no body
void info() { // concrete method - has a body
[Link]("This is a shape");
}
}
class Circle extends Shape {
void draw() { // must override the abstract method
[Link]("Drawing a circle");
}
}
Shape s = new Circle();
[Link](); // Drawing a circle
[Link](); // This is a shape
Rules of Abstract Classes
• Cannot be instantiated directly using the new keyword.
• Can have constructors, fields, static methods, and concrete (fully defined) methods.
• If a class contains even one abstract method, the class itself must be declared abstract.
• The first concrete subclass must override and implement all inherited abstract methods.
3.6 Final Class
final keyword (with class): When a class is declared with the final keyword, it cannot be inherited/extended
by any other class. This is used to prevent further modification of critical, complete functionality.
final class Constants {
static final double PI = 3.14159;
}
// The following line would cause a COMPILE-TIME ERROR:
// class MyConstants extends Constants { } // ERROR: cannot inherit from
final class
Other Uses of final Keyword
Usage Effect
final variable Value cannot be changed once assigned (acts as a constant).
final method Cannot be overridden by any subclass.
Page 18 of 19
BCA — Java Programming Unit II
Usage Effect
final class Cannot be extended/inherited by any other class.
Real-world example: The built-in Java class String is declared final, preventing programmers from creating a
subclass that could alter its core, security-critical behaviour.
End of Unit II Notes
Page 19 of 19