UNIT II Classes, Methods & Objects in java
Class Fundamentals
A class in Java is a blueprint or template used to create objects. It defines the common
properties (data members) and behaviors (methods) that the objects of that class will have. A
class itself does not occupy memory until an object is created from it.
Key Concepts of a Class
1. Data Members (Fields)
Data members are variables declared inside a class.
They store the state or properties of an object.
Each object has separate values for these variables.
Examples: rollNo, name
2. Methods (Member Functions)
Methods are functions defined inside a class.
They represent the behavior or actions an object can perform.
Methods operate on data members.
Example: display() method to show student details.
Syntax:- class ClassName {
data members;
methods;
}
Example Program
class Student {
int rollNo; // Data member
String name; // Data member
void display() { // Method
[Link](rollNo + " " + name);
Declaring Objects
An object is an instance of a class. To create an object, Java uses a two-step process:
declaration and instantiation.
These steps can be written separately or combined into a single statement.
Syntax
ClassName objectName = new ClassName();
ClassName → Name of the class (e.g., Student)
objectName → Reference variable (e.g., s1)
new → Allocates memory for the object
ClassName() → Calls the constructor
Step 1: Object Declaration
Object declaration creates a reference variable that can point to an object of a specific class.
Syntax
ClassName objectName;
Example
Student s1;
At this stage, no object is created
s1 holds the default value null
Step 2: Object Instantiation (Initialization)
Instantiation allocates memory and initializes the object using the new keyword.
Syntax
objectName = new ClassName();
Example
s1 = new Student();
Memory is allocated in the heap.
The constructor initializes data members.
Combined Declaration and Instantiation
Student s1 = new Student();
This line: Declares the reference variable
Creates the object
Assigns the reference to the object
Program
// Student class
class Student {
String name;
int rollNumber;
// Constructor
Student(String name, int rollNumber) {
[Link] = name;
[Link] = rollNumber;
}
// Method
void displayInfo() {
[Link]("Name: " + name + ", Roll Number: " + rollNumber);
}
}
// Main class
public class ObjectExample {
public static void main(String[] args) {
// Creating objects
Student s1 = new Student("Alice", 101);
Student s2 = new Student("Bob", 102);
// Using objects
[Link]();
[Link]();
}
}
Key Points (Exam-Important)
Objects are created using the new keyword.
Reference variables store addresses of objects.
Constructors initialize object data.
Each object has its own copy of instance variables.
Assigning Object Reference Variables
In Java, object variables store references, not actual objects.
When one object reference is assigned to another, both references point to the same object in
memory.
Key Point
Changes made using one reference affect the same object accessed by the other reference.
Example
Student s1 = new Student();
Student s2 = s1; // Both refer to the same object.
Explanation:- s1 and s2 point to one object
No new object is created
Program:-
class Student {
int roll;
void display() {
[Link]("Roll Number: " + roll);
}
}
public class ObjectReferenceDemo {
public static void main(String[] args) {
Student s1 = new Student(); // Create object
[Link] = 101;
Student s2 = s1; // Assign reference
// Modify value using s2
[Link] = 202;
// Display using both references
[Link]();
[Link]();
}
}
Output:-
Roll Number: 202
Roll Number: 202
Explanation
s1 creates a Student object.
s2 = s1 copies the object reference, not the object itself.
Both s1 and s2 point to the same object in memory.
Any change made using one reference is visible through the other.
Methods
A method in Java is a named block of code defined inside a class that performs a specific task.
Methods help in code reusability, modularity, and better program organization.
Syntax
returnType methodName(parameters) {
// statements
}
Key Terminology
Method Name: Identifier used to call the method.
Return Type: Data type of the value returned by the method. Use void if no value is returned.
Parameters: Variables that receive values when the method is called.
Method Signature: Combination of method name and parameter list.
Method Body: Block of statements executed when the method is called.
Program
public class Calculator {
// Method that returns an integer value
int add(int a, int b) {
return a + b;
}
// Method that does not return any value
void greet(String name) {
[Link]("Hello, " + name + "!");
}
public static void main(String[] args) {
Calculator myCalc = new Calculator(); // Object creation
int result = [Link](5, 3); // Method call
[Link]("The sum is: " + result);
[Link]("Alice"); // Method call
}
}
Output
The sum is: 8
Hello, Alice!
Advantages Of Methods
Code Reusability: Once a method is defined, it can be called multiple times from different parts
of a program without rewriting the code.
Reduces Repetition (DRY principle): Promotes the "Don't Repeat Yourself" principle by
centralizing common logic.
Modularity: Breaks down complex programs into smaller, manageable, and logical units,
making the code easier to understand, debug, and maintain.
Abstraction: Users only need to know what a method does (its purpose and signature), not
necessarily how it works internally.
Constructors
A constructor is a special member of a Java class that is used to initialize objects.
It has the same name as the class, has no return type (not even void), and is automatically
called when an object is created using the new keyword.
Main purpose: To initialize the data members of an object.
Characteristics of Constructors
Name must be same as the class name
No return type
Called automatically at the time of object creation
Can be overloaded
Used to set initial values of instance variables
Example:
class Student {
int roll;
// Constructor
Student(int r) {
roll = r;
}
void display() {
[Link]("Student roll number is: " + roll);
}
public static void main(String[] args) {
Student s1 = new Student(101); // Constructor called
[Link]();
}
}
Output
Student roll number is: 101
Types of Constructors in Java
1)Default Constructor
Provided automatically by the Java compiler
Created only if no constructor is defined
Takes no arguments
Initializes variables with default values
Example
class Student {
int roll;
Student() { // default constructor
roll = 0;
}
void display() {
[Link](roll);
}
}
class Main {
public static void main(String args[]) {
Student s = new Student();
[Link]();
}
}
Output
2) Parameterized Constructor
Accepts parameters
Initializes object with given values
Values are passed during object creation
Example
class Student {
int roll;
Student(int r) {
roll = r;
}
public static void main(String[] args) {
Student s = new Student(102);
[Link]([Link]);
}
}
Output
102
3) copy constructor
A copy constructor is a parameterized constructor that takes an object of the same class as an
argument and copies its data members into the new object.
Syntax:
ClassName(ClassName object) {
// copy values
}
Example of Copy Constructor
class Student {
int roll;
// Parameterized constructor
Student(int r) {
roll = r;
}
// Copy constructor
Student(Student s) {
roll = [Link];
}
void display() {
[Link](roll);
}
public static void main(String args[]) {
Student s1 = new Student(101);
Student s2 = new Student(s1); // copying object
[Link]();
[Link]();
}
}
Output:
101
101
Why Copy Constructor is Used
To copy object data safely
To create a new independent object
To avoid sharing references
Improves code clarity
Important Points (for Exams)
Java does not have a default copy constructor
Copy constructor is user-defined
It performs shallow copy (by default)
Used when object duplication is required
Constructor Overloading
Having more than one constructor in a class
Constructors differ in number or type of parameters
Provides multiple ways to initialize objects
Example
class Student {
int roll;
String name;
Student() {
roll = 0;
name = "Not Assigned";
}
Student(int r, String n) {
roll = r;
name = n;
}
void display() {
[Link](roll + " " + name);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student(101, "Alice");
[Link]();
[Link]();
}
}
Output
0 Not Assigned
101 Alice
Constructor Types Summary Table (Exam-Ready)
Type Arguments Provided By Purpose
DefaultNo Compiler Assign default values
ParameterizedYes Programmer Initialize with input
Copy Object Programmer Copy object data
The this Keyword
The this keyword is a reference variable that refers to the current object of the class.
Uses of this Keyword
1. To Distinguish Instance Variables from Local Variables
When instance variables and method parameters have the same name, this is used to refer to
the instance variable.
Example:
class Test {
int x; // instance variable
Test(int x) {
this.x = x; // this.x refers to instance variable
}
}
2. To Invoke Current Class Constructor (Constructor Chaining)
this() is used inside a constructor to call another constructor of the same class.
Example:
class Student {
int roll;
String name;
Student() {
this(101, "Gauri"); // calling parameterized constructor
}
Student(int r, String n) {
roll = r;
name = n;
}
}
⚠️ this() must be the first statement in the constructor.
3. To Pass Current Object as an Argument
The current object can be passed to a method using this.
Example:
class Demo {
void show(Demo d) {
[Link]("Method called");
}
void call() {
show(this); // passing current object
}
}
4. To Return the Current Object
this can be returned from a method.
Example:
class Sample {
Sample getObject() {
return this; // returning current object
}
}
Important Points for Exam
this is a reference variable
Refers to the current calling object
Cannot be used in static context
Helps in code clarity and readability
Summary
The this keyword in Java refers to the current object of the class. It is used to distinguish
instance variables from local variables, invoke constructors, pass the current object, and return
the current object.
Garbage Collection
Garbage Collection (GC) in Java is an automatic memory management process that helps Java
programs run efficiently by removing unused objects from memory.
Objects are created in the heap memory.
Over time, some objects are no longer needed.
Garbage collection automatically removes these unused (unreferenced) objects.
It is handled by the JVM (Java Virtual Machine).
The programmer does not need to delete objects manually.
Working of Garbage Collection
Garbage Collector performs the following tasks:
Identifies which objects are still in use (reachable)
Identifies which objects are not in use (unreachable)
Removes the unreachable objects from heap memory
Frees memory for new object creation
👉 Garbage collection is automatic and JVM-controlled.
Java Heap Memory Structure (Generations)
Java heap is divided into generations:
1. Young Generation
New objects are created here
Frequent garbage collection occurs
Short-lived objects are stored
2. Old Generation
Long-lived objects are stored here
Objects that survive multiple GC cycles move here
Garbage collection occurs less frequently
Types of Garbage Collection Activities
1. Minor (Incremental) Garbage Collection
Occurs in Young Generation
Removes short-lived, unreachable objects
Happens frequently
2. Major (Full) Garbage Collection
Occurs in Old Generation
Removes long-lived unreachable objects
Happens less frequently
Takes more time than minor GC
Advantages of Garbage Collection
Makes Java memory-efficient
Automatically removes unused objects
Prevents memory leaks
Reduces programmer effort
Improves application performance
Ensures better memory utilization
Summary
Garbage collection in Java is an automatic memory management process in which the JVM
removes unused and unreachable objects from heap memory to free space and improve
performance.
finalize() Method
Definition
The finalize() method is a special method of the Object class that is called by the Garbage
Collector before an object is destroyed. It was originally intended to perform cleanup operations
on non-Java resources such as files, database connections, or network resources.
Syntax
protected void finalize() throws Throwable {
// cleanup code
}
Purpose of finalize()
Used to release non-Java resources
Called automatically by Garbage Collector
Executes before the object is removed from heap memory
Example
class Test {
protected void finalize() {
[Link]("Finalize method called");
}
}
⚠️ Calling of finalize() is not guaranteed.
Limitations of finalize() Method
1. Unpredictable Execution
There is no guarantee when finalize() will be executed
It may never be called if the garbage collector does not run
2. Performance Overhead
Objects with finalize() take more time to collect
It slows down the garbage collection process
3. Deprecation
finalize() was deprecated in Java 9
Removed in Java 18
Its use is strongly discouraged in modern Java programs
Why finalize() Is Not Recommended
Unreliable execution
Poor performance
Risk of resource leaks
Better alternatives are available
Modern Alternatives to finalize()
1. try-with-resources Statement
Used for resource management
Works with classes implementing AutoCloseable
Ensures resources are closed automatically
Example:
try (FileInputStream fis = new FileInputStream("[Link]")) {
// use resource
2. Cleaner Class (Java 9+)
Introduced as a replacement for finalize()
Provides safer and more predictable cleanup
⚠️
Used when resources cannot implement AutoCloseable
More complex than try-with-resources
Important Exam Points
finalize() belongs to Object class
Called by Garbage Collector
Execution is not guaranteed
Deprecated in Java 9
Removed in Java 18
Prefer try-with-resources
Summary
The finalize() method is a method of the Object class that is called by the garbage collector
before an object is destroyed. Its use is deprecated due to unpredictable execution and
performance issues.
Method Overloading
Definition
Method overloading in Java allows a class to have more than one method with the same name,
provided that their parameter lists are different. The difference may be in the number, type, or
order of parameters.
Key Characteristics of Method Overloading
1)Same Method Name
All overloaded methods must have the same name.
2)Different Parameter List
Methods must differ by: Number of parameters , Type of parameters & Order (sequence) of
parameters.
3)Return Type Does Not Matter
Methods cannot be overloaded by return type alone
Return type may differ only if parameter list is different
4)Compile-Time Polymorphism
Method overloading is an example of compile-time (static) polymorphism
The method call is resolved by the compiler at compile time
How the Compiler Decides Which Method to Call
When an overloaded method is called, the compiler:
Compares the arguments passed
Matches them with the best-suited method signature
This process is called method resolution
Example of Method Overloading
class MathOp {
// Method 1: takes two integers
int add(int a, int b) {
return a + b;
}
// Method 2: takes two doubles
double add(double a, double b) {
return a + b;
}
// Method 3: takes three integers
int add(int a, int b, int c) {
return a + b + c;
}
}
class Main {
public static void main(String[] args) {
MathOp mo = new MathOp();
[Link]("Sum of two integers: " + [Link](5, 10));
[Link]("Sum of two doubles: " + [Link](5.5, 10.2));
[Link]("Sum of three integers: " + [Link](1, 2, 3));
}
}
Advantages of Method Overloading
Improves code readability
Increases flexibility
Allows using the same method name for similar operations
Supports compile-time polymorphism
Important Exam Notes
Overloading occurs within the same class
❌
Method signature = method name + parameter list
Changing only return type → not valid overloading
Overloaded methods may have different access modifiers
Summary
Method overloading in Java allows multiple methods with the same name but different
parameter lists. It is an example of compile-time polymorphism.
Passing Objects as Parameters
In Java, objects can be passed as parameters to methods. Java follows a pass-by-value
mechanism. When an object is passed to a method, the value of the reference (memory
address) to that object is passed, not the actual object itself.
This means that:
A copy of the reference to the object is passed to the method
Both the original reference and the method parameter refer to the same object in heap memory
Behavior When Objects Are Passed
1. Modification of Object State
If a method modifies the instance variables of the object, the changes are reflected outside the
method, because both references point to the same object.
2. Reassigning the Reference
If the method reassigns the reference variable to a new object, the change does not affect the
original object, because only the local copy of the reference is changed.
Key Points
Java does not support pass-by-reference
Objects are passed by value of reference
A method can modify object data
A method cannot change which object the caller’s reference points to
Advantages
Efficient memory usage
No unnecessary object copying
Enables object manipulation through methods
Supports real-world object behavior
Important Exam Notes
Objects are stored in heap memory
Reference variables are stored in stack memory
Passing object references allows shared access to object data
Example: Passing Object as Parameter
class Student {
int marks;
}
class Demo {
void changeMarks(Student s) {
[Link] = 80; // modifies original object
}
public static void main(String args[]) {
Student s1 = new Student();
[Link] = 50;
Demo d = new Demo();
[Link](s1);
[Link]([Link]);
}
}
Output
80
Explanation
A copy of the reference to s1 is passed
Both s and s1 refer to the same object
Changing [Link] affects the original object
Example: Reassigning Reference (No Effect)
void change(Student s) {
s = new Student(); // reassigns local copy
[Link] = 90;
}
➡️ This does not change the original object.
Key Exam Point
Java uses pass-by-value. For objects, the value passed is the reference, so object data can be
modified inside the method.
In Java, objects are passed to methods using pass-by-value. The value passed is the reference
to the object, so modifications to object data inside a method affect the original object.
Argument Passing
Java uses call by value for all types of argument passing.
For primitive data types, the actual value is copied.
For objects, the value of the reference is copied.
1. Argument Passing with Primitive Types
Example
class Demo {
static void change(int x) {
x = 20; // modifies local copy
}
public static void main(String args[]) {
int a = 10;
change(a);
[Link](a);
}
}
Output
10
Explanation
A copy of value 10 is passed to method
Changes to x do not affect a
Primitive types are passed by value
2. Argument Passing with Object Types
Example: Modifying Object State
class Student {
int marks;
}
class Demo {
static void change(Student s) {
[Link] = 80; // modifies object
}
public static void main(String args[]) {
Student s1 = new Student();
[Link] = 50;
change(s1);
[Link]([Link]);
}
}
Output
80
Explanation
A copy of the reference is passed
Both references point to the same object
Modifying object data affects original object
Explanation
Only local reference s changes
Original reference s1 remains unchanged
Object reassignment does not affect caller
Key Exam Points
Java does not support call by reference
Java always uses call by value
For objects, value passed is the reference
Object data can be modified inside methods
Reference itself cannot be changed
Summary
Java uses call by value for argument passing. For primitive types, a copy of the value is passed,
while for objects, a copy of the reference is passed.
Returning Objects
In Java, a method can return an object just like it can return primitive values.
When an object is returned from a method, the reference to the object is returned, not the actual
object itself.
This allows:
Creating objects inside a method
Returning them to the calling method
Reusing and manipulating objects efficiently
Syntax
ClassName methodName() {
return objectReference;
}
Example
class Student {
int roll;
Student(int r) {
roll = r;
}
}
class Demo {
Student getStudent() {
return new Student(101); // returning object
}
public static void main(String args[]) {
Demo d = new Demo();
Student s1 = [Link](); // receiving object
[Link]([Link]);
}
}
Output
101
Explanation of the Example
getStudent() creates a new Student object
The reference of that object is returned
The calling method stores the returned reference in s1
s1 refers to the same object created inside the method
Important Points
Java returns object references
Returned object is stored in heap memory
Reference variable is stored in stack memory
Multiple objects can be returned using arrays or collections
Advantages
Improves modularity
Promotes object-oriented design
Enables data sharing between methods
Reduces redundant object creation
Summary
In Java, methods can return objects. The reference to the object is returned, allowing the calling
method to access and use the object.
Recursion
Definition
Recursion is a programming technique in which a method calls itself in order to solve a problem
by breaking it into smaller sub-problems.
A recursive method must have:
Base condition – to stop recursion
Recursive call – the method calling itself
In recursion, a problem is solved by reducing it to a simpler version of the same problem. Each
recursive call creates a new stack frame in memory. The process continues until the base
condition is met. After that, the recursive calls are resolved one by one.
If the base condition is missing, recursion leads to infinite calls and results in
StackOverflowError.
Example: Factorial Using Recursion
int factorial(int n) {
if (n == 1) // base condition
return 1;
return n * factorial(n - 1); // recursive call
Step-by-Step Explanation (factorial of 4)
factorial(4)
= 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * 2 * factorial(1)
=4*3*2*1
= 24
factorial(1) stops recursion
Values are returned back step by step
Key Points
Method calls itself
Uses stack memory
Must contain a base condition
Simplifies problems like factorial, Fibonacci, tree traversal
Advantages of Recursion
Simple and clean code
Easy to understand complex problems
Reduces code length
Disadvantages of Recursion
Uses more memory (stack space)
Slower than iteration in some cases
Risk of StackOverflowError
Important Exam Notes
Recursion = function calling itself
Base condition is compulsory
Each call occupies stack memory
Summary
Recursion is a technique in which a method calls itself to solve a problem. It requires a base
condition to stop execution.
Access Control
Definition
Access control in Java determines the visibility and accessibility of classes, variables, methods,
and constructors. It is implemented using access modifiers.
Access control helps in:
Data hiding
Security
Proper encapsulation
Access Modifiers in Java
Java provides four access modifiers:
public
protected
default (no keyword)
private
Access Control Table
Modifier Same Class Same Package Subclass Outside
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ✖
default ✔ ✔ ✖ ✖
private ✔ ✖ ✖ ✖
Explanation of Each Access Modifier
1. public
Accessible from anywhere
No restriction on access
Example:
public int x;
public void show() {
📌 Used when members need to be globally accessible.
2. protected
Accessible within:
Same class
Same package
Subclasses (even in different packages)
Not accessible outside the package without inheritance
Example:
protected int y;
📌 Commonly used in inheritance.
3. default (Package-Private)
No keyword used
Accessible only within the same package
Example:
int z; // default access
📌 Used when access is required only within a package.
4. private
Accessible only within the same class
Most restrictive access level
Example:
private int a;
📌 Used for data hiding and encapsulation.
Important Rules
Access modifiers can be applied to:
Variables
Methods
Constructors
Classes (except private and protected for top-level classes)
Only one access modifier can be used at a time
private members are not inherited
Advantages of Access Control
Improves security
Prevents unauthorized access
Supports encapsulation
Enhances code maintainability
Summary
Access control in Java defines the visibility of class members using access modifiers such as
public, protected, default, and private.
Example
class AccessDemo {
public int pubVar = 10; // public
protected int protVar = 20; // protected
int defVar = 30; // default (no modifier)
private int privVar = 40; // private
// Method to display all variables
public void display() {
[Link]("Public Variable: " + pubVar);
[Link]("Protected Variable: " + protVar);
[Link]("Default Variable: " + defVar);
[Link]("Private Variable: " + privVar);
public static void main(String[] args) {
AccessDemo obj = new AccessDemo();
[Link]();
// Accessing variables directly
[Link]("\nDirect Access:");
[Link]("Public: " + [Link]);
[Link]("Protected: " + [Link]);
[Link]("Default: " + [Link]);
// [Link]("Private: " + [Link]); // ❌ Error: private variable
}
Output
Public Variable: 10
Protected Variable: 20
Default Variable: 30
Private Variable: 40
Direct Access:
Public: 10
Protected: 20
Default: 30
Explanation
public → accessible everywhere
protected → accessible in same package & subclasses
default → accessible only in same package
private → accessible only inside the class (display() method can access it)
✅ Note: Trying to access privVar outside the class directly will cause a compile-time error.
static
Definition
The static keyword is used to indicate that a class member (variable or method) belongs to the
class, rather than to any specific object of the class.
Static members are shared by all objects of the class.
They can be accessed without creating an object.
Features of static
Belongs to the class – shared by all objects
Memory efficient – only one copy exists in memory
Accessible without object – can be accessed using [Link]
Static methods cannot access non-static members directly
Syntax
class ClassName {
static int count; // static variable
static void method() {
// static method
}
}
Example
class Test {
static int count = 0; // static variable
Test() {
count++; // increment count whenever object is created
}
static void showCount() { // static method
[Link]("Count: " + count);
}
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test();
[Link](); // accessing static method without object
}
}
Output
Count: 3
Explanation
count is shared by all objects of Test class
Each time a new object is created, count is incremented
showCount() is static, so it can be called using the class name without creating an object
Key Points
Static members are class-level, not object-level
Only one copy exists in memory
Static methods cannot access non-static members directly
Useful for utility methods, counters, constants
Summary
The static keyword in Java is used to create class-level members that are shared by all objects
and can be accessed without creating an object.
final
Definition
The final keyword in Java is used to restrict modification.
Once something is declared as final, it cannot be changed (depending on the type: variable,
method, or class).
Uses of final
1. final Variable
Declares a constant whose value cannot be changed after initialization.
Must be initialized when declared or inside the constructor (for instance variables).
Example:
class Demo {
final int MAX = 100; // constant
void show() {
❌
[Link]("MAX = " + MAX);
// MAX = 200; // Error: cannot assign a value to final variable
}
}
2. final Method
A final method cannot be overridden by subclasses.
Useful to prevent modification of method behavior in child classes.
Example:
class Parent {
final void display() {
[Link]("This is a final method");
}
}
❌
class Child extends Parent {
// void display() { // Error: cannot override final method
// }
}
3. final Class
A final class cannot be inherited.
Useful to prevent subclassing for security or design reasons.
Example:
final class Constants {
int value = 10;
❌ Error: Cannot inherit from final class
}
// class Test extends Constants { //
// }
Key Points
final makes variables constants, methods un-overridable, and classes non-inheritable
Final variables must be initialized before use
Final methods improve security and maintain behavior consistency
Final classes are used in utility and helper classes (like [Link])
Summary
The final keyword in Java is used to restrict modification. It can make a variable constant,
prevent method overriding, and prevent class inheritance.
Arrays
Definition
An array is a container object in Java that can store multiple values of the same data type under
a single variable name.
Each value is called an element of the array.
Elements are stored in contiguous memory locations.
Array indices start from 0.
Key Features of Arrays
Store multiple values of the same type
Fixed size – size must be declared when created
Elements can be accessed using index
Can be single-dimensional or multi-dimensional
Syntax
dataType[] arrayName; // Declaration
arrayName = new dataType[size]; // Initialization
OR combined:
dataType[] arrayName = new dataType[size];
Direct initialization:
int arr[] = {1, 2, 3, 4};
Example: Single-Dimensional Array
class Demo {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4};
// Accessing elements
[Link]("First element: " + arr[0]);
[Link]("Third element: " + arr[2]);
// Using loop to print all elements
[Link]("Array elements: ");
for(int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
Output
First element: 1
Third element: 3
Array elements: 1 2 3 4
Explanation
arr is an array of integers
arr[0] refers to the first element
[Link] gives the size of the array
Using a loop, we can traverse all elements
Key Points
Arrays store elements of same type
Index starts from 0
Size is fixed at creation
Can be traversed using loops
Useful for storing related data efficiently
Multi-Dimensional Arrays
1. Declaration
dataType[][] arrayName;
dataType → type of elements (int, float, String, etc.)
[][] → indicates 2 dimensions
For 3D or higher, just add more []:
dataType[][][] arrayName; // 3-dimensional array
2. Initialization
Method 1: At the time of declaration
int matrix[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Method 2: Using new keyword
int matrix[][] = new int[3][3]; // 3 rows and 3 columns
3. Accessing Elements
matrix[0][1] = 10; // 0th row, 1st column
[Link](matrix[2][2]); // 2nd row, 2nd column
4. Traversing 2D Array Using Loops
for(int i = 0; i < [Link]; i++) { // rows
for(int j = 0; j < matrix[i].length; j++) { // columns
[Link](matrix[i][j] + " ");
[Link]();
Example Output (for matrix { {1,2,3}, {4,5,6}, {7,8,9} })
123
456
789
Key Points
Multi-dimensional arrays are arrays of arrays
Indexing starts from 0
[Link] → number of rows
array[i].length → number of columns in row i
Summary
An array in Java is a container object that stores multiple values of the same type under a single
variable name, accessible using indices starting from 0.
String Class
1. Definition
A String in Java is an object that represents a sequence of characters.
Strings are immutable, meaning once created, the content of a String cannot be changed.
Any operation that appears to modify a String creates a new String object.
2. Declaration of Strings
There are two ways to create strings:
(a) Using String Literals
String s1 = "Java";
Stored in String Pool (special memory area)
Reuses objects with the same content
(b) Using new Keyword
String s2 = new String("Java");
Creates a new object in heap memory
Does not use the String Pool
3. Immutability of Strings
Strings are immutable in Java.
Any modification (e.g., concatenation, substring) creates a new object.
String s = "Java";
[Link](" Programming"); // creates a new String, original s remains "Java"
[Link](s); // Output: Java
Reason for immutability:
Security (e.g., class loading, database URLs)
Thread safety
Performance with String Pool
4. String Pool
String literals are stored in a special memory area called String Pool.
When a literal is reused, Java does not create a new object, it reuses the existing one.
String s1 = "Java";
String s2 = "Java"; // s1 and s2 point to same object in pool
[Link](s1 == s2); // true (reference comparison)
Using new String("Java") always creates a new object in heap:
String s3 = new String("Java");
[Link](s1 == s3); // false
[Link]([Link](s3)); // true (content comparison)
5. Methods of String Class
i)length() → Returns the number of characters
String s = "Java";
[Link](); // 4
ii)charAt(int index) → Returns the character at the given index
[Link](1); // 'a'
iii)concat(String str) → Concatenates a string
[Link](" Programming"); // "Java Programming"
[J][a][v][a] + [ ][P][r][o][g][r][a][m][m][i][n][g]
equals(String str) → Compares the content of two strings
"Java".equals("java"); // false
Checks exact match (case-sensitive)
iv)equalsIgnoreCase(String str) → Compares ignoring case
"Java".equalsIgnoreCase("java"); // true
Ignores case differences
substring(int start, int end) → Returns substring
"Java".substring(1,3); // "av"
Includes start index, excludes end index
v)toUpperCase() → Converts all characters to uppercase
"java".toUpperCase(); // "JAVA"
vi)toLowerCase() → Converts all characters to lowercase
"JAVA".toLowerCase(); // "java"
viii)trim() → Removes leading & trailing spaces
" Java ".trim(); // "Java"
[ ][ ][J][a][v][a][ ][ ]
ix)replace(char old, char new) → Replaces all occurrences of a character
"Java".replace('a','o'); // "Jovo"
[J][a][v][a] → [J][o][v][o]
x)split(String regex) → Splits string into an array based on a delimiter
"a,b,c".split(","); // ["a","b","c"]
[a][,][b][,][c] → ["a","b","c"]
Important Notes
Strings are immutable → operations like concat(), replace(), substring() create new objects
== → checks reference equality
equals() → checks content equality
String Pool stores literals → reuses objects to save memory
For heavy modifications, use StringBuilder or StringBuffer (mutable alternatives)
6. Example Program – Demonstrating Methods
class Demo {
public static void main(String args[]) {
String s = "Java";
[Link]("String: " + s);
[Link]("Length: " + [Link]());
[Link]("Character at index 2: " + [Link](2));
[Link]("Concatenation: " + [Link](" Programming"));
[Link]("Equals 'Java': " + [Link]("Java"));
[Link]("Equals 'java': " + [Link]("java"));
[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());
[Link]("Substring(1,3): " + [Link](1,3));
[Link]("Replace 'a' with 'o': " + [Link]('a','o'));
}
Output
String: Java
Length: 4
Character at index 2: v
Concatenation: Java Programming
Equals 'Java': true
Equals 'java': false
Uppercase: JAVA
Lowercase: java
Substring(1,3): av
Replace 'a' with 'o': Jovo
7. Important Notes
Strings are immutable
== checks reference equality; equals() checks content equality
Strings can be concatenated using + operator
StringBuilder and StringBuffer are mutable alternatives for heavy string manipulation
8. Advantages of Using String Class
Easy to use
Provides many built-in methods for manipulation
Can be used as keys in hash maps (due to immutability)
Strings in String Pool save memory
Summary
A String in Java is an immutable object that stores a sequence of characters. Common methods
include length(), charAt(), concat(), and equals().
Command Line Arguments
1. Definition / Theory
Command Line Arguments are parameters passed to a Java program when it is executed.
They allow the program to accept input from the user at runtime without using Scanner or other
input methods.
Stored as an array of Strings (String[] args) in the main method.
They are optional; if no arguments are provided, the array is empty.
2. Syntax
public static void main(String args[])
args → an array of String objects, containing the command line arguments.
args[0] → first argument
args[1] → second argument, and so on.
Note: All arguments are stored as Strings. If you need numbers, you must convert them using
parsing methods like [Link]().
3. How It Works
When you run a Java program, you can pass arguments in the command line:
java Demo Hello World
The JVM passes these arguments to the main method:
args[0] = "Hello"
args[1] = "World"
The program can now use these arguments.
4. Example 1 – Simple Print
class Demo {
public static void main(String args[]) {
[Link]("First argument: " + args[0]);
}
}
Run Command:
java Demo Java
Output:
First argument: Java
Explanation:
"Java" is passed from the command line
args[0] stores "Java"
5. Example 2 – Multiple Arguments
class Demo {
public static void main(String args[]) {
[Link]("Number of arguments: " + [Link]);
for(int i = 0; i < [Link]; i++) {
[Link]("Argument " + i + ": " + args[i]);
}
}
}
Run Command:
java Demo Hello World 123
Output:
Number of arguments: 3
Argument 0: Hello
Argument 1: World
Argument 2: 123
Explanation:
[Link] → counts the number of command line arguments
Iterating over args[] prints each argument
6. Example 3 – Using Command Line Arguments as Numbers
class Demo {
public static void main(String args[]) {
int a = [Link](args[0]);
int b = [Link](args[1]);
[Link]("Sum: " + (a + b));
}
}
Run Command:
java Demo 10 20
Output:
Sum: 30
Explanation:
Command line arguments are Strings by default
Use [Link]() to convert to int for arithmetic operations
7. Key Points
Type: All command line arguments are Strings
Array: Stored in a String array: String[] args
Access: Use args[index] to access individual arguments
Length: [Link] → gives number of arguments
Conversion: Convert to numeric types if needed ([Link], [Link])
Optional: If no arguments are provided, [Link] = 0
8. Advantages of Command Line Arguments
Programs can take dynamic input at runtime without modifying code
Useful for small programs, scripts, utilities, and automation
Avoids the need for Scanner or GUI input
9. Summary
Command Line Arguments in Java are parameters passed to the program at runtime. They are
stored as a String array args[] in the main method. They allow dynamic input without using
Scanner.