[Go to site: main page, start]

0% found this document useful (0 votes)
14 views41 pages

Understanding Java Strings and Memory

Uploaded by

feret75857
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)
14 views41 pages

Understanding Java Strings and Memory

Uploaded by

feret75857
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

Java Strings

String is the type of object that can store a sequence of characters enclosed by double quotes and every
character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of
characters. Java provides a robust and flexible API for handling strings, allowing for various operations
such as concatenation, comparison and manipulation.

Example:

String name = "Geeks";


String num = "1234";

public class Geeks {// Main Function

public static void main(String args[]){// creating Java string using a new keyword

String str = new String("Geeks");

[Link](str);}}

Output

Geeks

Ways of Creating a Java String


There are two ways to create a string in Java:

1. String literal (Static Memory)

To make Java more memory efficient (because no new objects are created if it exists already in the string
constant pool).

Example:

String str = “GeeksforGeeks”;

2. Using new keyword (Heap Memory)

String s = new String("Welcome");


In such a case, JVM will create a new string object in normal (non-pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in the heap
(non-pool)

In the given example only one object will be created. Firstly JVM will not find any string object with the
value "Welcome" in the string constant pool, so it will create a new object. After that it will find the string
with the value "Welcome" in the pool, it will not create a new object but will return the reference to the
same instance.

Example:

String str = new String (“GeeksforGeeks”);

Interfaces and Classes in Strings in Java

CharSequence Interface

CharSequence Interface is used for representing the sequence of Characters in Java. Classes that are
implemented using the CharSequence interface are mentioned below and It provides basic methods such
as length(), charAt(), subSequence() and toString().

Classes that implement CharSequence include:

1. String

String is an immutable class in Java, which means that once a String object is created, its value cannot be
changed. If you want to modify a string a new String object is created and the original remains unchanged.

Syntax:

// Method 1
String str= "geeks";
// Method 2
String str= new String("geeks");

2. StringBuffer

StringBuffer is a peer class of String, it is mutable in nature and it is thread safe class , we can use it when
we have multi threaded environment and shared object of string buffer i.e, used by mutiple thread. As it is
thread safe so there is extra overhead, so it is mainly used for multithreaded program.

Syntax:

StringBuffer demoString = new StringBuffer("GeeksforGeeks");

3. StringBuilder

StringBuilder in Java represents an alternative to String and StringBuffer Class, as it creates a mutable
sequence of characters and it is not thread safe. It is used only within the thread , so there is no extra
overhead , so it is mainly used for single threaded program.

Syntax:

StringBuilder demoString = new StringBuilder();


[Link]("GFG");

4. StringTokenizer
StringTokenizer class in Java is used to break a string into tokens

A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations
advance this current position past the characters processed. A token is returned by taking a substring of the string
that was used to create the StringTokenizer object.

Syntax:

StringTokenizer st = new StringTokenizer("Java String Example");

Immutable String in Java

In Java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once a string object is
created its data or state can't be changed but a new string object is created.

import [Link].*;

class Geeks{ public static void main(String[] args){ String s = "Sachin";

// concat() method appends the string at the end

[Link](" Tendulkar");// This will print Sachin because strings are immutable objects

[Link](s);}}

Output

Sachin

Sachin is not changed but a new object is created with “Sachin Tendulkar”. That is why a string is known as
immutable.

As we can see in the given figure that two objects are created but s reference variable still refers to
"Sachin" and not to "Sachin Tendulkar". But if we explicitly assign it to the reference variable, it will refer to
the "Sachin Tendulkar" object.

Example: Java program to assign the reference explicitly in String using [Link]() method.

import [Link].*;

class Geeks{ public static void main(String[] args){

String name = "Sachin";


name = [Link](" Tendulkar");

[Link](name); }}

Output

Sachin Tendulkar

How Strings are Stored in Java Memory

String literal

Whenever a String Object is created as a literal, the object will be created in the String constant pool. This
allows JVM to optimize the initialization of String literal. The string constant pool is present in the heap.

Example 1: Using String literals to assigning char sequence value.

String str1 = "Hello";

string constant pool

Example 2: When we initialize the same char sequence using string literals.

String str1 = "Hello";


String str2 = "Hello";

string constant pool

Using new Keyword

The string can also be declared using a new operator i.e. dynamically allocated. In case of String are
dynamically allocated they are assigned a new memory location in the heap . This string will not be added
to the String constant pool.

Example 1: Using new keyword to assign a char sequence to a String object.

String str1 = new String("John"); String str2 = new String("Deo");

string constant pool

If we want to store this string in the constant pool then we will need to “intern” it.

Example 2: Using .intern() to add a string object in string constant pool.

// this will add the string to string constant pool.


String internedString = [Link]();

It is preferred to use String literals as it allows JVM to optimize memory allocation.

If we notice if we use new keyword or string literals both store the values in the string but the difference is
if we use the string literals or intern() the string object it will store the values in the string constant pool
which is present inside the heap as shown in the image.
Example that shows how to declare a String:

import [Link].*;

import [Link].*;

class Geeks{ public static void main(String[] args) { // Declare String without using new operator

String name = "GeeksforGeeks"; // Prints the String.

[Link]("String name = " + name); // Declare String using new operator

String newString = new String("GeeksforGeeks");// Prints the String.

[Link]("String newString = " + newString);}}

Output

String name = GeeksforGeeks

String newString = GeeksforGeeks

Note: String Object is created in Heap area and Literals are stored in special memory area known as
string constant pool.

String Pool Migration from PermGen to the Normal Heap

PermGen space is limited, the default size is just 64 MB. it was a problem with creating and storing too
many string objects in PermGen space. That's why the String pool was moved to a larger heap area. To
make Java more memory efficient, the concept of string literal is used. By the use of the 'new' keyword,
The JVM will create a new string object in the normal heap area even if the same string object is present in
the string pool.

For example:

String demoString = new String("Bhubaneswar");

Let us have a look at the concept with a Java program and visualize the actual JVM memory structure:

Below is the implementation of the above approach:

class Geeks { public static void main(String args[]) { // Declaring Strings using String literals

String s1 = "TAT";

String s2 = "TAT";

// Declaring Strings using new keyword

String s3 = new String("TAT");

String s4 = new String("TAT");

​// Printing all the Strings


[Link](s1);

[Link](s2);

[Link](s3);

[Link](s4);}}

Output

TAT

TAT

TAT

TAT

JVM Memory Area

Note: All objects in Java are stored in a heap. The reference variable is to the object stored in the stack
area or they can be contained in other objects which puts them in the heap area also.

Example 1:

class Geeks{public static void main(String args[]) {// Creating Byte ASCII Array

byte ascii[] = { 71, 70, 71 };// Creating String using byte array

String firstString = new String(ascii);

[Link](firstString);

​// Creating String using byte array with Start index to End Index

String secondString = new String(ascii, 1, 2);

[Link](secondString); }}

Output

GFG

FG

Example 2:

class Geeks{public static void main(String args[]) { // Character Array

char characters[] = { 'G', 'f', 'g' };// Creating new String using Character Array

String firstString = new String(characters);

// Creating new String using another String


String secondString = new String(firstString);

​[Link](firstString);

[Link](secondString);}}

Output

Gfg

Gfg

Why Java Strings are Immutable?

In Java, strings are immutable, meaning their values cannot be changed once created. If you try to
modify a string (e.g., using concat() or replace()), a new string object is created instead of altering the
original one.

Strings are stored in a String Pool, allowing reuse of objects and reducing memory overhead.
Multiple threads can safely share the same string object without synchronization.
Immutable strings have a consistent hash code, making them reliable for use in collections like
HashMap.

Example Demonstrating Immutability

public class GFG {

public static void main(String[] args) {

​// Both s1 and s2 refer to the same

// string literal in the String Pool

String s1 = "Hello";

String s2 = "Hello";

// true, both point to the same object in String Pool

[Link]("s1 == s2: " + (s1 == s2));

// Concatenation creates a new String

// object in heap, s1 now points to it

s1 = [Link](" World");

​[Link]("s1: " + s1);

[Link]("s2: " + s2);


[Link]("s1 == s2: " + (s1 == s2));

// Creating a string using new keyword stores it in the heap

String s3 = new String("Hello");

// false, because s2 is from String Pool and s3 is from heap

[Link]("s2 == s3: " + (s2 == s3));

// true, because equals() compares content

[Link]("[Link](s3): " + [Link](s3)) }}

Output

s1 == s2: true

s1: Hello World

s2: Hello

s1 == s2: false

s2 == s3: false

[Link](s3): true

Explanation:

s1 and s2 initially point to the same object in the String Pool.


After [Link](" World"), a new string object is created for "Hello World".
s3 is created using new String("Hello") and stored in the heap, separate from the String Pool.
== checks reference equality: s2 == s3 is false.
.equals() checks content equality, so [Link](s3) is true.

Why Strings Are Designed to Be Immutable

Memory Efficiency: The String Pool allows multiple references to share the same string object
safely.
Thread Safety: Immutable objects are inherently safe for multi-threaded access.
Hashcode Reliability: Strings are commonly used as keys in HashMap; immutability ensures the
hashcode remains consistent.
Performance Optimization: JVM can optimize immutable strings, including interning, which saves
memory and improves speed.

Java String concat() Method with Examples


The string concat() method concatenates (appends) a string to the end of another string. It
returns the combined string. It is used for string concatenation in Java. It returns
NullPointerException if any one of the strings is Null.

class GFG { public static void main(String args[]) {// String Initialization

String s = "Geeks";

// Use concat() method for string concatenation

s = [Link]("forGeeks");

[Link](s)}}

Output

GeeksforGeeks

Syntax of concat() Method

public String concat (String s);

Parameters:

A string to be concatenated at the end of the other string.

Return Value:

Concatenated(combined) string.

Exception:

NullPointerException: When either of the string is Null.

Java String concat() Examples

There are many ways to use the concat() method in Java:

Combining Two Strings with concat() Method

The below example combines two strings using concat() method of string class.

Example:

class GFG {public static void main(String args[]) {

​// String Initialization

String s1 = "Geeksfor";
String s2 = "Geeks";

// Concatenate the strings s1 and s2 using the concat() method and store the result back in s1.

s1 = [Link](s2);

[Link](s1); }}

Output

GeeksforGeeks

Sequential Concatenation of Multiple Strings

The below example shows sequential concatenation using String concat() method in Java.

Example:

public class GFG {

public static void main(String args[]) {

String s1 = "Computer-";

​String s2 = "Science-";

​// Combining above strings by passing one string as an argument

String s3 = [Link](s2);

// Print and display temporary combined string

[Link](s3);

String s4 = "Portal";

String s5 = [Link](s4);

[Link](s5);}}

Output

Computer-Science-

Computer-Science-Portal

Note: As perceived from the code we can do as many times as we want to concatenate strings
bypassing older strings with new strings to be contaminated as a parameter and storing the
resultant string in String datatype.
Handling NullPointerException in String concat()

The below example shows the NullPointerException in String concat() method.

Example:

public class GFG { public static void main(String args[]){

String s1 = "Computer-";

String s2 = null;

​// Combining above strings by passing one string as an argument

String s3 = [Link](s2);

// It will raise NullPointerException

[Link](s3); }}

Output

Exception in thread "main" [Link]

Reversing a String Using concat() Method

We can reverse a string using the concat() method of string class. Below is the example to
reverse a string in Java.

Example:

public class ReverseString {

public static void main(String[] args) {

// Declare original string variable

String a = "Geeks";

// Declare another string variable and initialize it with an empty string

String b = "";

​// Iterate through each character in string "a" from the last index to the first.

for (int i = [Link]() - 1; i >= 0; i--) {

// Extract the current character at index "i" of the "a" string


char ch = [Link](i);

// Convert the character to a String object using the "[Link]" method

String ch1 = [Link](ch);

// Concatenate the converted character String to the end of the "b" string

b = [Link](ch1); }

​[Link]("" + a);

[Link]("" + b);}}

Output

Geeks

skeeG

Java String Methods

In Java, a String represents a sequence of characters used for storing and manipulating text. It
is immutable and provides many built-in methods for operations like concatenation,
comparison, and manipulation.

public class Geeks{

public static void main(String[] args) {

String str = "GeeksforGeeks";

[Link]("Length: " + [Link]());

[Link]("Uppercase: " + [Link]());

[Link]("Substring: " + [Link](2, 6));

Output

Length: 13
Uppercase: GEEKSFORGEEKS

Substring: eksf

Commonly Used Java String Methods.

Java provides a rich set of String methods that help perform various operations like
comparison, searching, modification of string. Let's Understand one by one.

1. int length() Method

This method provides the total count of characters in the string.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]());

Output

13

2. charAt(int i) Method

This method returns the character at ith index.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link](7));

Output
W

3. String substring(int i) Method

This method return the substring from the ith index character to end.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link](7));

Output

World!

4. String substring(int i, int j) Method

This method returns the substring from i to j-1 index.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link](7, 12));

Output

World

5. String concat( String str) Method

This method appends the given string to the end of the current string.

public class Geeks {


public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]("!!!"));

Output

Hello, World!!!!

6. int indexOf(String s) Method

This method returns the index within the string of the first occurrence of the specified string.
If the specified string s is not found in the input string, the method returns -1 by default.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]("World"));

Output

7. int indexOf(String s, int i) Method

This method returns the index within the string of the first occurrence of the specified string,
starting at the specified index.

public class Geeks {

public static void main(String[] args) {

String str = "Hello, World!";

[Link]([Link]("l", 4));
}

Output

10

8. int lastIndexOf(String s) Method

This method returns the index within the string of the last occurrence of the specified string. If
the specified string s is not found in the input string, the method returns -1 by default.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]("l"));

Output

10

9. boolean equals(Object otherObj) Method

This method compares this string to the specified object.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]("Hello, World!"));

Output
true

10. boolean equalsIgnoreCase(String anotherString) Method

This method checks if two strings are equal, without considering letter case.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]("hello, world!"));

Output

true

11. int compareTo(String anotherString) Method

This method compares two string lexicographically.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]("Hello, Java!"));

Output

13

12. int compareToIgnoreCase(String anotherString) Method

This method compares two string lexicographically, ignoring case considerations.

public class Geeks {


public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]("hello, java!"));

Output

13

13. String toLowerCase() Method

This method converts all the characters in the String to lower case.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]());

Output

hello, world!

14. String toUpperCase() Method

This method converts all the characters in the String to upper case.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]());

}
}

Output

HELLO, WORLD!

15. String trim() Method

This method returns the copy of the String, by removing whitespaces at both ends. It does not
modify the whitespace characters present between the text.

public class Geeks {

public static void main(String[] args) {

String s = " Hello, Trim! ";

[Link]("'" + [Link]() + "'");

Output

'Hello, Trim!'

16. String replace(char oldChar, char newChar) Method

This method returns a new string where all instances of oldChar are replaced by newChar.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]('l', 'x'));

Output

Hexxo, Worxd!
17. boolean contains(CharSequence sequence) Method

This method returns true if string contains the given string.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]("World"));

Output

true

18. char[] toCharArray() Method

This method converts the string into a new character array.

public class Geeks {

public static void main(String[] args) {

String str = "Hello";

char[] chars = [Link]();

for(char c : chars) {

[Link](c + " ");

Output

Hello

19. boolean startsWith(String prefix) Method


This method returns true if string starts with this prefix.

public class Geeks {

public static void main(String[] args) {

String s = "Hello, World!";

[Link]([Link]("Hello"));

Output

true

Common String Methods in Java


String Methods Description

int length() Returns the number of characters in the String.

char charAt(int i) Returns the character at ith index.

String substring (int i) Return the substring from the ith index
character to end.

String substring (int i, int j) Returns the substring from i to j-1 index.

String concat( String str) Concatenates specified string to the end of this
string.

int indexOf (String s) Finds the position of the first occurrence of the
given substring within the main string. If the
specified string s is not found in the input
string, the method returns -1 by default.

int indexOf (String s, int i) Returns the index within the string of the first
occurrence of the specified string, starting at
the specified index.

int lastIndexOf( String s) Returns the index within the string of the last
occurrence of the specified string.
If the specified string s is not found in the input
string, the method returns -1 by default.

boolean equals( Object otherObj) Compares this string to the specified object.

boolean equalsIgnoreCase (String anotherString) Compares string to another string, ignoring


case considerations.

int compareTo( String anotherString) Compares two string lexicographically.

int compareToIgnoreCase( String anotherString) Compares two string lexicographically, ignoring


case considerations.

Note: In this case, it will not consider case of a


letter (it will ignore whether it is uppercase or
lowercase).

String toLowerCase() Converts all the characters in the String to


lower case.

String toUpperCase() Converts all the characters in the String to


upper case.

String trim() Returns the copy of the String, by removing


whitespaces at both ends. Whitespace
characters between words remain unchanged.

String replace (char oldChar, char newChar) Generates a new string where every instance of
oldChar is substituted with newChar.

Note: s1 is still feeksforfeeks and s2 is


geeksgorgeeks

boolean contains(CharSequence sequence) Returns true if string contains the given string.

Char[] toCharArray() Converts this String to a new character array.

boolean startsWith(String prefix) Return true if string starts with this prefix

String Class in Java

The String class in Java is used to create and manipulate sequences of characters. It is one of
the most commonly used classes in Java. Objects of the String class are immutable, which
means they cannot be changed once created

Key Features of the String Class

1. Immutable

Immutable means that once a String object is created, its value cannot be changed.

Example:

public class Main {

public static void main(String[] args) {

String text = "hello";


[Link](0) = 'H'; // compile-time error

Explanation: The line [Link](0) = 'H'; causes a compile-time error because charAt(0)
returns a read-only char, not a variable. String is immutable in Java, you cannot modify its
characters directly.

2. Thread-Safe

String in Java is thread-safe because it is immutable, allowing safe access by multiple threads
without synchronization.

3. Supports Various Utility Methods

String is a predefined final class in Java present in [Link] package. It provides various
methods to create, manipulate, and compare strings, like length(), charAt(), concat(), equals(),
etc.

import [Link].*;

class GFG {

public static void main (String[] args) {

String str = "hello geeks";

[Link]("Length of String-> "+[Link]());

[Link]("Changed String ->"+[Link]());

Output

Length of String-> 11

Changed String ->HELLO GEEKS

4. Implements Interfaces
The String class in Java implements three important interfaces.

CharSequence: Allows access to characters in the string using charAt(), length(), etc.
Comparable<String>: Enables comparing two strings lexicographically using compareTo()
Serializable: Allows string objects to be converted into a byte stream

String Constructors in Java

In Java, String constructors are used to create new String objects from different sources like
character arrays, byte arrays, or another string. Although strings in Java are usually created
using string literals, the String class also provides constructors for more control.

Let us check these constructors using a example demonstrating the use of them.

public class Geeks {

public static void main(String[] args) {

// Constructor 1: Creating string using new keyword

String str1 = new String("Hello Java");

[Link]("String using new keyword: " + str1);

// Constructor 2: Creating string from character array

char[] charArray = { 'J', 'A', 'V', 'A' };

String str2 = new String(charArray);

[Link]("String from char array: " + str2);

// Constructor 3: Creating string from byte array

byte[] byteArray = { 72, 101, 108, 108, 111 };

String str3 = new String(byteArray);

[Link]("String from byte array: " + str3);

}
Output

String using new keyword: Hello Java

String from char array: JAVA

String from byte array: Hello

String Constructors Table

String Constructors Description

String(byte[] byte_arr) Construct a new String by decoding the byte


array. It uses the platform's default character set
for decoding.

String(byte[] byte_arr, Charset char_set) Construct a new String by decoding the byte
array. It uses the char_set for decoding.

String(byte[] byte_arr, int start_index, int length) Construct a new string from the bytes array
depending on the start_index(Starting location)
and length(number of characters from starting
location).

String(byte[] byte_arr, int start_index, int length, Construct a new string from the bytes array
Charset char_set) depending on the start_index(Starting location)
and length(number of characters from starting
location).Uses char_set for decoding.

String(char[] char_arr) Allocates a new String from the given Character


array.

String(char[] char_array, int start_index, int count) Allocates a String from a given character array
but choose count characters from the
start_index.

String(int[] uni_code_points, int offset, int count) Allocates a String from a uni_code_array but
choose count characters from the start_index.

String(StringBuffer s_buffer) Allocates a new string from the string in s_buffer.

String(StringBuilder s_builder) Allocates a new string from the string in


s_builder.
StringBuffer Class in Java

StringBuffer class in Java represents a sequence of characters that can be modified, which
means we can change the content of the StringBuffer without creating a new object every
time. It represents a mutable sequence of characters.

Unlike String, we can modify the content of the StringBuffer without creating a new
object.
All methods of StringBuffer are synchronized, making it safe to use in multithreaded
environments.
Ideal for scenarios with frequent modifications like append, insert, delete or replace
operations.

Example: Here is an example of using StringBuffer to concatenate strings.

public class Geeks {

public static void main(String[] args){

// Creating StringBuffer

StringBuffer s = new StringBuffer();

// Adding elements in StringBuffer

[Link]("Hello");

[Link](" ");

[Link]("world");

// String with the StringBuffer value

String str = [Link]();

[Link](str);

Output

Hello world
StringBuffer

Constructors of StringBuffer Class

1. StringBuffer(): It reserves room for 16 characters without reallocation


2. StringBuffer(int size): It accepts an integer argument that explicitly sets the size of the
buffer.
3. StringBuffer(String str): It accepts a string argument that sets the initial contents of the
StringBuffer object and reserves room for 16 more characters without reallocation.

Example:

public class Geeks {

public static void main(String[] args) {

// 1. Using default constructor

StringBuffer sb1 = new StringBuffer();

[Link]("Hello");

[Link]("Default Constructor: " + sb1);

​// 2. Using constructor with specified capacity

StringBuffer sb2 = new StringBuffer(50);

[Link]("Java Programming");

[Link]("With Capacity 50: " + sb2);

​// 3. Using constructor with String

StringBuffer sb3 = new StringBuffer("Welcome");

[Link](" to Java");

[Link]("With String: " + sb3);

}
}

Output

Default Constructor: Hello

With Capacity 50: Java Programming

With String: Welcome to Java

Implementation of Java StringBuffer Method

1. append() Method

append() method concatenates the given argument with this string.

import [Link].*;

class Geeks {

public static void main(String args[])

StringBuffer sb = new StringBuffer("Hello ");

[Link]("Java"); // now original string is changed

[Link](sb);

Output

Hello Java

2. insert() Method

insert() method inserts the given string with this string at the given position.

import [Link].*;
class Geeks {

public static void main(String args[])

StringBuffer sb = new StringBuffer("Hello ");

[Link](1, "Java");

// Now original string is changed

[Link](sb);

Output

HJavaello

3. replace() Method

replace() method replaces the given string from the specified beginIndex and endIndex-1.

import [Link].*;

class Geeks {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer("Hello");

[Link](1, 3, "Java");

[Link](sb);

}
Output

HJavalo

4. delete() Method

delete() method is used to delete the string from the specified beginIndex to endIndex-1.

import [Link].*;

class Geeks {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer("Hello");

[Link](1, 3);

[Link](sb);

Output

Hlo

5. reverse() Method

reverse() method of the StringBuffer class reverses the current string.

import [Link].* ;

class Geeks {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer("Hello");

[Link]();
[Link](sb);

Output

olleH

6. capacity() Method

capacity() method of the StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of characters increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2.

For example, if the current capacity is 16, it will be (16*2)+2=34.

import [Link].*;

class Geeks {

public static void main(String args[])

StringBuffer sb = new StringBuffer();

// default 16

[Link]([Link]());

[Link]("Hello");

// now 16

[Link]([Link]());

[Link]("java is my favourite language");


// (oldcapacity*2)+2

[Link]([Link]());

Output

16

16

34

7. length()

This method return the number of character in given string.

import [Link].*;

class Geeks {

public static void main(String[] args) {

// Creating and storing string by creating object of StringBuffer

StringBuffer s = new StringBuffer("GeeksforGeeks");

// Getting the length of the string

int p = [Link]();

// Getting the capacity of the string

[Link]("Length of string GeeksforGeeks=" + p);

}
}

Output

Length of string GeeksforGeeks=13

StringBuilder Class in Java

In Java, the StringBuilder class (part of the [Link] package) provides a mutable sequence of
characters. Unlike the String class (which is immutable), StringBuilder allows modification of character
sequences without creating new objects, making it memory-efficient and faster for frequent string
operations.

It provides similar functionality to StringBuffer, but without thread safety.


StringBuilder is not synchronized, so it performs better in single-threaded applications.
Use StringBuffer only when thread safety is required; otherwise, prefer StringBuilder for improved
performance.

Declaration:

StringBuilder sb = new StringBuilder("Initial String");

StringBuilder Class

Example: : Basic Demonstration of StringBuilder

public class Geeks {

public static void main(String[] args) {

StringBuilder sb = new StringBuilder("GeeksforGeeks");

[Link]("Initial StringBuilder: " + sb);

[Link](" is awesome!");

[Link]("After append: " + sb);

Output
Initial StringBuilder: GeeksforGeeks

After append: GeeksforGeeks is awesome!

The append() method adds the given string to the end of the existing sequence without creating a new
object. This makes StringBuilder efficient for concatenation operations.

StringBuilder Constructors

StringBuilder class provides multiple constructors for different use cases.

1. StringBuilder() : Creates an empty builder with a default capacity of 16 characters.


2. StringBuilder(int capacity) : Creates an empty builder with a specified initial capacity.
3. StringBuilder(String str) : Initializes the builder with the content of the given String.
4. StringBuilder(CharSequence cs) : Initializes the builder with the given CharSequence (for example,
String or StringBuffer).

Example:

public class StringBuilderConstructorsDemo {

public static void main(String[] args) {

StringBuilder sb1 = new StringBuilder();

[Link]("Hello");

[Link]("sb1: " + sb1);

StringBuilder sb2 = new StringBuilder(50);

[Link]("This has initial capacity 50");

[Link]("sb2: " + sb2);

StringBuilder sb3 = new StringBuilder("Geeks");

[Link]("ForGeeks");

[Link]("sb3: " + sb3);

CharSequence cs = "Java";
StringBuilder sb4 = new StringBuilder(cs);

[Link]("Programming");

[Link]("sb4: " + sb4);

Output

sb1: Hello

sb2: This has initial capacity 50

sb3: GeeksForGeeks

sb4: JavaProgramming

Commonly Used Methods in StringBuilder

The StringBuilder class provides various methods for string manipulation.

Example: Using StringBuilder Methods

public class Geeks {

public static void main(String[] args) {

StringBuilder sb = new StringBuilder("GeeksforGeeks");

[Link]("Initial: " + sb);

[Link](" is awesome!");

[Link]("After append: " + sb);

[Link](13, " Java");

[Link]("After insert: " + sb);


[Link](0, 5, "Welcome to");

[Link]("After replace: " + sb);

[Link](8, 14);

[Link]("After delete: " + sb);

[Link]();

[Link]("After reverse: " + sb);

[Link]("Capacity: " + [Link]());

[Link]("Length: " + [Link]());

char c = [Link](5);

[Link]("Character at index 5: " + c);

[Link](5, 'X');

[Link]("After setCharAt: " + sb);

String sub = [Link](5, 10);

[Link]("Substring (5–10): " + sub);

[Link](); // Revert for search

[Link]("Index of 'Geeks': " + [Link]("Geeks"));

[Link](5);
[Link]("After deleteCharAt: " + sb);

String result = [Link]();

[Link]("Final String: " + result);

Output:

Initial: GeeksforGeeks
After append: GeeksforGeeks is awesome!
After insert: GeeksforGeeks Java is awesome!
After replace: Welcome toforGeeks Java is awesome!
After delete: Welcome eeks Java is awesome!
After reverse: !emosewa si avaJ skee emocleW
Capacity: 60
Length: 29
Character at index 5: e
After setCharAt: !emosXwa si avaJ skee emocleW
Substring (5?10): Xwa s
Index of 'Geeks': -1
After deleteCharAt: Welcoe eeks Java is awXsome!
Final String: Welcoe eeks Java is awXsome!

In the above program, we use different methods of the StringBuilder class to perform different string
manipulation operations such as append(), insert(), reverse() and delete().

Important StringBuilder Methods


Method Description Example

append(String str) Appends the specified string to [Link]("Geeks");


the end of the StringBuilder.

insert(int offset, String) Inserts the specified string at the [Link](5, " Geeks");
given position in the StringBuilder.

replace(int start, int end, Replaces characters in a substring [Link](6, 11, "Geeks");
String) with the specified string.

delete(int start, int end) Removes characters in the [Link](5, 11);


specified range.

reverse() Reverses the sequence of [Link]();


characters in the StringBuilder.

capacity() Returns the current capacity of int cap = [Link]();


the StringBuilder.

length() Returns the number of characters int len = [Link]();


in the StringBuilder.

charAt(int index) Returns the character at the char ch = [Link](4);


specified index.

setCharAt(int index, char) Replaces the character at the [Link](0, 'G');


specified position with a new
character.

substring(int start, int end) Returns a new String that contains String sub = [Link](0, 5);
characters from the specified
range.

ensureCapacity(int minimum) Ensures the capacity of the [Link](50);


StringBuilder is at least equal to
the specified minimum.

deleteCharAt(int index) Removes the character at the [Link](3);


specified position.

indexOf(String str) Returns the index of the first int idx = [Link]("Geeks");
occurrence of the specified string.
lastIndexOf(String str) Returns the index of the last int idx = [Link]("Geeks");
occurrence of the specified string.

toString() Converts the StringBuilder object String result = [Link]();


to a String.

StringBuilder vs String vs StringBuffer

The table below demonstrates the difference between String, StringBuilder and StringBuffer:

Features String StringBuilder StringBuffer

Mutability String are StringBuilder are StringBuffer are


immutable(creat mutable(modifies mutable
es new objects in place) (modifies in
on modification) place)

Thread-Safe It is thread-safe It is not thread- It is thread-safe


safe

Performance It is slow because It is faster (no It is slower due to


it creates an object creation) synchronization
object each time overhead

Use Case Fixed, Single-threaded Multi-threaded


unchanging string string
strings manipulation manipulation

Common questions

Powered by AI

StringBuilder is beneficial over String when frequent modifications are needed, as it is mutable and provides faster performance due to its in-place modifications, avoiding the creation of multiple objects . However, a drawback is that StringBuilder is not thread-safe, making it unsuitable for multi-threaded environments where synchronization might be necessary .

These methods are beneficial when anticipating a large number of concatenation or modification operations on strings. For example, in a log collector appending a large number of log messages, ensureCapacity() can pre-allocate space to reduce the frequency of resizing operations, improving performance .

Choosing between StringBuffer and StringBuilder depends on the application's thread requirements. StringBuffer is suitable for multi-threaded environments due to its thread safety with synchronized methods, whereas StringBuilder is more efficient for single-threaded applications, providing faster performance due to its lack of synchronization .

String is immutable and inherently thread-safe, which can lead to slower performance due to object creation on each modification . StringBuffer is mutable and thread-safe through synchronized methods but has slower performance than StringBuilder due to synchronization overhead. StringBuilder is mutable and offers faster performance due to its lack of thread safety, making it suitable for single-threaded applications .

Using the new keyword for string creation allocates memory for each string in the heap, even if an identical string exists in the String Pool, leading to higher memory usage . In contrast, string literals allow strings to be stored in the String Pool, enabling memory sharing and reuse, which is more efficient .

The string constant pool is a special area in memory where the JVM stores string literals to save memory by reusing instances. When a string is interned using the intern() method, it adds or references the string object in the string constant pool, allowing the JVM to share the instance among strings with the same value, thereby optimizing memory allocation .

StringTokenizer is used to break strings into tokens based on delimiters, maintaining an internal position for tracking . However, it has limitations such as not supporting regular expressions, being less flexible, and being considered obsolete due to newer classes like String.split() or regular expressions that provide greater functionality and ease of use for complex string parsing operations .

String immutability ensures that once a string's hashcode is computed, it remains consistent, which is crucial for collections like HashMap. It allows strings to be used safely as keys without the risk of hashcode changes causing lookup issues or misplacing entries within the map .

Java's design of immutable strings and the use of the String Pool contribute to performance optimization by reducing memory usage and enhancing memory management. Immutable strings prevent changes, enabling safe sharing among threads and fostering reusability within the String Pool, while pooling ensures that identical literals share a single memory reference, optimizing both memory allocation and access speed .

Immutable strings in Java enhance memory efficiency by allowing the String Pool to reuse string objects, which reduces memory overhead. Since strings cannot be modified once created, this ensures that multiple threads can safely share the same string object without requiring synchronization, thus maintaining thread safety and reducing concurrency issues .

You might also like