0% found this document useful (0 votes)
8 views35 pages

Features and JVM Architecture of Java

Java is a high-level, object-oriented, platform-independent programming language known for its simple syntax, scalability, and robust memory management. Key features include dynamic method dispatch, the Java Virtual Machine (JVM) architecture, and garbage collection, which enhances performance and memory efficiency. The language supports mobile and web application development, making it widely used across various platforms.

Uploaded by

RAMESH YADAV
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)
8 views35 pages

Features and JVM Architecture of Java

Java is a high-level, object-oriented, platform-independent programming language known for its simple syntax, scalability, and robust memory management. Key features include dynamic method dispatch, the Java Virtual Machine (JVM) architecture, and garbage collection, which enhances performance and memory efficiency. The language supports mobile and web application development, making it widely used across various platforms.

Uploaded by

RAMESH YADAV
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

Q.1. Explain the features of Java?

Ans.

Features of Java:-
Java is a high-level, object-oriented, platform-independent programming language developed
by Sun Microsystems (now owned by Oracle) in 1995.
It has several features that make it one of the most widely used programming languages in the
world.
1. Simple Syntax
Java syntax is very straightforward and very easy to learn. Java removes complex features like
pointers and multiple inheritance, which makes it a good choice for beginners.

2. Object-Oriented

 Everything in Java is treated as an object.

 Java is a pure object-oriented language. It supports core OOP concepts like,


 Class
 Objects
 Inheritance
 Encapsulation
 Abstraction
 Polymorphism
3. Platform Independent
Java is platform-independent because of Java Virtual Machine (JVM).
When we write Java code, it is first compiled by the compiler and then converted into bytecode
(which is platform-independent).
This byte code can run on any platform which has JVM installed.

 Work in (WORA) principle "Write Once, Run Anywhere.

4. Interpreted
Java code is not directly executed by the computer. It is first compiled into bytecode. This byte
code is then understand by the JVM. This enables Java to run on any platform without
rewriting code.
5. Scalable
Java can handle both small and large-scale applications. Java provides features like
multithreading and distributed computing that allows developers to manage loads more easily.
6. Portable
When we write a Java program, the code first get converted into bytecode and this bytecode
does not depend on any operating system or any specific computer. We can simply execute
this bytecode on any platform with the help of JVM. Since JVMs are available on most devices
and that's why we can run the same Java program on different platform
7. Secured and Robust
Java is a reliable programming language because it can catch mistakes early while writing the
code and also keeps checking for errors when the program is running. It also has a feature
called exception handling that helps deal with unexpected problems smoothly.
8. Memory Management
Memory management in Java is automatically handled by the Java Virtual Machine (JVM).
Java garbage collector reclaim memory from objects that are no longer needed.
Memory for objects are allocated in the heap
Method calls and local variables are stored in the stack.
9. High Performance
Java is faster than old interpreted languages. Java program is first converted into bytecode
which is faster than interpreted code. It is slower than fully compiled languages like C or C++
because of interpretation and JIT compilation process. Java performance is improve with the
help of Just-In-Time (JIT) compilation, which makes it faster than many interpreted languages
but not as fast as fully compiled languages.
10. Multithreading
Multithreading in Java allows multiple threads to run at the same time.
It improves CPU utilization and enhancing performance in applications that require concurrent
task execution.
Multithreading is especially important for interactive and high-performance applications, such
as games and real-time systems.
Java provides build in support for managing multiple threads. A thread is known as the smallest
unit of execution within a process.
11. Support for Mobile and Web Application
Java offers support for both web and mobile applications.
For web development: Java offers technologies like JSP and Servlets, along with frameworks
like Spring and Spring boot, which makes it easier to build web applications.
For mobile development: Java is the main language for Android app development. The Android
SDK uses special version of Java and its various tools to build mobile apps for Android devices.

Q.2. Write a program to demonstrate Dynamic Method Dispatching?


Dynamic Method Dispatch, also known as Runtime Polymorphism, is a core concept in Java's
object-oriented programming that allows the Java Virtual Machine (JVM) to determine which
version of an overridden method to execute at runtime. This mechanism is crucial for achieving
method overriding and supporting polymorphic behavior.
How it works:
 Method Overriding:
A subclass provides its own specific implementation of a method that is already
defined in its superclass. The method signature (name, parameters, and return type)
must be identical in both the superclass and subclass for overriding to occur.
 Upcasting:
A reference variable of a superclass type is made to refer to an object of a subclass
type. This is a common practice in polymorphism, allowing a single superclass
reference to point to various subclass objects.
 Runtime Resolution:
When an overridden method is invoked using a superclass reference that points to a
subclass object, the JVM dynamically determines which version of the method (from
the superclass or the specific subclass) to call based on the actual type of the object
being referred to at that moment, not the type of the reference variable.
Ex.
class Animal {

public void makeSound() {

[Link]("Animal makes a sound");

class Dog extends Animal {

@Override

public void makeSound() {

[Link]("Dog barks");

class Cat extends Animal {

@Override

public void makeSound() {

[Link]("Cat meows");

public class DynamicDispatchDemo {

public static void main(String[] args) {

Animal myAnimal; // Superclass reference

myAnimal = new Dog(); // myAnimal refers to a Dog object

[Link](); // Calls Dog's makeSound() - "Dog barks"

myAnimal = new Cat(); // myAnimal refers to a Cat object

[Link](); // Calls Cat's makeSound() - "Cat meows"

myAnimal = new Animal(); // myAnimal refers to an Animal object

[Link](); // Calls Animal's makeSound() - "Animal makes a sound"

}
Output:-

Dog barks

Cat meows

Animal makes a sound

Q.3. Describe the Java Virtual Machine (JVM) architecture and the role of bytecode?
How JVM Works - JVM Architecture

JVM (Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls
the main method present in a Java code. JVM is a part of JRE (Java Runtime Environment). Java
applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and expect it to run on any other Java-enabled system without
any adjustments. This is all possible because of the JVM. When we compile a .java file, .class files
(containing byte-code) with the same class names present in the .java file are generated by the
Java compiler. This .class file goes through various steps when we run it. These steps together
describe the whole JVM.
The image below demonstrates the architecture and key components of JVM.
Components Of JVM:-

Following are the core components of JVM:-

1. Class Loader Subsystem in JVM Architecture

The Class Loader Subsystem is a part of the JVM (Java Virtual Machine) responsible for
loading class files into memory and making them ready for execution.

It mainly performs three activities: Loading, Linking, and Initialization.


1. Loading

 The class loader loads the .class file (bytecode) into JVM memory.
 There are three types of class loaders:
1. Bootstrap Class Loader → Loads core Java classes ([Link], [Link], etc.).
2. Extension Class Loader → Loads classes from the ext (extension) directories.
3. Application (System) Class Loader → Loads classes from the classpath (user-
defined classes).
 If the class is not found, it throws ClassNotFoundException.

2. Linking

This step verifies and prepares the loaded class. It has three sub-steps:

1. Verification → Checks bytecode for correctness and security (no invalid code).
2. Preparation → Allocates memory for class-level variables (static variables) and assigns
default values.
3. Resolution → Replaces symbolic references (class/method/field names) with actual
memory references.

3. Initialization

 Assigns actual values to static variables.


 Executes static blocks of the class.
 Ensures that the class is fully ready to be used by the JVM.

2. JVM Memory Areas

 Method area: In the method area, all class level information like class name, immediate
parent class name, methods and variables information etc. are stored, including static
variables. There is only one method area per JVM, and it is a shared resource.
 Heap area: Information of all objects is stored in the heap area. There is also one Heap
Area per JVM. It is also a shared resource.
 Stack area: For every thread, JVM creates one run-time stack which is stored here. Every
block of this stack is called activation record/stack frame which stores methods calls. All
local variables of that method are stored in their corresponding frame. After a thread
terminates, its run-time stack will be destroyed by JVM. It is not a shared resource.
 PC Registers: Store address of current execution instruction of a thread. Obviously, each
thread has separate PC Registers.
 Native method stacks: For every thread, a separate native stack is created. It stores
native method information.
3. Execution Engine

Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses data
and information present in various memory area and executes instructions. It can be classified
into three parts:

 Interpreter: It interprets the bytecode line by line and then executes. The disadvantage
here is that when one method is ca lled multiple times, every time interpretation is
required.
 Just-In-Time Compiler(JIT): It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the interpreter
sees repeated method calls, JIT provides direct native code for that part so re-
interpretation is not required, thus efficiency is improved.
 Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector,
refer Garbage Collector.

5. Java Native Interface (JNI)


It is an interface that interacts with the Native Method Libraries and provides the native
libraries(C, C++) required fo` r the execution. It enables JVM to call C/C++ libraries and to
be called by C/C++ libraries which may be specific to hardware.
6. Native Method Libraries
These are collections of native libraries required for executing native methods. They include
libraries written in languages like C and C++.

Garbage Collection in Java

In Java, Garbage Collection (GC) is the process of automatically freeing memory by destroying objects
that are no longer in use (i.e., no reference is pointing to them).

It helps in memory management and prevents memory leaks.


In Java, the JVM automatically manages garbage collection using the Garbage Collector.

When does an object become eligible for Garbage Collection?

An object is eligible for GC when no reference variable points to it.


Example:

String s = new String("Hello");


s = null; // "Hello" object is now eligible for GC

Ways to make objects eligible for GC

1. Nulling a reference

Employee e = new Employee();


e = null; // object is ready for GC

2. Reassigning a reference

Employee e1 = new Employee();


Employee e2 = new Employee();
e1 = e2; // first object is now eligible for GC

3. Objects created inside a method

void show() {
Employee e = new Employee();
// after method ends, 'e' is destroyed → object becomes eligible for GC
}

Forcing Garbage Collection

We can request JVM to run Garbage Collector, but JVM may or may not run immediately.

[Link](); // Request garbage collection


[Link]().gc(); // Another way

Example Program

class Employee {
int id;
Employee(int id) {
[Link] = id;
}

// finalize() is called before object is garbage collected


protected void finalize() {
[Link]("Employee object with id " + id + " is garbage collected");
}
}

public class GarbageCollectionDemo {


public static void main(String[] args) {
Employee e1 = new Employee(101);
Employee e2 = new Employee(102);

// Making objects eligible for GC


e1 = null; // e1 is eligible
e2 = null; // e2 is eligible

// Requesting GC
[Link]();
}
}

Output (may vary depending on JVM):

Employee object with id 101 is garbage collected


Employee object with id 102 is garbage collected

Key Points for Exams:

 GC in Java is automatic (unlike C/C++ where you use free() or delete).


 JVM decides when to run GC.
 [Link]() is just a request.
 finalize() method is called before object is destroyed (but in modern Java, it is deprecated).

Super Keyword in Java


Definition:

In Java, super is a keyword that refers to the immediate parent class object.
It is mainly used when child (subclass) wants to access parent class methods, variables, or
constructors.

Uses of super keyword

1. To access parent class variable (when child class has same variable name).
2. To call parent class method (when overridden in child class).
3. To call parent class constructor (to reuse parent initialization).

Example 1: Accessing Parent Class Variable

class Parent {
int num = 100;
}

class Child extends Parent {


int num = 200;

void show() {
[Link]("Child num = " + num);
[Link]("Parent num = " + [Link]); // using super
}
}

public class SuperVariableDemo {


public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}

Output:

Child num = 200


Parent num = 100

Example 2: Calling Parent Class Method

class Parent {
void display() {
[Link]("Display from Parent class");
}
}

class Child extends Parent {


void display() {
[Link]("Display from Child class");
}

void show() {
[Link](); // calls parent method
}
}

public class SuperMethodDemo {


public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}

Output:
Display from Parent class

Example 3: Calling Parent Class Constructor

class Parent {
Parent() {
[Link]("Parent constructor called");
}
}

class Child extends Parent {


Child() {
super(); // calls parent constructor
[Link]("Child constructor called");
}
}

public class SuperConstructorDemo {


public static void main(String[] args) {
Child c = new Child();
}
}

Output:

Parent constructor called


Child constructor called

Final Exam-Point Notes

 super is used to refer immediate parent class object.


 3 main uses:
1. Access parent variable.
2. Call parent method.
3. Call parent constructor.
 Must be the first statement when used inside constructor.

Definition:
In Java, this is a reference variable in a class that refers to the current object of that class.
It is mainly used to avoid confusion between instance variables and local variables, and to call
methods/constructors of the same class.

Uses of this keyword

1. To refer current class instance variable (when local variable name is same as instance
variable).
2. To call current class method.
3. To call current class constructor (constructor chaining).
4. To pass current object as an argument in method/constructor.
5. To return current object from a method.

Example 1: Referring Instance Variable

class Student {

int id;

String name;

Student(int id, String name) {

[Link] = id; // 'this' refers to current object

[Link] = name;

void display() {

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

}
}

public class ThisVariableDemo {

public static void main(String[] args) {

Student s1 = new Student(101, "Ramesh");

[Link]();

Output:

101 Ramesh

Example 2: Calling Current Class Method

class Demo {

void display() {

[Link]("Display method called");

void show() {

[Link](); // calling current class method

}
public class ThisMethodDemo {

public static void main(String[] args) {

Demo d = new Demo();

[Link]();

Output:

Display method called

Example 3: Constructor Chaining (Calling another constructor)

class Person {

Person() {

this(20); // calling parameterized constructor

[Link]("Default constructor");

Person(int age) {

[Link]("Age: " + age);

public class ThisConstructorDemo {


public static void main(String[] args) {

Person p = new Person();

Output:

Age: 20

Default constructor

Static Keyword In Java


Definition:

In Java, the static keyword is used for memory management.


It belongs to the class rather than objects, which means:

 A static variable is shared by all objects of a class.


 A static method can be called without creating an object.
 A static block is executed only once when the class is loaded.

Uses of static keyword

1. Static variable → memory is shared by all objects.


2. Static method → can be called without object crea on.
3. Static block → used to initialize static data; runs once when class is loaded.(when object
is created / data member access by [Link])

Example 1: Static Variable

class Student {
int roll;

String name;

static String college = "BIT"; // static variable (shared by all)

Student(int roll, String name) {

[Link] = roll;

[Link] = name;

void display() {

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

public class StaticVariableDemo {

public static void main(String[] args) {

Student s1 = new Student(101, "Ramesh");

Student s2 = new Student(102, "Amit");

[Link]();

[Link]();

}
}

Output:

101 Ramesh BIT

102 Amit BIT

Example 2: Static Method

class Utility {

static void showMessage() {

[Link]("Hello! This is a static method.");

public class StaticMethodDemo {

public static void main(String[] args) {

[Link](); // no need to create object

Output:

Hello! This is a static method.

Example 3: Static Block

class Demo {
static int value;

// static block

static {

value = 100;

[Link]("Static block executed");

public class StaticBlockDemo {

public static void main(String[] args) {

[Link]("Value = " + [Link]);//

// Demo d = new Demo(); // object creation → loads class

Output:

Static block executed

Value = 100
final Keyword in Java
Definition:
The final keyword in Java is a non-access modifier used to apply restrictions on variables,
methods, and classes.

Once something is declared final, it cannot be changed.

Uses of final Keyword


1. Final Variable → value cannot be changed (acts like a constant).
2. Final Method → cannot be overridden by child classes.
3. Final Class → cannot be inherited.

Example 1: Final Variable


class Demo {
final int x = 10; // final variable

void display() {

// x = 20; ❌ Error: cannot assign a value to final variable


[Link]("x = " + x);
}
}

public class FinalVariableDemo {


public static void main(String[] args) {
Demo d = new Demo();
[Link]();
}
}
Output:
x = 10

Example 2: Final Method


class Parent {
final void show() {
[Link]("This is a final method.");
}
}

class Child extends Parent {

// void show() { ❌ Error: cannot override final method }


}

public class FinalMethodDemo {


public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}
Output:
This is a final method.

Example 3: Final Class


final class Vehicle {
void run() {
[Link]("Vehicle is running");
}
}

// class Car extends Vehicle { ❌ Error: cannot inherit from final class }

public class FinalClassDemo {


public static void main(String[] args) {
Vehicle v = new Vehicle();
[Link]();
}
}
Output:
Vehicle is running

Final Exam-Point Notes


 final keyword puts restrictions:
1. Final variable → constant (value cannot change).
2. Final method → cannot be overridden.
3. Final class → cannot be inherited.
 Helps in security, performance, and immutability.
Method Overriding in Java
Method Overriding in Java occurs when a subclass provides its own implementation of a
method that is already defined in the parent class with the same name, return type, and
parameters.

It is used to achieve runtime polymorphism (dynamic method dispatch).

Rules of Method Overriding

1. The method must have the same name, return type, and parameters as the parent
class method.
2. The method must be inherited (i.e., subclass and superclass relationship).
3. The access modifier cannot be more restrictive (e.g., parent method public → child
cannot make it private).
4. final, static, and private methods cannot be overridden.
5. Happens at runtime (not compile time).

Example: Method Overriding

class Animal {

void sound() {

[Link]("Animal makes a sound");

class Dog extends Animal {

// overriding parent method

void sound() {
[Link]("Dog barks");

public class MethodOverridingDemo {

public static void main(String[] args) {

Animal a = new Dog(); // upcasting

[Link](); // calls Dog's version at runtime

Output:

Dog barks

Explanation:

 The sound() method in Animal is overridden by the sound() method in Dog.


 At runtime, JVM decides which method to call (Dog’s method).
 This is an example of runtime polymorphism.

Final Exam-Point Notes

 Definition: Subclass redefines a parent class method with the same signature.
 Purpose: To provide a specific implementation.
Q.3. Describe the Java Virtual Machine (JVM) architecture and the role of bytecode?
Q.3. Describe the Java Virtual Machine (JVM) architecture and the role of bytecode?
Polymorphism,string,abstract class and interface, inheritance and method overriding
Q.3. Explain the advantages of using Interface in java. How they are different from Abstract
Class.
Or
List the differences between Abstract class and interface with suitable example.
Ans.

Abstract Class:-
An abstract class in Java is a class declared with the abstract keyword. It serves as a blueprint
for other classes and cannot be instantiated directly, meaning you cannot create objects of an
abstract class.
Key characteristics of abstract classes:
 Cannot be instantiated: You cannot use the new keyword to create an object of an
abstract class.
 Can contain abstract methods: These are methods declared without an implementation
(no method body), indicated by the abstract keyword. Subclasses extending an abstract
class must provide implementations for all inherited abstract methods, or they must
also be declared as abstract themselves.
 Can contain concrete (non-abstract) methods: Abstract classes can also have regular
methods with full implementations.
 Can have constructors: Although you cannot instantiate an abstract class, its
constructors can be called by the constructors of its subclasses during object creation.
 Used for abstraction: They are a core part of Java's abstraction mechanism, allowing
you to define common behaviors and properties for a group of related classes while
deferring specific implementations to their subclasses.
// Abstract class
abstract class Animal {
// Abstract method (no body)
abstract void sound();

// Concrete method (with body)


void eat() {
[Link]("This animal eats food.");
}
}
// Subclass (must implement abstract method)
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}

public class AbstractClassDemo {


public static void main(String[] args) {
// Animal a = new Animal(); // Cannot create object of abstract class
Animal myDog = new Dog(); // Upcasting
[Link](); // Calls Dog's implementation
[Link](); // Calls Animal's concrete method
}
}

Output:-
Dog barks
This animal eats food.

Interface:-
In Java, an interface is a collection of abstract methods (methods without a body) and
constants that can be implemented by any class. It defines a contract that the implementing
classes must follow.

Key Points

 A class implements an interface using the implements keyword.


 A class can implement multiple interfaces (supports multiple inheritance in Java).

Key characteristics of interfaces:


 Abstraction:
Interfaces primarily achieve abstraction by defining method signatures without
providing their implementations.
 Multiple Inheritance (Achieved through implementation):
While Java does not support multiple inheritance of classes, a class can implement
multiple interfaces, effectively achieving a form of multiple inheritance of behavior.
 Constants:
Interfaces can declare constants, which are implicitly public, static, and final.
 Default and Static Methods (Java 8+):
From Java 8 onwards, interfaces can include default methods (with implementations)
and static methods.
 Cannot be instantiated:
Interfaces cannot be directly instantiated. Instead, classes implement interfaces.
 No constructors:
Interfaces do not have constructors.
interface Animal {
void eat(); // abstract method
void sleep();
}

class Dog implements Animal {


public void eat() {
[Link]("Dog eats bones");
}
public void sleep() {
[Link]("Dog sleeps");
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Animal obj = new Dog();
[Link]();
[Link]();
}
}

output:
Dog eats bones
Dog sleeps
Advantages of Using Interface in Java
1. Achieves Multiple Inheritance
o Java does not support multiple inheritance with classes, but an interface allows a
class to implement multiple interfaces.
o This helps in designing flexible systems.
2. Provides Abstraction
o Interfaces contain only abstract methods (until Java 7), and from Java 8 onward,
they can also have default and static methods.
o This hides implementation details and shows only the required functionalities.
3. Supports Loose Coupling
o Interfaces allow classes to interact with each other through common methods
without knowing their actual implementation.
o This reduces dependency between classes.
4. Improves Testability and Maintenance
o Code written using interfaces is easier to test (mock implementations can be
used).
o Future changes in implementation do not affect the code that depends on the
interface.
5. Helps in Achieving Polymorphism
o With interfaces, we can use one reference type to point to different
implementations at runtime, enabling runtime polymorphism.
6. Standardization
o Interfaces define a contract or a standard set of methods.
o Any class implementing the interface must follow the same rules, which ensures
consistency.

Difference Between Abstract Class and Interface


Points Abstract Class Interface
Definition Cannot be instantiated; contains both Specifies a set of methods a class
abstract (without implementation) and must implement; methods are
concrete methods (with abstract by default.
implementation)
Implementation Can have both implemented and Methods are abstract by default;
Method abstract methods. Java 8, can have default and
static methods.

Inheritance class can inherit from only one abstract A class can implement multiple
class. interfaces.

Access Methods and properties can have any Methods and properties are
Modifiers access modifier (public, protected, implicitly public.
private).

Variables Can have member variables (final, non- Variables are implicitly public,
final, static, non-static). static, and final (constants).
"Differentiate between String, StringBuffer, and StringBuilder classes in Java with examples"

The String, StringBuffer, and StringBuilder classes in Java are all used to represent sequences of
characters, but they differ significantly in terms of mutability, thread safety, and performance.
1. String:
 Mutability:
String objects are immutable. Once a String object is created, its content cannot be
changed. Any operation that appears to modify a String (e.g., concatenation) actually
creates a new String object.
 Thread Safety:
String is inherently thread-safe due to its immutability. Multiple threads can access
a String object concurrently without causing data inconsistency.
 Performance:
Performance can be lower for frequent modifications or concatenations, as each
modification creates a new object, leading to increased memory allocation and
garbage collection.
 Example:
Java
String s = "Hello";
s = s + " World"; // Creates a new String object "Hello World"
[Link](s); // Output: Hello World
2. StringBuffer:
 Mutability:
StringBuffer objects are mutable. Their content can be modified after creation using
methods like append(), insert(), delete(), etc., without creating a new object.
 Thread Safety:
StringBuffer is thread-safe because its methods are synchronized. This means that only
one thread can access a StringBuffer object at a time, ensuring data consistency in
multi-threaded environments.
 Performance:
Due to synchronization overhead, StringBuffer is generally slower than StringBuilder in
single-threaded environments.
 Example:
Java
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Modifies the existing StringBuffer object
[Link](sb); // Output: Hello World
3. StringBuilder:
 Mutability:
StringBuilder objects are also mutable, similar to StringBuffer, allowing in-place
modifications using methods like append(), insert(), etc.
 Thread Safety:
StringBuilder is not thread-safe. Its methods are not synchronized, making it
unsuitable for use in multi-threaded environments where multiple threads might
concurrently modify the same StringBuilder object.
 Performance:
StringBuilder offers better performance than StringBuffer in single-threaded
environments due to the absence of synchronization overhead.
 Example:
Java
StringBuilder sbr = new StringBuilder("Hello");
[Link](" World"); // Modifies the existing StringBuilder object
[Link](sbr); // Output: Hello World

Difference Between String, StringBuilder, and StringBuffer

Features String StringBuilder StringBuffer

Introduction Introduced in JDK 1.0 Introduced in JDK 1.5 Introduced in JDK 1.0

Mutability Immutable Mutable Mutable

Thread Safety Thread Safe Not Thread Safe Thread Safe

Memory
High Efficient Less Efficient
Efficiency
Features String StringBuilder StringBuffer

Can be slower for High(No- Low(Due to


Performance many concatenations Synchronization) Synchronization)

This is used when This is used when


This is used when we
Thread safety is not Thread safety is
want immutability.
Usage required. required.

You might also like