0% found this document useful (0 votes)
3 views38 pages

Objects, Classes, and Constructors in Java

This document covers the fundamentals of objects, classes, and constructors in Java. It explains the definitions and differences between classes and objects, the syntax for creating them, and the concept of constructors, including their types and overloading. Additionally, it discusses methods, method overloading, and method binding, providing examples and analogies for better understanding.
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)
3 views38 pages

Objects, Classes, and Constructors in Java

This document covers the fundamentals of objects, classes, and constructors in Java. It explains the definitions and differences between classes and objects, the syntax for creating them, and the concept of constructors, including their types and overloading. Additionally, it discusses methods, method overloading, and method binding, providing examples and analogies for better understanding.
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

Unit 2.

0: Objects, Classes, and Constructors in Java

PART 1: Basics of Objects and Classes

2.1 What is a Class?

Simple Definition:

A class is a blueprint or template for creating objects. It defines what an object will look like and
what it can do.

Analogy 1 — Blueprint of a House : A class is like an architect's blueprint. The blueprint itself is
not a house — but you can build many houses FROM that blueprint. Each house built = an object.

Analogy 2 — Cookie Cutter : Class = Cookie cutter (the mold) Object = The actual cookie made
from the mold You can make many cookies from one cutter!

What does a Class contain?

❖ Class
▪ Fields/Variables (Attributes) → What the object HAS
Example: color, speed, name
▪ Methods (Beha––viors) → What the object DOES
Example: drive(), stop(), accelerate()

Syntax of a Class:
class ClassName {
// Fields (attributes/variables)
dataType fieldName;

// Methods (behaviors)
returnType methodName(parameters) {
// method body
}
}

Real Example — Car Class:


class Car {
// Fields
String color;
String brand;
int speed;
// Method
void drive() {
[Link](brand + " is driving at " + speed + " km/h");
}

void stop() {
[Link](brand + " has stopped.");
}
}

2.2 What is an Object?

Simple Definition:

An object is a real-world instance (actual entity) created from a class. It has its own copy of the
class's fields and can use its methods.

Analogy: If Car is the blueprint, then myCar, yourCar, taxiCar are actual objects (real cars) built from
that blueprint.

Key Properties of an Object:

Property Meaning Example

State Data stored in fields color = "Red", speed = 80

Behavior What it does (methods) drive(), stop()

Identity Unique reference/address Each object has own memory address

2.3 Declaring Objects — The new Keyword

How to Create an Object:


// Syntax:
ClassName objectName = new ClassName();

// Example:
Car myCar = new Car();

What happens step by step:


Car myCar = new Car();

new Car() Allocates memory in HEAP,calls constructor, returns reference


myCar Variable that STORES the reference (address)

Car Data type (reference type)

Visual Memory Diagram:

Stack Memory Heap Memory


color = null

myCar (reference) ────────▶ brand = null

speed = 0

Accessing Fields and Methods:

// Using dot (.) operator


[Link] = "Red"; // Setting field
[Link] = "Toyota"; // Setting field
[Link] = 80; // Setting field
[Link](); // Calling method

Complete Example:
class Car {
String color;
String brand;
int speed;

void drive() {
[Link](brand + " (" + color + ") driving at " +
. speed + " km/h");
}
}

class Main {
public static void main(String[] args) {
// Creating objects
Car car1 = new Car();
[Link] = "Red";
[Link] = "Toyota";
[Link] = 80;
[Link](); // Output: Toyota (Red) driving at 80 km/h

Car car2 = new Car();


[Link] = "Blue";
[Link] = "Honda";
[Link] = 60;
[Link](); // Output: Honda (Blue) driving at 60 km/h
}
}

Key Point: Each object has its own separate copy of instance variables. [Link] and [Link]
are independent!

Quick Summary:

• Class = Blueprint (template)

• Object = Real instance created from class

• new keyword allocates memory in heap and returns reference

• Use dot . operator to access fields and methods

Practice Questions:

1. What is the difference between a class and an object?

2. What does the new keyword do in Java?

3. Can two objects of the same class have different values for their fields? Explain.

PART 2: Methods in Detail

2.4 Defining and Calling Methods in a Class

We already touched on methods in Unit 1. Now let's go deeper.

Method Structure:
accessModifier returnType methodName(parameterList) {
// method body
return value; // only if returnType ≠ void
}

Types of Method Calls:

1. Method with no parameters, no return value:


class Greeter {
void greet() {
[Link]("Hello! Welcome to Java.");
}
}

// Calling:
Greeter g = new Greeter();
[Link]();

2. Method with parameters, no return value:

class Calculator {
void printSum(int a, int b) {
[Link]("Sum = " + (a + b));
}
}

// Calling:
Calculator c = new Calculator();
[Link](5, 3); // Output: Sum = 8

3. Method with parameters AND return value:

class Calculator {
int add(int a, int b) {
return a + b; // returns the result
}
}

// Calling:
Calculator c = new Calculator();
int result = [Link](10, 20);
[Link](result); // Output: 30
2.5 Overloading Methods

Definition:

Method Overloading means having multiple methods with the SAME name but different
parameter lists (different number, type, or order of parameters) within the same class.

Analogy: Think of a Swiss Army Knife — one tool, but it can do many things (cut, open bottle, file
nails). Same name (knife), different functionality.

Real-life: A print() method that can print integers, strings, doubles — you call print() every time but it
behaves differently based on what you pass.

Rules for Overloading:

Must Change Can Stay Same

Parameter list (type/number/order) Method name

Return type (can be same or different)

Access modifier

IMPORTANT: You CANNOT overload by changing only the return type!


class MathOperations {

// Same name, different parameter types


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

double add(double a, double b) {


return a + b;
}

// Same name, different number of parameters


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

// Same name, different order of parameters


String combine(String s, int n) {
return s + n;
}
String combine(int n, String s) {
return n + s;
}
}

class Main {
public static void main(String[] args) {
MathOperations m = new MathOperations();
[Link]([Link](3, 4)); // 7 (int version)
[Link]([Link](3.5, 4.5)); // 8.0 (double version)
[Link]([Link](1, 2, 3)); // 6 (3-param version)
}
}

How Java decides which method to call? This is called compile-time polymorphism or static
binding — the compiler looks at the arguments and decides at compile time.

Quick Summary:

Method overloading = same name, different parameters. Resolved at compile time.

Practice Questions:

1. What is method overloading? Give an example.

2. Can two methods have the same name and same parameters but different return types? Why?

3. Write a class with an overloaded method area() that calculates area of square, rectangle, and
circle.

PART 3: Constructors

2.6 What is a Constructor?

Simple Definition:

A constructor is a special method that is automatically called when an object is created using new.
Its purpose is to initialize the object.

Analogy — Hospital Birth Registration : When a baby is born (object created), immediately the
hospital registers the birth — name, date, weight (initialization). This automatic registration =
constructor!
Analogy 2 — New Phone Setup : When you first turn on a new phone (create object), it
automatically runs a setup process (constructor) — setting language, date, etc.

Properties of Constructor:

Property Value

Name MUST be same as class name

Return type NO return type (not even void)

Called automatically YES — when new is used

Can be overloaded YES

Can have parameters YES

Basic Example:

class Student {
String name;
int age;

// Constructor
Student() {
name = "Unknown";
age = 0;
[Link]("Student object created!");
}
}

class Main {
public static void main(String[] args) {
Student s = new Student(); // Constructor called automatically
// Output: Student object created!
}
}

2.7 Types of Constructors

Three Types:
I. Constructors
1. Default Constructor
2. No-Argument Constructor (No-arg)
3. Parameterized Constructor

Type 1: Default Constructor

Definition: When you do NOT write any constructor in a class, Java automatically provides an
invisible, empty constructor. This is called the default constructor.

class Animal {
String name;
// No constructor written by programmer
// Java automatically adds:
// Animal() { } ← invisible default constructor
}

Animal a = new Animal(); // Uses default constructor


// name = null (default for String)

Important: If you write ANY constructor yourself, Java stops providing the default constructor!

Type 2: No-Argument Constructor

Definition: A constructor written by the programmer with no parameters.


class Animal {
String name;
int age;

// No-arg constructor (programmer written)


Animal() {
name = "Unknown";
age = 0;
[Link]("Animal created with default values");
}
}

Animal a = new Animal();


// Output: Animal created with default values
// [Link] = "Unknown", [Link] = 0

Type 3: Parameterized Constructor

Definition: A constructor that accepts parameters to initialize the object with specific values.
class Student {
String name;
int age;
double marks;

// Parameterized constructor
Student(String n, int a, double m) {
name = n;
age = a;
marks = m;
}

void display() {
[Link]("Name: " + name + ", Age: " + age + ", Marks:
" + marks);
}
}

class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20, 85.5);
Student s2 = new Student("Bob", 21, 90.0);

[Link](); // Name: Alice, Age: 20, Marks: 85.5


[Link](); // Name: Bob, Age: 21, Marks: 90.0
}
}
2.8 Constructor Overloading

Just like method overloading, we can have multiple constructors in the same class with different
parameter lists.
class Rectangle {
int length;
int width;

// No-arg constructor
Rectangle() {
length = 1;
width = 1;
}

// One parameter (square)


Rectangle(int side) {
length = side;
width = side;
}

// Two parameters
Rectangle(int l, int w) {
length = l;
width = w;
}

int area() {
return length * width;
}
}

class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(); // 1x1
Rectangle r2 = new Rectangle(5); // 5x5
Rectangle r3 = new Rectangle(4, 6); // 4x6

[Link]([Link]()); // 1
[Link]([Link]()); // 25
[Link]([Link]()); // 24
}
}

Constructor vs Method Comparison:

Feature Constructor Method

Name Same as class Any valid name

Return type None (not even void) Must have (void or other)

Called by new keyword (automatically) Explicitly by programmer

Purpose Initialize object Perform operations

Inheritance NOT inherited Inherited

Overloading YES YES

7-Mark Question: "Explain types of constructors with examples and compare constructor vs
method."

Quick Summary:

• Default constructor → Java provides automatically if no constructor written

• No-arg constructor → Programmer writes with no parameters

• Parameterized constructor → Takes parameters to initialize with specific values

• Constructor overloading → Multiple constructors with different parameters

Practice Questions:

1. What is a constructor? How is it different from a method?

2. What happens to the default constructor when we write a parameterized constructor?

3. Write a class Book with constructor overloading (no-arg and parameterized).

PART 4: Array of Objects

2.9 Array of Objects


Definition:

An array of objects is an array where each element is an object reference (instead of a primitive
value).

Analogy — Classroom : A classroom has 30 students. Instead of creating 30 separate variables


(student1, student2...), you create an array of Student objects — much cleaner!

How to Create an Array of Objects:

// Step 1: Declare the array


Student[] students = new Student[3]; // Array of 3 Student references

// Step 2: Create individual objects


students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 21);
students[2] = new Student("Charlie", 19);

// Step 3: Access objects


students[0].display();
students[1].display();

Memory Diagram:

students array (Stack)

[0] [1] [2]

│ │ │

▼ ▼ ▼

[Alice] [Bob] [Charlie] ← Objects in Heap

Complete Example:
class Student {
String name;
int age;

Student(String n, int a) {
name = n;
age = a;
}

void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}

class Main {
public static void main(String[] args) {
// Array of 3 Student objects
Student[] students = new Student[3];

students[0] = new Student("Alice", 20);


students[1] = new Student("Bob", 21);
students[2] = new Student("Charlie", 19);

// Display all using loop


for (int i = 0; i < [Link]; i++) {
students[i].display();
}
}
}

Output:
Name: Alice, Age: 20
Name: Bob, Age: 21
Name: Charlie, Age: 19

PART 5: Method Binding, Overriding, and Exceptions

2.10 Method Binding

Definition:
Method Binding refers to the process of connecting a method call to the method body (deciding
which method gets executed).

Two Types:

1. Static Binding (Early Binding)

• Happens at compile time

• Used for: static methods, private methods, final methods, overloaded methods

• Compiler knows exactly which method to call

class Animal {
static void sound() {
[Link]("Some animal sound");
}
}
// Resolved at compile time → static binding
[Link]();

2. Dynamic Binding (Late Binding)

• Happens at runtime

• Used for: overridden methods (via inheritance)

• JVM determines which method to call based on the actual object type at runtime
class Animal {
void sound() {
[Link]("Generic animal sound");
}
}

class Dog extends Animal {


void sound() { // overriding
[Link]("Woof!");
}
}

class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Animal reference, Dog object
[Link](); // Which sound()? Decided at RUNTIME → "Woof!"
// This is dynamic binding!
}
}

Analogy: Static binding = Reading from a book (decided in advance). Dynamic binding = Asking
someone a question and they answer based on who they actually are at that moment.

2.11 Method Overriding

Definition:

Method Overriding occurs when a child class provides its own specific implementation of a
method that is already defined in the parent class.

Analogy — Recipe Customization : A parent class has a makeFood() method that makes basic
food. A child class (Italian Restaurant) overrides it to make pizza specifically. Same method name,
but different behavior!

Rules for Overriding:

Rule Detail

Method name MUST be same

Parameter list MUST be same

Return type Must be same (or covariant)

Access modifier Can be same or more accessible (not less)

Inheritance Child class overrides parent's method

@Override Use annotation (optional but recommended)

Example:
class Shape {
void draw() {
[Link]("Drawing a generic shape");
}

double area() {
return 0;
}
}

class Circle extends Shape {


double radius;

Circle(double r) {
radius = r;
}

@Override
void draw() {

[Link]("Drawing a Circle ");

@Override
double area() {
return 3.14 * radius * radius;
}
}

class Rectangle extends Shape {


double l, w;

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

@Override
void draw() {

[Link]("Drawing a Rectangle ▭");


}
@Override
double area() {
return l * w;
}
}

class Main {
public static void main(String[] args) {
Shape s1 = new Circle(5);
Shape s2 = new Rectangle(4, 6);

[Link](); // Drawing a Circle

[Link](); // Drawing a Rectangle ▭

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

Overloading vs Overriding Comparison :

Feature Overloading Overriding

Where Same class Parent-Child classes

Method name Same Same

Parameters DIFFERENT SAME

Return type Can differ Must be same

Binding Static (compile-time) Dynamic (runtime)

Also called Compile-time polymorphism Runtime polymorphism

Inheritance needed? NO YES

2.12 Exceptions (Introduction)


Definition:

An exception is an unwanted event that occurs during program execution and disrupts the normal
flow.

Analogy — Traffic Accident : You're driving normally (program running). Suddenly there's an
accident (exception). If you have no plan, traffic stops (program crashes). But if there's a traffic control
system (exception handling), traffic is redirected (program continues).

Basic Exception Handling:


try {
// Code that might throw exception
int result = 10 / 0; // ArithmeticException!
}
catch (ArithmeticException e) {
// Handle the exception
[Link]("Error: Cannot divide by zero!");
}
finally {
// Always executes (cleanup code)
[Link]("This always runs.");
}

Common Exceptions:

Exception Cause

ArithmeticException Division by zero

NullPointerException Using null reference

ArrayIndexOutOfBoundsException Invalid array index

NumberFormatException Invalid number format

ClassCastException Invalid type casting

Quick Summary:

• Static Binding → Compile time (overloading, static methods)

• Dynamic Binding → Runtime (overriding)

• Overriding → Child redefines parent's method (same name + parameters)


• Exception → Runtime error handled by try-catch

Practice Questions:

1. What is the difference between method overloading and overriding?

2. What is dynamic binding? Give an example.

3. Write a program showing method overriding with @Override annotation.

PART 6: Passing Objects & Returning Objects

2.13 Passing Object as Parameters

In Java, you can pass an object as an argument to a method, just like you pass primitive values.

Important: Java passes the reference (address) of the object, not a copy of the object itself. So any
changes made inside the method WILL affect the original object!

class Student {
String name;
int marks;

Student(String n, int m) {
name = n;
marks = m;
}

// Method that takes another Student object as parameter


void compare(Student other) {
if ([Link] > [Link]) {
[Link]([Link] + " scored higher!");
} else if ([Link] < [Link]) {
[Link]([Link] + " scored higher!");
} else {
[Link]("Both scored equally!");
}
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice", 85);
Student s2 = new Student("Bob", 90);

[Link](s2); // Output: Bob scored higher!


}
}

2.14 Returning Object from a Method

A method can return an object of a class type.

class Temperature {
double celsius;

Temperature(double c) {
celsius = c;
}

// Method that RETURNS a Temperature object (converted)


Temperature toFahrenheit() {
double f = (celsius * 9/5) + 32;
return new Temperature(f); // returning new object
}

void display() {
[Link]("Temperature: " + celsius);
}
}

class Main {
public static void main(String[] args) {
Temperature t1 = new Temperature(100); // 100°C
Temperature t2 = [Link](); // returns new object

[Link](); // Temperature: 100.0


[Link](); // Temperature: 212.0
}
}

PART 7: Static Members

2.15 Static Variables and Methods

Static Variables:

Definition: A static variable is shared among ALL objects of a class. It belongs to the class itself, not
to any individual object.

Analogy — School Whiteboard : A whiteboard in a classroom is shared by all students (static).


Each student's notebook (instance variable) is their own personal copy.

class Student {
String name; // instance variable (each object has its own)
static int count = 0; // static variable (SHARED by all objects)

Student(String n) {
name = n;
count++; // increment shared counter whenever new student
created
}
}

class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
Student s3 = new Student("Charlie");
[Link]("Total students: " + [Link]); // 3
// Access static variable using CLASS NAME (not object name)
}
}

Static Methods:

Definition: A static method belongs to the class, not to objects. Can be called without creating an
object.

class MathUtils {
static int square(int n) {
return n * n;
}

static int cube(int n) {


return n * n * n;
}
}

class Main {
public static void main(String[] args) {
// No need to create object!
[Link]([Link](5)); // 25
[Link]([Link](3)); // 27
}
}

Rules for Static Methods:

Can do Cannot do

Access static variables Access instance variables directly

Call other static methods Call instance methods directly

Be called without object Use this or super keywords

Why is main() static? Because JVM needs to call main() WITHOUT creating any object first!
Static vs Instance Members:

Feature Static Instance

Belongs to Class Object

Memory One copy for all Separate copy per object

Access [Link] [Link]

When created Class loading Object creation

Example [Link] [Link]

PART 8: Access Modifiers

2.16 Access Modifiers

Definition:

Access modifiers are keywords that control the visibility/accessibility of classes, variables, and
methods.

Analogy — Building Security System :

• Public area (lobby) → Anyone can enter = public

• Employees only (office floor) → Only insiders = protected (package + subclass)

• Same department only → Only same area = default

• CEO's private office → Only the CEO = private

Four Access Modifiers:

Modifier Same Class Same Package Subclass (different package) Other Package

public

protected

default (no keyword)

private

Visualization:

private ⊂ default ⊂ protected ⊂ public

(least access) (most access)

Example:
class Person {
public String name; // accessible everywhere
protected int age; // accessible in package + subclasses
String city; // default - accessible in same package
only
private String password; // accessible ONLY in this class

// Getter and Setter for private field (Encapsulation)


public void setPassword(String pwd) {
password = pwd;
}
public String getPassword() {
return password;
}
}
Getter and Setter Pattern (Encapsulation in Action):
class BankAccount {
private double balance; // hidden

// Getter
public double getBalance() {
return balance;
}
// Setter with validation
public void setBalance(double amount) {
if (amount >= 0) {
balance = amount;
} else {
[Link]("Invalid amount!");
}
}
}

Best Practice: Make all fields private, provide public getters/setters = Perfect Encapsulation!
7-Mark Question: "Explain access modifiers in Java with examples and an accessibility table."

PART 9: this Keyword

2.17 The this Keyword

Definition:

this is a reference to the current object — the object that is currently calling the method or
constructor.

Analogy: When you say "I will do this" — "I" refers to yourself. Similarly, this in Java refers to the
current object itself.

Uses of this:

Use 1: Resolve Naming Conflict (most common)

When parameter name is same as field name:

class Student {
String name;
int age;

Student(String name, int age) {


// 'name' here is ambiguous — parameter or field?
[Link] = name; // [Link] = field, name = parameter
[Link] = age;
}
}
Without this:
Student(String name, int age) {

name = name; // WRONG! Assigning param to itself, field


unchanged
}
With this:
Student(String name, int age) {

[Link] = name; // CORRECT! [Link] = field

Use 2: Call Another Constructor — this()


class Rectangle {
int length, width;

Rectangle() {
this(1, 1); // calls Rectangle(int, int) constructor
}

Rectangle(int l, int w) {
[Link] = l;
[Link] = w;
}
}

this() must be the first statement in a constructor!

Use 3: Pass Current Object as Argument

class Printer {
void print(Student s) {
[Link]("Printing: " + [Link]);
}
}

class Student {
String name = "Alice";

void sendToPrint(Printer p) {
[Link](this); // passing current object
}
}

Use 4: Return Current Object


class Builder {
int value;
Builder setValue(int v) {
[Link] = v;
return this; // return current object (method chaining)
}
}

PART 10: Garbage Collection & finalize()

2.18 Garbage Collection

Definition:

Garbage Collection is Java's automatic memory management system that removes objects from
heap memory that are no longer being referenced/used.

Analogy — Automatic Room Cleaning Robot : Imagine a robot that automatically cleans your
room by removing things you no longer use (unused objects). You don't need to manually clean — Java
does it for you!

In C/C++: Programmer manually frees memory → Prone to memory leaks

In Java: JVM automatically handles it → Much safer

How does an object become eligible for GC?

// Case 1: Null reference


Student s = new Student("Alice");
s = null; // Alice object has no reference → eligible for GC

// Case 2: Re-assignment
Student s = new Student("Alice");
s = new Student("Bob"); // Alice object lost reference → eligible for
GC

// Case 3: Object goes out of scope


void method() {
Student s = new Student("Temp");
} // After method ends, s is out of scope → eligible for GC
Key Points:

• Garbage collection happens automatically (you can suggest but not force it)

• [Link]() → requests GC to run (not guaranteed)

• GC runs in the background as a low-priority thread

• Removes objects from Heap memory

2.19 finalize() Method

Definition:

finalize() is a method that the JVM calls on an object just before garbage collecting it. It gives the
object a chance to clean up resources (close files, database connections, etc.).

Analogy — Last Will Before Departure : Before someone leaves (object destroyed), they write a
will/leave instructions. finalize() is Java's "last will" — execute this before I'm destroyed!

class DatabaseConnection {
String connectionName;

DatabaseConnection(String name) {
[Link] = name;
[Link]("Connection opened: " + name);
}

@Override
protected void finalize() throws Throwable {
[Link]("Connection closed: " + connectionName);
// cleanup code here
[Link]();
}
}

class Main {
public static void main(String[] args) {
DatabaseConnection db = new DatabaseConnection("DB1");
db = null; // eligible for GC
[Link](); // request GC
// finalize() may be called before object is collected
}
}

Note: finalize() is deprecated since Java 9 — not recommended for use. Better to use try-with-
resources or close() methods.

PART 11: Nested and Inner Classes

2.20 Nested Classes

Definition:

A class defined inside another class is called a nested class. The outer class is called the Enclosing
class.

Analogy — File inside a Folder : Just as you can have a file (inner class) inside a folder (outer
class), Java allows classes inside classes.

Types of Nested Classes:

1. Nested Classes
a. Static Nested Class
b. Non-Static (Inner Classes)
i. Regular Inner Class
ii. Method Local Inner Class
iii. Anonymous Inner Class

Type 1: Static Nested Class


class Outer {
static int x = 10;
static class StaticNested {
void display() {
[Link]("Static nested: x = " + x);
// Can access only STATIC members of outer class
}
}
}
class Main {
public static void main(String[] args) {
// Creating object of static nested class
[Link] obj = new [Link]();
[Link](); // Static nested: x = 10
}
}

Type 2: Regular Inner Class (Non-static)

class Outer {
int x = 10; // instance variable

class Inner {
void display() {
[Link]("Inner class: x = " + x);
// Can access ALL members of outer class
}
}
}

class Main {
public static void main(String[] args) {
// Must create outer object first
Outer outer = new Outer();
[Link] inner = [Link] Inner(); // special syntax
[Link](); // Inner class: x = 10
}
}

Type 3: Anonymous Inner Class

A class without a name, defined and instantiated in one expression. Used for one-time use.
// Typically used with interfaces or abstract classes
interface Greeting {
void greet();
}

class Main {
public static void main(String[] args) {
// Anonymous class implementing Greeting interface
Greeting g = new Greeting() {
@Override
public void greet() {
[Link]("Hello from anonymous class!");
}
};
[Link]();
}
}

When to Use Nested Classes?

Type Use When

Static Nested Helper class that doesn't need outer instance

Inner Class Needs access to outer class's instance members

Anonymous Class One-time implementation of interface/abstract class

PART 12: String Class

2.21 Exploring the String Class

Definition:

String is a class in Java (not a primitive type!) that represents a sequence of characters. Strings in
Java are immutable — once created, they cannot be changed.

Analogy — Engraved Stone Tablet : Once words are engraved in stone (String created), you can't
change them. But you can create a NEW stone with different words. That's string immutability!
Creating Strings:

// Method 1: String Literal (stored in String Pool)


String s1 = "Hello";

// Method 2: Using new keyword (stored in Heap)


String s2 = new String("Hello");

String Pool:

String Pool (inside Heap)

┌────────────────┐

│ "Hello │ ← s1 and s3 both point here

│ "World" │ ← s2 points here

└────────────────┘

String s1 = "Hello";
String s3 = "Hello";
// s1 and s3 point to SAME object in string pool (memory efficient!)

String s2 = new String("Hello");


// s2 is a NEW object in heap (different from s1)

Important String Methods :

String str = "Hello, World!";

Method Example Result Meaning

length() [Link]() 13 Number of characters

charAt(i) [Link](0) 'H' Character at index

indexOf(s) [Link]("World") 7 First occurrence position

substring(i) [Link](7) "World!" From index to end

substring(i,j) [Link](0,5) "Hello" From i to j-1


Method Example Result Meaning

toUpperCase() [Link]() "HELLO, WORLD!" All uppercase

toLowerCase() [Link]() "hello, world!" All lowercase

trim() " hi ".trim() "hi" Remove spaces

replace(a,b) [Link]("World","Java") "Hello, Java!" Replace substring

equals(s) [Link](s2) true/false Content comparison

equalsIgnoreCase(s) "Hi".equalsIgnoreCase("hi") true Case-insensitive compare

contains(s) [Link]("World") true Checks substring

startsWith(s) [Link]("Hello") true Checks prefix

endsWith(s) [Link]("!") true Checks suffix

split(delimiter) [Link](",") ["Hello", " World!"] Split into array

isEmpty() "".isEmpty() true Check if empty

compareTo(s) [Link](s2) 0/-ve/+ve Lexicographic compare

String Immutability — Demonstrated:

String s = "Hello";

[Link](); // Doesn't change s!

[Link](s); // Still "Hello"

s = [Link](); // Creates new string, assigns to


s
[Link](s); // "HELLO"

StringBuilder vs String:

// String: immutable, slow for repeated modifications


String s = "Hello";
s = s + " World"; // Creates new String object every time!
// StringBuilder: mutable, fast for repeated modifications
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // Modifies same object
[Link]([Link]()); // "Hello World"
Feature String StringBuilder StringBuffer

Mutable No Yes Yes

Thread-safe Yes No Yes

Performance Slow (modifications) Fast Moderate

Use when Fixed strings Single thread Multi-thread

Important: Always use equals() to compare Strings, NEVER ==!

String a = "hello";
String b = new String("hello");
[Link](a == b); // false (comparing references)

[Link]([Link](b)); // true (comparing content)

Quick Summary:

• String is immutable in Java

• String Pool saves memory for literals

• equals() for content comparison, == for reference comparison

• StringBuilder for mutable string operations

Practice Questions:

1. What is string immutability? Why is it important?

2. What is the difference between == and .equals() for Strings?

3. Write a program to count vowels in a string using String methods.


UNIT 2 — FULL REVISION SUMMARY

1) CLASSES & OBJECTS


i) Class = Blueprint | Object = Instance
ii) new keyword → allocates heap memory, calls constructor
iii) Dot (.) operator → access fields and methods
iv) Each object has own copy of instance variables

2) CONSTRUCTORS
i) Default → Auto-provided by Java (if no constructor written)
ii) No-arg → Programmer written, no parameters
iii) Parameterized → Takes parameters for initialization
iv) Overloaded → Multiple constructors, different parameters
★ No return type | Same name as class | Called by new

3) METHOD OVERLOADING vs OVERRIDING


i) Overloading: Same class, same name, DIFFERENT params → Compile-time
ii) Overriding: Parent-Child, same name + params → Runtime

4) BINDING
i) Static/Early → Compile time (overloading, static, private, final)
ii) Dynamic/Late → Runtime (overriding)

5) ACCESS MODIFIERS
i) public → Everywhere
ii) protected → Same package + subclass
iii) default → Same package only
iv) private → Same class only
★ private < default < protected < public

6) this KEYWORD
i) Refers to current object
ii) Resolves name conflicts ([Link] = param)
iii) this() → calls another constructor
iv) Can pass/return current object

7) GARBAGE COLLECTION
i) Automatic memory management by JVM
ii) Removes unreferenced heap objects
iii) finalize() → called before object is GC'd (deprecated)
iv) [Link]() → requests GC (not guaranteed)

8) NESTED CLASSES
i) Static Nested → No outer instance needed
ii) Inner Class → Can access outer instance members
iii) Anonymous → One-time, nameless class

9) STRING CLASS
i) Immutable (cannot change once created)
ii) String Pool for literals
iii) Use equals() not == for comparison
iv) StringBuilder for mutable strings

MIXED PRACTICE QUESTIONS (Exam Level)

Short Answer (2 marks):

1. What is the purpose of the new keyword?

2. What is this keyword? Give one use with example.

3. What is an anonymous inner class?

4. Differentiate String and StringBuilder.

5. What is garbage collection?

Medium Answer (5 marks):

1. Explain constructor overloading with a program.

2. Explain the four access modifiers with an accessibility table.

3. Write a program to demonstrate array of objects.

Long Answer — 7 Marks :

1. Explain all types of constructors in Java with examples and difference from methods.

2. Explain method overloading and method overriding with examples. Tabulate the
differences.

3. What are access modifiers in Java? Explain each with examples and accessibility table.

4. Explain static members in Java. How are static variables different from instance
variables? Give programs.

5. Explain the String class in Java with at least 8 important methods and examples.

6. What are nested classes? Explain the types with examples.


COMMON MISTAKES — Unit 2

Mistake Correction

Constructor has return type Constructor NEVER has return type

Using == to compare strings Always use .equals() for strings

Accessing instance variable from static


Static methods can't directly access instance vars
method

Forgetting this() must be first in constructor this() MUST be the first statement

Calling [Link]() and expecting


It's a request, not a command
immediate GC

Confusing overloading with overriding Overloading = same class; Overriding = parent-child

Thinking String is mutable String is IMMUTABLE — operations return new strings

Not initializing array elements after creating new Student[3] creates refs, not objects — must create
array each

Accessing static variable via object name Access via class name: [Link]

You might also like