KEMBAR78
JAVA Unit 1 | PDF | Java Virtual Machine | Java (Programming Language)
0% found this document useful (0 votes)
22 views67 pages

JAVA Unit 1

The document introduces Object-Oriented Programming (OOP) concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction, emphasizing their importance in software development. It also covers the history and evolution of Java, highlighting key milestones, features, and Java's unique characteristics known as buzzwords. Additionally, it explains the Java Virtual Machine (JVM) architecture, data types, and variable types in Java.
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)
22 views67 pages

JAVA Unit 1

The document introduces Object-Oriented Programming (OOP) concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction, emphasizing their importance in software development. It also covers the history and evolution of Java, highlighting key milestones, features, and Java's unique characteristics known as buzzwords. Additionally, it explains the Java Virtual Machine (JVM) architecture, data types, and variable types in Java.
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
You are on page 1/ 67

UNIT – 1

Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that focuses on


organizing software around objects rather than actions. It is based on real-world
entities and enhances code reusability, scalability, and maintainability.

Key Object-Oriented Concepts

1. Class and Object

• Class: A blueprint for creating objects. It defines attributes (data members)


and behaviors (methods).
• Object: An instance of a class that holds real values and can perform
operations.

Real-Time Example:
Think of a Car as a class. The car has attributes like color, model, and engine
capacity and behaviors like accelerate, brake, and honk.
Each specific car (e.g., "Honda City" or "Toyota Corolla") is an object of the Car
class.

2. Encapsulation (Data Hiding)

Encapsulation is the process of bundling data (variables) and methods (functions)


that operate on the data into a single unit (class). It restricts direct access to data to
ensure security.

Real-Time Example:
A bank account class has private data members like account balance and
account number. Only authorized methods (like deposit and withdraw) can modify
the balance, preventing unauthorized access.
3. Inheritance (Code Reusability)

Inheritance allows a new class (child) to acquire properties and behaviors of an


existing class (parent). This promotes code reusability.

Real-Time Example:
A Smartphone class may inherit properties from a Mobile Phone class, which
already has attributes like calling and messaging. The Smartphone class can
extend it with additional features like internet browsing and apps.

4. Polymorphism (Many Forms)

Polymorphism enables a method to perform different actions based on the object


that calls it. It can be method overloading (same method name with different
parameters) or method overriding (subclass providing its own implementation of a
method).

Real-Time Example:
A Printer class has a method print(). A Laser Printer and Inkjet Printer can
override this method to print in their own way.

5. Abstraction (Hiding Implementation Details)

Abstraction allows a class to expose only essential features while hiding the internal
implementation. This simplifies code complexity.

Real-Time Example:
When using an ATM machine, the user only sees options like withdraw, deposit,
and check balance. The internal processes (like database verification) are hidden.

History of Java

Introduction

Java is a high-level, object-oriented programming language developed by James


Gosling and his team at Sun Microsystems in 1991. It was initially designed for
interactive television but later evolved into a powerful, platform-independent
language widely used for web, mobile, and enterprise applications.

Key Milestones in Java Development

1. The Beginning (1991 - 1995)

• In 1991, James Gosling, Mike Sheridan, and Patrick Naughton started the
Green Project at Sun Microsystems.
• Their goal was to develop a language for embedded systems, such as smart
appliances and set-top boxes.
• Initially, the language was called Oak, named after an oak tree outside
Gosling’s office.
• Later, it was renamed Java, inspired by Java coffee beans, symbolizing
energy and productivity.
• In 1995, Sun Microsystems officially released Java 1.0, marking the beginning
of Java’s journey.

2. "Write Once, Run Anywhere" (WORA) Concept

• Java was designed to be platform-independent, meaning a program written


in Java can run on any system without modification.
• This was achieved using the Java Virtual Machine (JVM), which converts
Java code into platform-specific machine code.

3. Evolution of Java Versions

Java has gone through several versions, each introducing improvements and new
features.
Release
Version Key Features
Year

Java 1.0 1995 First official release with Applets and AWT.

Java 2 (J2SE 1.2 -


1998-2002 Swing, Collections Framework, JDBC.
1.4)

Java 5 (J2SE 5.0) 2004 Generics, Enhanced for-loop, AutoBoxing.

Performance improvements, Web Services


Java 6 2006
support.

Java 7 2011 Try-with-resources, NIO enhancements.

Lambda Expressions, Stream API, Date-Time


Java 8 2014
API.

Java 9 2017 Java Modules (Project Jigsaw).

Java 10-17 2018-2021 Performance updates, records, sealed classes.

Java 21 (Latest LTS Virtual threads, pattern matching, enhanced


2023
version) switch expressions.

4. Java’s Growth and Popularity

• Java became the foundation for Android app development.


• It is widely used in enterprise applications, web applications, and cloud
computing.
• With continuous updates and improvements, Java remains one of the most
powerful programming languages in the world.

Java Buzzwords

Introduction
Java is known for its unique characteristics, often referred to as Java Buzzwords.
These features make Java a powerful and widely used programming language.

1. Simple

• Java is easy to learn and has a clean syntax, similar to C++.


• Complex features like pointers and operator overloading are removed.
• Memory management is handled automatically using Garbage Collection.

2. Object-Oriented

• Java follows the Object-Oriented Programming (OOP) paradigm.


• Key OOP concepts: Encapsulation, Inheritance, Polymorphism, and
Abstraction.
• Everything in Java is treated as an object, improving modularity and code
reusability.

3. Platform-Independent

• Java follows the "Write Once, Run Anywhere" (WORA) concept.


• Java code is compiled into bytecode, which runs on any system with a Java
Virtual Machine (JVM).
• No need for platform-specific modifications.

4. Secure

• Java eliminates explicit memory pointers, preventing memory access


violations.
• It has a built-in security manager that defines access rules for applications.
• Java’s bytecode verification process ensures safe execution.

5. Robust (Strong & Reliable)


• Java has automatic memory management with Garbage Collection.
• It performs strong type-checking to prevent type mismatches.
• Exception handling ensures errors are managed properly without crashing
programs.

6. Multithreaded

• Java supports multiple threads to execute tasks concurrently.


• Multithreading improves performance, responsiveness, and efficiency.
• Java provides built-in support for threads using the Thread class and
Runnable interface.

7. Architecture-Neutral

• Java’s bytecode is independent of hardware architecture, allowing


portability.
• Programs run on any system with a JVM, regardless of OS or hardware.
• No need for separate versions for different platforms.

8. Portable

• Java programs can run on any system without modification.


• The JVM ensures consistent execution across different environments.
• Java libraries and APIs are designed to be cross-platform.

9. Interpreted

• Java is compiled into bytecode, which is then interpreted by the JVM.


• This approach makes Java faster than traditional interpreted languages
like Python.
• Java programs do not require full compilation before execution.

10. High Performance


• Java uses Just-In-Time (JIT) Compiler to optimize execution speed.
• Efficient memory management improves application performance.
• Though slightly slower than C++, Java’s performance is optimized for real-
time applications.

11. Distributed

• Java supports network-based applications using built-in APIs.


• Features like Remote Method Invocation (RMI) and CORBA enable
distributed computing.
• Java applications can communicate over the internet or local networks.

12. Dynamic

• Java supports dynamic class loading, meaning new classes can be added
at runtime.
• The Reflection API allows programs to inspect and modify themselves during
execution.
• Libraries and modules can be updated without recompiling the entire
program.

JVM Architecture (Java Virtual Machine)

Introduction

The Java Virtual Machine (JVM) is the core component of the Java Runtime
Environment (JRE) that enables Java applications to run on different platforms
without modification. It converts Java bytecode (compiled Java code) into
machine-specific code that the underlying operating system understands.

JVM follows the "Write Once, Run Anywhere" (WORA) principle, making Java
platform-independent. It provides crucial features like memory management,
garbage collection, and security.
JVM Architecture Overview

The JVM consists of three major components:

1. Class Loader Subsystem – Loads Java classes into memory.


2. Runtime Data Areas (JVM Memory) – Manages memory allocation for Java
programs.
3. Execution Engine – Converts bytecode into machine code and executes it.

1. Class Loader Subsystem

The Class Loader is responsible for loading Java classes into memory at runtime.

Phases of Class Loading

Loading:
• Reads the .class file (bytecode) from disk, network, or other sources.
• Converts the binary class file into a Class object in memory.

Linking:

• Verification: Ensures that the bytecode is valid and follows JVM rules.
• Preparation: Allocates memory for static variables and assigns default
values.
• Resolution: Converts symbolic references (method names, field names) into
actual memory addresses.

Initialization:

• Assigns values to static variables and executes static blocks.


• The first time a class is accessed, its static variables and blocks are
initialized.

Types of Class Loaders

1. Bootstrap Class Loader


o Loads core Java classes (e.g., java.lang.*, java.util.*).
o Uses the JVM's internal mechanism.
2. Extension Class Loader
o Loads classes from the lib/ext directory (e.g., security libraries, crypto
APIs).
3. Application Class Loader
o Loads classes from the user-defined classpath (e.g., C:\Program
Files\Java\MyProject).

2. Runtime Data Areas (JVM Memory)

JVM divides memory into several areas to manage program execution efficiently.

Method Area (Class Area)


• Stores class-related data, including metadata, method definitions, and static
variables.
• Shared among all threads.
• Loaded only once per class and remains in memory until the class is
unloaded.

Heap Memory

• Stores objects, instance variables, and reference variables.


• Managed by the Garbage Collector (GC) to free up unused memory.
• Divided into:
o Young Generation (Eden + Survivor Spaces) → For newly created
objects.
o Old Generation (Tenured Space) → For long-lived objects.
o Permanent Generation (Metaspace in Java 8+) → For class
metadata.

Java Stack Memory

• Stores method-specific information like:


o Local variables (e.g., int a = 5;).
o Method call details.
o Intermediate results.
• Each thread has its own stack.
• When a method is called, a stack frame is created; when the method ends,
the frame is removed.

PC Register (Program Counter Register)

• Stores the address of the currently executing instruction.


• Each thread has a separate PC register.

Native Method Stack


• Used for executing native (non-Java) code like C/C++ methods.
• Java applications use native methods through the Java Native Interface
(JNI).

3. Execution Engine

The Execution Engine is responsible for executing Java bytecode by converting it


into machine code.

Components of Execution Engine

1. Interpreter
o Reads and executes bytecode line by line.
o Faster startup but slower execution speed.
2. Just-In-Time (JIT) Compiler
o Converts entire bytecode into native machine code at runtime for
better performance.
o Stores compiled code in memory for faster reuse.
o Significantly improves execution speed over interpretation.
3. Garbage Collector (GC)
o Automatically removes unused objects from Heap Memory.
o Runs in the background to free memory without manual intervention.
o Uses algorithms like Mark and Sweep, Generational GC, and G1 GC.

JVM Workflow (Step-by-Step Execution Process)

1⃣ Compilation: The Java compiler (javac) compiles Java source code (.java) into
bytecode (.class).
2⃣ Class Loading: The Class Loader loads the bytecode into JVM memory.
3⃣ Bytecode Verification: The JVM verifies the bytecode to ensure security and
integrity.
4⃣ Execution: The Execution Engine interprets or compiles the bytecode into
machine code.
5⃣ Garbage Collection: The Garbage Collector (GC) manages memory by
removing unused objects.

DATA TYPES

Introduction

In Java, data types specify the type of value a variable can store. Java is a strongly
typed language, meaning every variable must be declared with a specific data type
before use.

Java has two main categories of data types:

1. Primitive Data Types (stores simple values like numbers, characters, or


boolean values)
2. Non-Primitive Data Types (stores complex objects like Strings, Arrays, and
Classes)

1. Primitive Data Types

Java provides 8 primitive data types that store fundamental values. These are:

Data Default
Size Description
Type Value

byte 1 byte 0 Stores small integers (-128 to 127)

2
short 0 Stores medium-sized integers (-32,768 to 32,767)
bytes
Data Default
Size Description
Type Value

4
int 0 Stores whole numbers (-2³¹ to 2³¹-1)
bytes

8
long 0L Stores large integers (-2⁶³ to 2⁶³-1)
bytes

4
float 0.0f Stores decimal numbers (up to 7 decimal places)
bytes

8 Stores precise decimal numbers (up to 15 decimal


double 0.0d
bytes places)

2
char '\u0000' Stores a single character (Unicode format)
bytes

boolean 1 bit false Stores only true or false values

1.1 Integer Data Types

byte → Used for memory-efficient applications, such as storing large arrays


where memory is crucial.
short → Rarely used but helpful in legacy systems that process numeric data.

int → The default integer type, widely used in Java programs.


long → Used for large numbers, such as bank transactions or scientific
calculations.

Example:

byte smallNumber = 120;


short mediumNumber = 15000;
int normalNumber = 100000;
long bigNumber = 1000000000L;
1.2 Floating-Point Data Types

float → Used for less precise calculations (e.g., graphics and game
development).
double → The default type for decimal numbers, used in scientific and
financial calculations.

float price = 10.99f; // 'f' suffix is required


double preciseValue = 99.99; // No suffix needed

1.3 Character and Boolean Data Types

char → Stores single characters, including letters, digits, and symbols. Uses
Unicode format (e.g., 'A', '@', '5').
boolean → Stores true or false, often used in decision-making and
conditional statements.

Example:

char grade = 'A';


boolean isJavaFun = true;

2. Non-Primitive Data Types

Non-primitive types store complex data structures and are not pre-defined in Java.

2.1 Strings

• A String is a sequence of characters.


• Unlike primitive types, String is an object in Java.

Example:
String message = "Hello, Java!";

2.2 Arrays

• An array is a collection of elements of the same data type.


• It has a fixed size and can store multiple values.

Example:

int[] numbers = {10, 20, 30, 40};


String[] names = {"John", "Alice", "Bob"};

2.3 Class and Object

• Class: A blueprint for creating objects.


• Object: An instance of a class.

Example:

class Car {
String brand = "Toyota";
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car(); // Creating an object
System.out.println(myCar.brand);
}
}

VARIABLES

Introduction
A variable in Java is a named memory location used to store data. Variables must
be declared before use, specifying their data type.

Java variables have two key aspects:

1. Scope – Defines where the variable can be accessed in the program.


2. Lifetime – Defines how long the variable exists in memory.

1. Types of Variables in Java

Java provides three types of variables based on their scope and lifetime:

1. Instance Variables (Non-Static Variables)


2. Static Variables (Class Variables)
3. Local Variables

1.1 Instance Variables (Non-Static Variables)

• Declared inside a class but outside any method.


• Each object gets its own copy of the instance variable.
• Scope: Available as long as the object exists.
• Lifetime: Exists until the object is garbage collected.
• Default Value: If not assigned, it takes default values (0 for numbers, null for
objects, false for boolean).

Example:

class Employee {
String name; // Instance variable
int age; // Instance variable

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
Employee emp1 = new Employee(); // Creating object
emp1.name = "Alice";
emp1.age = 25;
emp1.display(); // Output: Name: Alice, Age: 25
}
}

1.2 Static Variables (Class Variables)

• Declared with the static keyword inside a class but outside any method.
• Shared among all instances of the class (one copy per class).
• Scope: Available throughout the program.
• Lifetime: Exists until the program ends.

Example:

class Student {
static String school = "ABC School"; // Static variable

void display() {
System.out.println("School: " + school);
}
}

public class Main {


public static void main(String[] args) {
Student stu1 = new Student();
Student stu2 = new Student();

stu1.display(); // Output: School: ABC School


stu2.display(); // Output: School: ABC School
}
}
Since school is static, changing its value in one instance affects all instances.

1.3 Local Variables

• Declared inside a method, constructor, or block.


• Scope: Limited to the block where they are defined.
• Lifetime: Created when the block is executed and destroyed when the block
ends.
• No Default Value: Must be initialized before use.

Example:

class Test {
void display() {
int num = 10; // Local variable
System.out.println("Number: " + num);
}
}

public class Main {


public static void main(String[] args) {
Test obj = new Test();
obj.display(); // Output: Number: 10
}
}

Local variables cannot be accessed outside their method.

Scope of Variables in Java

The scope of a variable determines where it can be accessed in the program.

Block Scope
• Variable declared inside a block {} is accessible only within that block.
• Mostly used in loops and conditional statements.

Example:

public class Main {


public static void main(String[] args) {
if (true) {
int x = 10; // x is limited to this block
System.out.println("x inside block: " + x);
}
// System.out.println(x); // Error: x is out of scope
}
}

Method Scope

• A local variable inside a method is accessible only within that method.


• Once the method ends, the variable is destroyed.

Example:

class Test {
void show() {
int a = 50; // Method scope
System.out.println("a = " + a);
}
}

public class Main {


public static void main(String[] args) {
Test obj = new Test();
obj.show();
// System.out.println(a); // Error: a is not accessible outside show()
}
}
Class Scope (Instance and Static Variables)

• Instance variables belong to objects and can be accessed using this.


• Static variables belong to the class and can be accessed using
ClassName.variableName.

Example:

class Car {
String model; // Instance variable
static int wheels = 4; // Static variable

void display() {
System.out.println("Model: " + model);
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car();
myCar.model = "Toyota";
myCar.display();

System.out.println("Wheels: " + Car.wheels); // Accessing static variable


}
}

Lifetime of Variables in Java

The lifetime of a variable determines how long it exists in memory.

Variable Type Lifetime

Local Variable Created when the method starts, destroyed when it ends

Instance Variable Exists as long as the object exists (until garbage collection)
Variable Type Lifetime

Static Variable Exists throughout the program execution

1. Example: Local, Instance, and Static Variables

This program demonstrates all three types of variables:

Example: Understanding Scope and Lifetime of Variables

class Employee {
// Instance variable (exists as long as the object exists)
String name;

// Static variable (shared among all instances, exists throughout program execution)
static String company = "TechCorp";

void display() {
// Local variable (only exists during method execution)
int empID = 101;
System.out.println("Employee ID: " + empID);
System.out.println("Employee Name: " + name);
System.out.println("Company: " + company);
}
}

public class Main {


public static void main(String[] args) {
Employee emp1 = new Employee();
emp1.name = "Alice";
emp1.display(); // Calling method

Employee emp2 = new Employee();


emp2.name = "Bob";
emp2.display();

// Accessing static variable


System.out.println("Company (Static): " + Employee.company);
}
}

Output:

Employee ID: 101


Employee Name: Alice
Company: TechCorp

Employee ID: 101


Employee Name: Bob
Company: TechCorp

Company (Static): TechCorp

Explanation:

• empID is local, created when display() is called and destroyed after execution.
• name is an instance variable, each object has its own copy.
• company is static, shared across all objects.

2. Example: Block Scope

A variable declared inside a block {} is only accessible within that block.

Example: Block Scope

public class ScopeExample {


public static void main(String[] args) {
if (true) {
int x = 100; // x is limited to this block
System.out.println("Inside block: x = " + x);
}
// System.out.println(x); // Error: x is not accessible here
}
}
Output:

Inside block: x = 100

Key Takeaway:

• The variable x only exists inside the if block.


• If we try to access x outside the block, we get an error.

3. Example: Lifetime of Variables

This example shows how different types of variables exist for different durations.

Example: Variable Lifetime

class Test {
int instanceVar; // Instance variable (exists as long as object exists)
static int staticVar = 10; // Static variable (exists throughout the program)

void method() {
int localVar = 20; // Local variable (exists only within method)
System.out.println("Local Variable: " + localVar);
}
}

public class Main {


public static void main(String[] args) {
Test obj1 = new Test();
Test obj2 = new Test();

obj1.instanceVar = 5;
obj2.instanceVar = 15;

obj1.method(); // Calls the method, localVar is created and destroyed


obj2.method();

System.out.println("Instance Variable (obj1): " + obj1.instanceVar);


System.out.println("Instance Variable (obj2): " + obj2.instanceVar);
System.out.println("Static Variable: " + Test.staticVar);
}
}

Output:

Local Variable: 20
Local Variable: 20
Instance Variable (obj1): 5
Instance Variable (obj2): 15
Static Variable: 10

Key Takeaways:

• localVar is created when method() is called and destroyed after execution.


• instanceVar is different for each object (obj1 has 5, obj2 has 15).
• staticVar remains constant across all objects (10).

ARRAYS

Introduction

An array in Java is a collection of similar types of elements stored in contiguous


memory locations. It allows multiple values to be stored under a single variable
name.

Key Features of Arrays:

• Stores multiple values of the same data type.


• Fixed size (cannot be changed after declaration).
• Index-based access (first element starts at index 0).
• Stored in contiguous memory locations for fast access.
1. Declaring and Initializing Arrays

1.1 Declaring an Array

An array is declared using the data type followed by square brackets ([]).

Syntax:

datatype[] arrayName; // Recommended


// OR
datatype arrayName[]; // Valid but less preferred

Example:

int[] numbers; // Declares an array of integers


double[] prices; // Declares an array of doubles
String[] names; // Declares an array of Strings

1.2 Allocating Memory for an Array

After declaration, memory must be allocated using new.

Syntax:

arrayName = new datatype[size];

Example:

int[] numbers = new int[5]; // Allocates memory for 5 integers

1.3 Initializing an Array

Arrays can be initialized manually or at the time of declaration.

Example: Assigning values manually

int[] numbers = new int[3];


numbers[0] = 10; // Assigning values
numbers[1] = 20;
numbers[2] = 30;

Example: Declaring and initializing together

int[] numbers = {10, 20, 30}; // Array initialization

Example: Using new keyword

int[] numbers = new int[]{10, 20, 30};

2. Accessing Array Elements

Each element in an array is accessed using index values. The index starts from 0
and goes up to size - 1.

Example: Accessing Array Elements

public class ArrayExample {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

System.out.println("First Element: " + numbers[0]); // 10


System.out.println("Second Element: " + numbers[1]); // 20
}
}

Output:

First Element: 10
Second Element: 20

3. Types of Arrays in Java

3.1 Single-Dimensional Array


A 1D array stores elements in a single row.

Example: 1D Array

public class OneDArray {


public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20};

for (int i = 0; i < numbers.length; i++) {


System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}

Output:

Element at index 0: 5
Element at index 1: 10
Element at index 2: 15
Element at index 3: 20

3.2 Multi-Dimensional Arrays (2D Arrays)

A 2D array stores data in a table (rows & columns).

Syntax:

datatype[][] arrayName = new datatype[rows][columns];

Example: 2D Array (Matrix)

public class TwoDArray {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Output:

123
456
789

Key Takeaways:

• matrix[0][0] → 1, matrix[1][2] → 6, etc.


• Each row and column is accessed using two indices.

3.3 Jagged Arrays (Irregular Rows)

A jagged array is a 2D array with varying column sizes.

Example: Jagged Array

public class JaggedArray {


public static void main(String[] args) {
int[][] jagged = {
{1, 2},
{3, 4, 5},
{6}
};

for (int i = 0; i < jagged.length; i++) {


for (int j = 0; j < jagged[i].length; j++) {
System.out.print(jagged[i][j] + " ");
}
System.out.println();
}
}
}

Output:

12
345
6

Key Takeaway:

• The first row has 2 columns, the second row has 3 columns, and the third
row has 1 column.

4. Array Operations

4.1 Finding the Length of an Array

Use .length property to get the size of an array.

Example:

int[] arr = {5, 10, 15, 20};


System.out.println("Array Length: " + arr.length); // Output: 4

4.2 Copying an Array

Example: Using System.arraycopy()

int[] source = {1, 2, 3, 4, 5};


int[] destination = new int[5];

System.arraycopy(source, 0, destination, 0, source.length);


for (int num : destination) {
System.out.print(num + " ");
}

Output:

12345

5. Arrays and Memory Allocation

• Arrays are stored contiguously in memory.


• The size of an array cannot be changed dynamically.
• Java automatically initializes an array’s elements:
o Integers: 0
o Floats/Doubles: 0.0
o Booleans: false
o Objects: null

6. Enhanced For Loop (for-each loop)

A for-each loop simplifies array traversal.

Example:

int[] numbers = {10, 20, 30, 40};

for (int num : numbers) {


System.out.println(num);
}

Output:

10
20
30
40

OPERATORS

Introduction

Operators in Java are symbols that perform specific operations on variables and
values. These operations can be mathematical, logical, or used for assigning values.
Understanding operators is essential for writing efficient Java programs.

1. Types of Operators in Java

Java provides a variety of operators, categorized into the following types:

Operator Type Description

Perform basic mathematical operations such as addition,


Arithmetic Operators
subtraction, multiplication, and division.

Relational
(Comparison) Compare values and return a boolean result (true or false).
Operators

Used to perform logical operations, mostly in decision-


Logical Operators
making statements.

Perform operations at the bit level (used in low-level


Bitwise Operators
programming).

Assignment Operators Used to assign values to variables in different ways.

Operate on a single operand (e.g.,


Unary Operators
increment/decrement).

Ternary Operator A shortcut for if-else conditions.


Operator Type Description

Used to check if an object is an instance of a particular


Instanceof Operator
class.

Type Casting Operator Converts a value from one data type to another.

2. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical calculations.

Operator Description Example (a = 10, b = 5) Output

+ Addition a+b 15

- Subtraction a-b 5

* Multiplication a*b 50

/ Division (quotient) a/b 2

% Modulus (remainder) a % b 0

Example: Calculating the total price of items in a store

public class ArithmeticExample {


public static void main(String[] args) {
int item1 = 30, item2 = 50, quantity = 2;
int totalCost = (item1 + item2) * quantity;
System.out.println("Total Cost: " + totalCost);
}
}

Output:

Total Cost: 160


Division vs Modulus:

• / gives quotient (e.g., 10 / 3 = 3).


• % gives remainder (e.g., 10 % 3 = 1).

3. Relational (Comparison) Operators

These operators compare two values and return true or false.

Operator Description Example (a = 10, b = 5) Output

== Equal to a == b false

!= Not equal to a != b true

> Greater than a>b true

< Less than a<b false

>= Greater than or equal to a >= b true

<= Less than or equal to a <= b false

Example: Checking if a student passed an exam

public class ComparisonExample {


public static void main(String[] args) {
int passingMarks = 40, studentMarks = 35;
boolean hasPassed = studentMarks >= passingMarks;
System.out.println("Student passed: " + hasPassed);
}
}

Output:

Student passed: false


4. Logical Operators

Logical operators are used to perform boolean logic operations (true/false


conditions).

Example (a = true, b
Operator Description Output
= false)

Logical AND (both must


&& a && b false
be true)

Logical OR (at least one


` `
must be true)

Logical NOT (inverts the


! !a false
value)

Example: Checking if a user is eligible to vote

public class LogicalExample {


public static void main(String[] args) {
int age = 20;
boolean hasVoterID = true;
boolean canVote = (age >= 18) && hasVoterID;
System.out.println("Eligible to vote: " + canVote);
}
}

Output:

Eligible to vote: true

5. Assignment Operators

Used to assign values to variables.


Operator Example (a = 10) Equivalent to

= a = 10 a = 10

+= a += 5 a=a+5

-= a -= 5 a=a-5

*= a *= 5 a=a*5

/= a /= 5 a=a/5

%= a %= 5 a=a%5

Example: Salary increment calculation

public class AssignmentExample {


public static void main(String[] args) {
int salary = 50000;
salary += 5000; // Increase salary by 5000
System.out.println("New Salary: " + salary);
}
}

Output:

New Salary: 55000

6. Unary Operators

Unary operators operate on a single operand.

Operator Description Example (a = 10) Output

+ Positive sign +a 10

- Negative sign -a -10


Operator Description Example (a = 10) Output

++ Increment (increase by 1) ++a 11

-- Decrement (decrease by 1) --a 9

Example: Increment and decrement

int count = 5;
System.out.println(++count); // 6 (Pre-increment)
System.out.println(count--); // 6 (Post-decrement)
System.out.println(count); // 5

7. Ternary Operator

The ternary operator (? :) is a shortcut for if-else conditions.

Example:

int age = 18;


String eligibility = (age >= 18) ? "Eligible to Vote" : "Not Eligible";
System.out.println(eligibility);

Output:

Eligible to Vote

8. Bitwise Operators

These work at bit-level operations and are mostly used in low-level programming.

Example:

int a = 5, b = 3;
System.out.println(a & b); // Bitwise AND
System.out.println(a | b); // Bitwise OR
System.out.println(a ^ b); // Bitwise XOR

CONTROL STATEMENTS

Introduction

Control statements in Java are used to control the flow of execution in a program.
They allow decision-making, looping, and jumping to different sections based on
conditions. These statements improve efficiency by avoiding redundant code and
automating repetitive tasks. Java provides different types of control statements,
including decision-making statements, looping statements, and jump
statements.

Types of Control Statements

Control statements in Java are classified into three main categories:

1⃣ Decision-Making Statements → Used for conditional execution (if, if-else,


switch).
2⃣ Looping Statements → Used for repeated execution (for, while, do-while).
3⃣ Jump Statements → Used to alter control flow (break, continue, return).

1. Decision-Making Statements

Decision-making statements allow programs to execute different blocks of code


based on conditions. They help make logical choices, ensuring that the right code
executes in different scenarios.

a) if Statement
The if statement executes a block of code only if a specified condition is true. If
the condition is false, the program moves to the next statement outside the if block. It
is useful for validations, conditions, and logical operations in programs.

Syntax:

if (condition) {
// Code to execute if condition is true
}

Example: Checking if a number is positive

public class IfExample {


public static void main(String[] args) {
int num = 10;
if (num > 0) {
System.out.println("The number is positive.");
}
}
}

Output:

The number is positive.

b) if-else Statement

The if-else statement is an extension of the if statement. If the condition is true, the
if block executes; otherwise, the else block executes. It ensures that at least one
block of code runs based on the given condition.

Syntax:

if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example: Checking if a number is even or odd

public class IfElseExample {


public static void main(String[] args) {
int num = 7;
if (num % 2 == 0) {
System.out.println(num + " is Even.");
} else {
System.out.println(num + " is Odd.");
}
}
}

Output:

7 is Odd.

c) if-else-if Ladder

The if-else-if ladder is used when there are multiple conditions to evaluate. The
program checks conditions one by one, and the first true condition's block is
executed. If none of the conditions are true, the else block runs.

Syntax:

if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if all conditions are false
}

Example: Checking grade based on marks

public class GradeExample {


public static void main(String[] args) {
int marks = 85;
if (marks >= 90) {
System.out.println("Grade: A+");
} else if (marks >= 75) {
System.out.println("Grade: A");
} else if (marks >= 50) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: F");
}
}
}

Output:

Grade: A

d) switch Statement

The switch statement allows a program to execute one block of code from multiple
options. Instead of using multiple if-else statements, switch provides a more
structured and readable approach. Each case is checked, and if it matches the
expression, the corresponding block executes.

Syntax:

switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}

Example: Checking the day of the week


public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
default: System.out.println("Weekend");
}
}
}

Output:

Wednesday

2. Looping Statements (Iteration)

Looping statements execute a block of code multiple times based on a condition.


They are used when repetitive tasks need to be performed efficiently. There are
three types of loops in Java: for loop, while loop, and do-while loop.

a) for Loop

The for loop is used when the number of iterations is known in advance. It
consists of an initialization, condition, and update step, all in one line. This makes
it compact and easy to use for tasks like iterating over arrays.

Syntax:

for (initialization; condition; update) {


// Code to execute in each iteration
}

Example: Printing numbers from 1 to 5


public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}

Output:

1
2
3
4
5

b) while Loop

The while loop executes a block of code as long as the condition is true. It is useful
when the number of iterations is not known beforehand, like reading input from a
user.

Syntax:

while (condition) {
// Code to execute while condition is true
}

Example: Printing numbers from 1 to 5

public class WhileLoopExample {


public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
}
}

Output:

1
2
3
4
5

c) do-while Loop

The do-while loop executes the block at least once, even if the condition is false. It
is mainly used when a task should be executed at least once before checking a
condition.

Syntax:

do {
// Code to execute at least once
} while (condition);

Example: Printing numbers from 1 to 5

public class DoWhileExample {


public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}

Output:

1
2
3
4
5

TYPE CONVERSION AND CASTING

Introduction

In Java, data types determine the kind of values a variable can store. Sometimes, we
need to convert one data type into another to ensure compatibility between
operations. Java provides two ways to achieve this:

1⃣ Type Conversion (Implicit Type Casting or Widening)


2⃣ Type Casting (Explicit Type Casting or Narrowing)

1. Type Conversion (Implicit Type Casting or


Widening)

Type conversion happens automatically when a smaller data type is converted


into a larger data type. Since there is no risk of data loss, Java performs this
conversion without explicit instructions from the programmer.

Rules for Type Conversion:

• The destination type must be larger than the source type.


• No data should be lost during conversion.
• This process is also called widening conversion.

Conversion Hierarchy in Java:


byte → short → int → long → float → double

Example of Type Conversion:


public class TypeConversionExample {
public static void main(String[] args) {
int num = 10;
double result = num; // Automatic conversion from int to double
System.out.println("Integer value: " + num);
System.out.println("Converted to double: " + result);
}
}

Output:

Integer value: 10
Converted to double: 10.0

2. Type Casting (Explicit Type Casting or Narrowing)

Type casting is manually converting a larger data type into a smaller one. Since
this process may lead to data loss, it must be done explicitly by the programmer
using casting syntax.

Rules for Type Casting:

• The source type must be larger than the destination type.


• The programmer must use explicit casting ((datatype) value).
• Data loss or precision loss may occur.

Example of Type Casting:

public class TypeCastingExample {


public static void main(String[] args) {
double num = 10.99;
int result = (int) num; // Explicit casting from double to int
System.out.println("Double value: " + num);
System.out.println("Converted to integer: " + result);
}
}
Output:

Double value: 10.99


Converted to integer: 10

(Notice that the decimal part is lost.)

3. Difference Between Type Conversion and Type


Casting

Feature Type Conversion (Widening) Type Casting (Narrowing)

Performed by Java (Automatically) Programmer (Manually)

Data Flow Small → Large Large → Small

Risk of Data Loss No Yes

Example int → double double → int

4. Example: Both Type Conversion and Type


Casting

public class ConversionCastingExample {


public static void main(String[] args) {
// Implicit Type Conversion
int intValue = 50;
double doubleValue = intValue; // int to double (widening)
System.out.println("Widening (int to double): " + doubleValue);

// Explicit Type Casting


double anotherDouble = 99.99;
int castedInt = (int) anotherDouble; // double to int (narrowing)
System.out.println("Narrowing (double to int): " + castedInt);
}
}

Output:

Widening (int to double): 50.0


Narrowing (double to int): 99

Simple Java Program to Print "Hello, Java!"

// This is a simple Java program to print a message


public class HelloJava {
public static void main(String[] args) {
System.out.println("Hello, Java!"); // Printing output
}
}

Output:

Hello, Java!

Explanation of Each Part

1. Comments (// This is a simple Java program...)

• In Java, comments start with // and are ignored by the compiler.


• They help programmers understand the code easily.

2. public class HelloJava { ... } (Defining a Class)

• Every Java program must have a class, and the class name should match
the filename (HelloJava.java).
• A class is a blueprint that defines the behavior and properties of objects in
Java.
3. public static void main(String[] args) { ... } (Main Method)

• This is the entry point of any Java program. The JVM (Java Virtual Machine)
starts execution from here.
• Breakdown of each keyword:
o public → Makes the method accessible from anywhere.
o static → Allows execution without creating an object of the class.
o void → Means this method does not return a value.
o main(String[] args) → Standard method signature for Java programs.

4. System.out.println("Hello, Java!"); (Printing Output)

• System.out.println() is used to print text to the console.


• "Hello, Java!" is the message that will be displayed.
• println moves the cursor to the next line after printing, whereas print stays on
the same line.

CONSTRUCTORS

Introduction

A constructor is a special type of method in Java that is used to initialize objects.


It is automatically called when an object of a class is created. Unlike regular
methods, constructors do not have a return type (not even void).

1. Characteristics of a Constructor

The constructor name must be the same as the class name.


It does not return any value (not even void).

It is automatically called when an object is created.


It is mainly used to initialize instance variables.
2. Types of Constructors in Java

Java provides three types of constructors:


1⃣ Default Constructor (No-Argument Constructor)
2⃣ Parameterized Constructor
3⃣ Copy Constructor

3. Default Constructor (No-Argument Constructor)

A default constructor is a constructor without parameters. If a class does not


have a constructor, Java automatically provides a default constructor.

Example of a Default Constructor

class Student {
// Default Constructor
Student() {
System.out.println("Default Constructor Called!");
}

public static void main(String[] args) {


Student s1 = new Student(); // Constructor is called automatically
}
}

Output:

Default Constructor Called!

Explanation:

• The constructor Student() is called automatically when we create an object


(new Student();).
• It prints the message "Default Constructor Called!".
4. Parameterized Constructor

A parameterized constructor allows passing values while creating an object. This


is useful when we need to initialize instance variables with specific values.

Example of a Parameterized Constructor

class Student {
String name;
int age;

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

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


Student s1 = new Student("John", 20); // Passing values
s1.display();
}
}

Output:

Name: John, Age: 20

Explanation:

• The constructor Student(String n, int a) takes two parameters (name and age).
• When new Student("John", 20); is executed, the values "John" and 20 are assigned
to the instance variables.
5. Copy Constructor

A copy constructor creates a new object by copying values from an existing


object. Java does not provide a built-in copy constructor, so we define it manually.

Example of a Copy Constructor

class Student {
String name;
int age;

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

// Copy Constructor
Student(Student s) {
name = s.name;
age = s.age;
}

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


Student s1 = new Student("Alice", 22);
Student s2 = new Student(s1); // Copying object s1 into s2

s1.display();
s2.display();
}
}

Output:
Name: Alice, Age: 22
Name: Alice, Age: 22

Explanation:

• The constructor Student(Student s) takes another object (s) as a parameter and


copies its values.
• The object s2 is a copy of s1, having the same data.

6. Difference Between Constructor and Method

Feature Constructor Method

Name Same as class name Can have any name

Return Type No return type (not even void) Must have a return type

Called When? Automatically when object is created Manually when invoked

Purpose Initializes objects Performs operations

METHODS

Introduction

A method in Java is a block of code designed to perform a specific task. Instead of


repeating the same code multiple times, methods allow us to define logic once and
call it whenever needed. This helps in code reusability, readability, and modular
programming.

1. Characteristics of Methods
✔ Code Reusability – Avoids repeating the same code.

✔ Modular Approach – Breaks programs into smaller, manageable parts.


✔ Improves Readability – Makes programs easy to understand.

✔ Reduces Redundancy – Prevents duplication of logic.

2. Types of Methods in Java

Java methods can be divided into two categories:


1⃣ Predefined Methods (Built-in Methods) – Already available in Java (e.g.,
Math.sqrt(), System.out.println()).

2⃣ User-defined Methods – Created by programmers to perform specific tasks.

3. Defining and Calling a Method

A method in Java consists of:


Method Declaration – Defining the method with a name and parameters.

Method Body – The block of code executed when the method is called.
Method Invocation (Calling the Method) – Executing the method inside the
main() function.

Syntax of a Method in Java

returnType methodName(parameters) {
// Method body (set of statements)
return value; // (if applicable)
}

• returnType → The type of value returned by the method (e.g., int, String). Use
void if no value is returned.
• methodName → The name of the method (should be meaningful).
• parameters → Optional inputs that the method can accept.
4. Example: A Simple User-Defined Method

class MethodExample {
// Defining a method
void greet() {
System.out.println("Hello, welcome to Java!");
}

public static void main(String[] args) {


MethodExample obj = new MethodExample(); // Creating an object
obj.greet(); // Calling the method
}
}

Output:

Hello, welcome to Java!

Explanation:

• greet() is a user-defined method that prints a message.


• obj.greet(); calls the method inside main().
• The method executes when called and prints "Hello, welcome to Java!".

5. Types of User-Defined Methods

A. Method Without Parameters and Without Return Type

This type of method does not take any input parameters and does not return any
value.

class Demo {
void show() { // No parameters, No return type
System.out.println("This is a method without parameters.");
}

public static void main(String[] args) {


Demo obj = new Demo();
obj.show(); // Calling method
}
}

Output:

This is a method without parameters.

Explanation:

• The method show() is defined without parameters.


• It prints a message but does not return any value.
• obj.show(); calls the method, executing the print statement.

B. Method With Parameters and Without Return Type

This method accepts parameters but does not return any value.

class MathOperations {
void add(int a, int b) { // Method with parameters
System.out.println("Sum: " + (a + b));
}

public static void main(String[] args) {


MathOperations obj = new MathOperations();
obj.add(5, 10); // Passing arguments
}
}

Output:

Sum: 15

Explanation:
• The method add(int a, int b) accepts two integer parameters.
• The method adds the numbers and prints the result, but it does not return
any value.
• obj.add(5, 10); passes 5 and 10 as arguments to the method.

C. Method With Return Type and Parameters

This method accepts parameters and returns a value.

class Calculator {
int multiply(int x, int y) { // Method with return type
return x * y;
}

public static void main(String[] args) {


Calculator obj = new Calculator();
int result = obj.multiply(4, 3); // Storing return value
System.out.println("Multiplication: " + result);
}
}

Output:

Multiplication: 12

Explanation:

• The method multiply(int x, int y) accepts two numbers, multiplies them, and
returns the result.
• The returned value is stored in result and printed.

STATIC BLOCK, STATIC DATA, AND STATIC


METHODS

Introduction
The static keyword in Java is used to define class-level members, meaning they
belong to the class rather than to any specific object. static members can be
accessed without creating an object of the class.

1. Static Data (Static Variables)

A static variable is shared among all objects of the class because it belongs to the
class, not individual objects.

Characteristics of Static Variables

✔ Declared using the static keyword inside a class.

✔ Memory is allocated only once, at the time of class loading.


✔ All objects share the same copy of the static variable.

✔ Can be accessed using the class name (e.g., ClassName.variableName).

Example: Static Variable

class Student {
static String schoolName = "ABC School"; // Static Variable
String studentName;

Student(String name) {
this.studentName = name;
}

void display() {
System.out.println(studentName + " studies at " + schoolName);
}

public static void main(String[] args) {


Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
s1.display();
s2.display();

// Changing static variable


Student.schoolName = "XYZ School";
s1.display();
s2.display();
}
}

Output:

Alice studies at ABC School


Bob studies at ABC School
Alice studies at XYZ School
Bob studies at XYZ School

Explanation:

• schoolName is declared as static, so it is shared among all objects.


• When we change schoolName in main(), it affects all objects.

2. Static Methods

A static method belongs to the class rather than instances (objects) of the class.

Characteristics of Static Methods

✔ Declared using the static keyword.

✔ Can be called without creating an object.


✔ Can only access static variables and other static methods.

✔ Cannot use this or super, as it does not belong to an instance.

Example: Static Method

class MathOperations {
static int add(int a, int b) { // Static Method
return a + b;
}

public static void main(String[] args) {


// Calling static method without object
int sum = MathOperations.add(5, 10);
System.out.println("Sum: " + sum);
}
}

Output:

Sum: 15

Explanation:

• The method add(int a, int b) is static, so we call it using ClassName.methodName().


• No need to create an object of MathOperations.

3. Static Block

A static block is a special block in Java that executes before the main() method
when the class is loaded.

Characteristics of Static Block

✔ Used for initializing static variables.

✔ Executed only once, when the class is loaded into memory.


✔ Runs before the main method.

Example: Static Block

class StaticExample {
static int number;
// Static Block
static {
System.out.println("Static Block Executed!");
number = 10;
}

public static void main(String[] args) {


System.out.println("Main Method Executed!");
System.out.println("Static Variable: " + number);
}
}

Output:

Static Block Executed!


Main Method Executed!
Static Variable: 10

Explanation:

• The static block executes first, even before main().


• It initializes the static variable before using it in main().

4. Static Class (Nested Static Class)

In Java, a static class is a nested class declared with the static keyword inside
another class.

Example: Static Nested Class

class Outer {
static class Inner {
void show() {
System.out.println("Inside Static Inner Class");
}
}
public static void main(String[] args) {
Outer.Inner obj = new Outer.Inner(); // Creating object of static inner class
obj.show();
}
}

Output:

Inside Static Inner Class

Explanation:

• A static inner class can be accessed without creating an object of the outer
class.
• We can directly create an object of the static inner class using Outer.Inner.

5. When to Use static?

✔ Use static variables when data needs to be shared among all objects (e.g., a
common company name for employees).
✔ Use static methods for utility functions that don’t require object state (e.g.,
mathematical operations).
✔ Use static blocks to initialize static data before main().

6. Key Differences

Feature Static Variable Static Method Static Block

Stored once in class Stored in class No memory storage


Memory
memory memory (executes once)
Feature Static Variable Static Method Static Block

Accessed by class Called using class


Accessibility Executes automatically
name name

Available as long as the Executed only


Execution Executes before main()
class is loaded when called

Object Independent of
Independent of objects Independent of objects
Dependency objects

STRING AND STRINGBUFFER CLASSES

Introduction

In Java, strings are used to store and manipulate text. Java provides two primary
classes for handling strings:

1. String (Immutable)
2. StringBuffer (Mutable)

Each class has unique characteristics and use cases, which we will explore in detail.

1. String Class in Java

A String in Java is immutable, meaning once a string is created, its value cannot be
changed. If you modify a string, a new object is created instead of modifying the
existing one.

Characteristics of String Class

✔ Immutable – Once created, its value cannot be changed.


✔ Stored in String Pool – Helps in memory optimization.
✔ Concatenation creates a new object – Every modification results in a new string.

✔ Efficient for fixed values – Suitable for strings that do not change frequently.

Example: String is Immutable

class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
str1 = str1 + " World"; // Creates a new object

System.out.println(str1); // Output: Hello World


}
}

Output:

Hello World

Explanation:

• "Hello" is stored in memory.


• When " World" is added, a new string object "Hello World" is created.
• The original string "Hello" remains unchanged.

Common String Methods

Method Description Example

Returns the number of


length() "Hello".length() →5
characters in a string.

Returns character at specified


charAt(index) "Java".charAt(1) → 'a'
index.

"Hello".concat(" World") → "Hello


concat(str) Concatenates two strings.
World"

toUpperCase() Converts to uppercase. "java".toUpperCase() → "JAVA"


Method Description Example

toLowerCase() Converts to lowercase. "JAVA".toLowerCase() → "java"

substring(start, end) Extracts part of the string. "Hello".substring(1, 4) → "ell"

replace(old, new) Replaces characters. "Java".replace('a', 'o') → "Jovo"

equals(str) Compares two strings. "Java".equals("java") → false

Compares without case "Java".equalsIgnoreCase("java") →


equalsIgnoreCase(str)
sensitivity. true

2. StringBuffer Class in Java

A StringBuffer is mutable, meaning its value can be changed without creating a new
object. It is more efficient when dealing with frequent string modifications.

Characteristics of StringBuffer Class

✔ Mutable – Can be modified without creating new objects.

✔ Efficient for modifications – Faster than String for large text manipulations.
✔ Thread-Safe – Synchronization ensures safe usage in multi-threaded
environments.
✔ Allocated in Heap Memory – Unlike String, it does not use the String Pool.

Example: StringBuffer is Mutable

class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Modifies existing object

System.out.println(sb); // Output: Hello World


}
}
Output:

Hello World

Explanation:

• The StringBuffer object "Hello" is created.


• When " World" is appended, the same object is modified instead of creating a
new one.

Common StringBuffer Methods

Method Description Example

append(str) Adds a string at the end. sb.append(" Java") → "Hello Java"

Inserts at the specified


insert(index, str) sb.insert(5, "X") → "HelloX Java"
position.

replace(start, end,
Replaces part of the string. sb.replace(0, 5, "Hi") → "Hi Java"
str)

delete(start, end) Deletes a part of the string. sb.delete(2, 4) → "Heo Java"

reverse() Reverses the string. sb.reverse() → "avaJ oolleH"

sb.capacity() → Default is 16 + string


capacity() Returns buffer capacity.
length

3. Difference Between String and StringBuffer

Feature String StringBuffer

Mutability Immutable (unchangeable) Mutable (modifiable)


Feature String StringBuffer

Memory Creates a new object for every


Modifies the same object
Usage modification

Faster for multiple


Performance Slower for multiple changes
changes

Storage Stored in String Pool Stored in Heap Memory

Thread-Safety Not thread-safe Thread-safe

4. When to Use String and StringBuffer?

✔ Use String when the text is fixed or rarely modified (e.g., storing names,
messages).
✔ Use StringBuffer when modifying the text frequently (e.g., building dynamic
strings, concatenating large amounts of text).

5. Example: Comparing Performance of String and


StringBuffer

class PerformanceTest {
public static void main(String[] args) {
long startTime, endTime;

// String Performance Test


String str = "Java";
startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
str = str + " Programming"; // Creates new object every time
}
endTime = System.currentTimeMillis();
System.out.println("Time taken by String: " + (endTime - startTime) + "ms");

// StringBuffer Performance Test


StringBuffer sb = new StringBuffer("Java");
startTime = System.currentTimeMillis();
for (int i = 10000; i < 20000; i++) {
sb.append(" Programming"); // Modifies existing object
}
endTime = System.currentTimeMillis();
System.out.println("Time taken by StringBuffer: " + (endTime - startTime) + "ms");
}
}

Output (Time may vary):

Time taken by String: 400ms


Time taken by StringBuffer: 10ms

Explanation:

• String takes more time because new objects are created repeatedly.
• StringBuffer performs better as it modifies the same object.

You might also like