0% found this document useful (0 votes)
3 views

String ,String Buffer& String Buileder

The document provides an overview of string handling in Java, detailing the characteristics of strings, including their immutability and methods for creation. It explains the differences between String, StringBuffer, and StringBuilder, highlighting their use cases and performance implications. Additionally, it lists various methods available for string manipulation, such as length(), charAt(), substring(), and more, along with examples of their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

String ,String Buffer& String Buileder

The document provides an overview of string handling in Java, detailing the characteristics of strings, including their immutability and methods for creation. It explains the differences between String, StringBuffer, and StringBuilder, highlighting their use cases and performance implications. Additionally, it lists various methods available for string manipulation, such as length(), charAt(), substring(), and more, along with examples of their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

A string in Java is a sequence of characters stored using UTF-16 encoding, where every character occupies 16 bits.

In
Java, strings are immutable, meaning once created, their content cannot be changed once created.

Creating a String in Java

There are four ways to create a string in Java:

1. Using Character Array / ArrayList - Strings can be created by initializing a character array. For example:

char[] arr = ['g', 'e', 'e', 'k', 's'];

Here, each character of the string is stored in an array format.

2. Using the String Class - The String class creates immutable strings. Once a string is created, its content cannot be
modified. Operations like concatenation or changing the case of a string will create a new string object.

 String literal

String s = “GeeksforGeeks”;

A literal creates a string in the String Pool.

 Using new keyword

String s = new String (“GeeksforGeeks”);

This explicitly creates a new string object in the heap memory.

3. StringBuffer Class - The StringBuffer class creates mutable strings and is thread-safe. It is suitable for
multithreaded environments where multiple threads might access the same string object.

StringBuffer s = new StringBuffer("GeeksforGeeks");

With StringBuffer, you can append, insert, or modify the string.

4. StringBuilder Class - The StringBuilder class is similar to StringBuffer but is not thread-safe. It is used in single-
threaded environments to avoid the performance overhead of synchronization.

StringBuilder s = new StringBuilder("GeeksforGeeks");

Examples and Methods

Here, we explore some key methods provided by the String class in Java along with examples.

 length() : This method returns the number of characters in the string.

 charAt() : The charAt() method returns the character at a specified index. Index starts from 0 (like arrays).

 str.substring(start): Returns the substring from the start index to the end of the string.

 str.substring(start, end) : Returns the substring from the start index to the end - 1 index.

Example:

import java.io.*;

class GFG {

public static void main (String[] args) {

String str = "Geeks";

System.out.println(str.length());

System.out.println(str.charAt(3));
System.out.println(str.substring(2));

System.out.println(str.substring(2, 4));

Output

eks

ek

Create String Objects using String literals

When strings are created using literals, Java optimizes memory usage by storing them in a String Pool. If two string
literals have the same content, they share the same memory location in the pool. However, when strings are created
using the new keyword, they are stored in the heap memory, and each object gets a separate memory allocation,
even if they have the same content.

import java.io.*;

class GFG {

public static void main (String[] args) {

// String creation using literals

String s1 = "geek";

String s2 = "geek";

// Comparing string literals

if (s1 == s2)

System.out.println("Yes");

else

System.out.println("No");

// String creation using the new keyword

String s3 = new String("geek");

// Comparing literal with object created using 'new'

if (s1 == s3)

System.out.println("Yes");
else

System.out.println("No");

Output

Yes

No

More functions on the String Class

contains() Method : The contains() method checks if a specific sequence of characters exists within a string. It
returns true if the sequence is found, otherwise false.

import java.io.*;

class GFG {

public static void main (String[] args) {

String s1 = "geeksforgeeks";

String s2 = "geeks";

// Check if s1 contains s2

System.out.println(s1.contains(s2));

Output

true

equals() Method : The equals() method compares two strings for equality based on their content. It is case-sensitive.

import java.io.*;

class GFG {

public static void main (String[] args) {

String s1 = "GeeksforGeeks";

String s2 = "GeeksforGeeks";

// Compare s1 and s2 for equality


System.out.println(s1.equals(s2));

Output

true

compareTo() Method : The compareTo() method compares two strings lexicographically:

 Returns 0 if both strings are equal.

 Returns a positive value if the first string is lexicographically greater.

 Returns a negative value if the first string is lexicographically smaller.

import java.io.*;

class GFG {

public static void main (String[] args) {

String s1 = "geeksforgeeks";

String s2 = "for";

// Compare s1 and s2

int res = s1.compareTo(s2);

if (res == 0)

System.out.println("Same");

else if (res > 0)

System.out.println("s1 Greater");

else

System.out.println("s1 Smaller");

Output

s1 Greater
indexOf() Method : The indexOf() method returns the starting index of the first occurrence of a specified substring
within the string. If the substring is not found, it returns -1.

import java.io.*;

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

String s1 = "geeksforgeeks";

String s2 = "geek";

// Find the starting index of s2 in s1

System.out.println(s1.indexOf(s2));

}
Output

0
String Concatenation : String concatenation is the process of joining two or more strings to form a single combined
string. In Java, there are multiple ways to achieve string concatenation, including using the + operator and
the concat() method.

import java.io.*;

class GFG {

public static void main (String[] args) {

String s1 = "geeks";

// s2 references the same object as s1

String s2 = s1;

// Concatenating "forgeeks" to s1

s1 = s1 + "forgeeks"; // OR s1 = s1.concat("forgeeks");

System.out.println(s1);

System.out.println(s1 == s2);

Output

geeksforgeeks

false

String Methods in Java

String Methods

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

"GeeksforGeeks".length(); // returns 13
2. Char charAt(int i): Returns the character at ith index.

"GeeksforGeeks".charAt(3); // returns ‘k’

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

"GeeksforGeeks".substring(3); // returns “ksforGeeks”

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

"GeeksforGeeks".substring(2, 5); // returns “eks”

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

String s1 = ”Geeks”;

String s2 = ”forGeeks”;

String output = s1.concat(s2); // returns “GeeksforGeeks”

6. int indexOf (String s): Returns the index within the string of the first occurrence of the specified string.

String s = ”Learn Share Learn”;

int output = s.indexOf(“Share”); // returns 6

7. 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.

String s = ”Learn Share Learn”;

int output = s.indexOf("ea",3);// returns 13

8. Int lastIndexOf( String s): Returns the index within the string of the last occurrence of the specified string.

String s = ”Learn Share Learn”;

int output = s.lastIndexOf("a"); // returns 14

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

Boolean out = “Geeks”.equals(“Geeks”); // returns true

Boolean out = “Geeks”.equals(“geeks”); // returns false

10. boolean equalsIgnoreCase (String anotherString): Compares string to another string, ignoring case
considerations.

Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true

Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true

11. int compareTo( String anotherString): Compares two string lexicographically.

int out = s1.compareTo(s2); // where s1 ans s2 are

// strings to be compared

This returns difference s1-s2. If :

out < 0 // s1 comes before s2

out = 0 // s1 and s2 are equal.

out > 0 // s1 comes after s2.


12. int compareToIgnoreCase( String anotherString): Compares two string lexicographically, ignoring case
considerations.

int out = s1.compareToIgnoreCase(s2);

// where s1 ans s2 are

// strings to be compared

This returns difference s1-s2. If :

out < 0 // s1 comes before s2

out = 0 // s1 and s2 are equal.

out > 0 // s1 comes after s2.

 Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).

13. String toLowerCase(): Converts all the characters in the String to lower case.

String word1 = “HeLLo”;

String word3 = word1.toLowerCase(); // returns “hello"

14. String toUpperCase(): Converts all the characters in the String to upper case.

String word1 = “HeLLo”;

String word2 = word1.toUpperCase(); // returns “HELLO”

15. String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not affect
whitespaces in the middle.

String word1 = “ Learn Share Learn “;

String word2 = word1.trim(); // returns “Learn Share Learn”

16. String replace (char oldChar, char newChar): Returns new string by replacing all occurrences
of oldChar with newChar.

String s1 = “feeksforfeeks“;

String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”

 Note:- s1 is still feeksforfeeks and s2 is geeksgorgeek

StringBuilder and StringBuffer

StringBuilder: StringBuilder is a class in Java that represents a mutable sequence of characters. Unlike the String
class, which creates immutable sequences, StringBuilder allows modification of its contents without creating new
objects. It is specifically designed for use in single-threaded environments, as it does not provide thread safety.
StringBuilder is a faster alternative to StringBuffer when thread synchronization is not required. Its functions are very
similar to those of the StringBuffer class, making it a straightforward option for mutable string manipulation.

 Use StringBuilder in single-threaded environments for faster performance.

 Ideal for applications where thread safety is not a concern.

StringBuffer: StringBuffer is a class in Java that also represents a mutable sequence of characters. However, unlike
StringBuilder, it provides thread safety by ensuring synchronization. This makes StringBuffer a suitable choice for
multi-threaded environments where multiple threads may access or modify the string concurrently. Although it has
slightly more overhead than StringBuilder due to synchronization, it ensures reliable operation in concurrent
scenarios. StringBuffer is often used when both mutability and thread safety are essential.

Difference Between StringBuilder and StringBuffer

Feature StringBuilder StringBuffer

Thread Safety Not thread-safe. Thread-safe.

Synchronization Does not provide synchronization. Provides synchronization.

Faster, as it doesn't have overhead for thread Slower due to synchronization


Performance
safety. overhead.

Use Case Single-threaded environment. Multi-threaded environment.

Recommendatio
Preferred for single-threaded programs. Used when thread safety is required.
n

Here is the Example for the StringBuilder and StringBuffer Classes:

// Java code to illustrate the internal

// working of String, StringBuilder

// and StringBuffer class

class GfG

public static void main (String[] args) {

String s1 = "geeks";

String s2 = s1;

// Creates a new location to store s1

s1 = s1 + "forgeeks";

// s1 and s2 refers to different location

if(s1 == s2)

System.out.println("Same");

else

System.out.println("Not Same");

// StringBuilder or StringBuffer class

StringBuilder sb1 = new StringBuilder("geeks");


// sb2 refers to the same location as sb1

StringBuilder sb2 = sb1;

// Append operation modifies the same object

// as it is mutable in nature

sb1 = sb1.append("forgeeks");

// Both sb1 and sb2 refers to the same location

if(sb1 == sb2)

System.out.println("Same");

else

System.out.println("Not Same");

Output

Not Same

Same

StringBuilder and StringBuffer Methods

Common Methods in String, StringBuilder, and StringBuffer Classes:

1. length():
The length() method is used to determine the number of characters in a sequence. It returns the length of
the sequence represented by the object. For example, if you call length() on a StringBuilder object, it will
return the number of characters currently stored in it.

2. charAt(index):
This method is used to fetch the character present at a specific index in the sequence. The index should be
between 0 and length()-1. For instance, if the string is "Geeks", charAt(1) will return 'e'.

3. indexOf(str):
The indexOf() method searches for the first occurrence of a specified substring within the sequence. If the
substring exists, the method returns the index of its first occurrence; otherwise, it returns -1.

4. indexOf(str, fromIndex):
This is a variation of the indexOf() method, which starts searching for the substring from a specified index. If
the substring is found, it returns the index of the first occurrence; otherwise, it returns -1.
5. lastIndexOf(str):
This method searches for the last occurrence of a specified substring within the sequence. If the substring
exists, it returns the index of its last occurrence; otherwise, it returns -1.

6. lastIndexOf(str, fromIndex):
Similar to lastIndexOf(str), this method begins the search from the specified fromIndex and moves backward
to find the last occurrence of the substring.

7. compareTo(sb):
The compareTo() method compares two sequences lexicographically. It returns 0 if the sequences are equal,
a positive value if the current sequence is greater, and a negative value if it is smaller.

8. substring(beginIndex):
This method returns a new sequence starting from the specified beginIndex to the end of the sequence.

9. substring(beginIndex, endIndex):
This variation of substring() allows you to specify both the starting and ending indices. It returns a new
sequence starting at beginIndex and ending at endIndex - 1.

10. chars():
The chars() method provides a stream of integer values representing the characters in the sequence.

Methods Exclusive to StringBuilder and StringBuffer Classes:

1. append(x):
The append() method adds the specified data to the end of the sequence. This data can be of various types,
such as boolean, int, char, String, float, or Object. For example, you can append "World" to "Hello"
using append().

2. insert(offset, x):
This method allows you to insert data at a specified offset position in the sequence. For instance, you can
insert "Java" at index 4 in the string "GeeksFor" to make it "GeeksJavaFor".

3. setCharAt(index, c):
The setCharAt() method modifies the character at the specified index in the sequence. For example, you can
change the first character of "Geeks" to 'T', resulting in "Teeks".

4. reverse():
The reverse() method reverses the characters in the sequence. For instance, applying reverse() on "Geeks"
will give "skeeG".

5. deleteCharAt(index):
This method removes the character at the specified index in the sequence. For example, deleting the
character at index 3 in "Geeks" will result in "Gees".

6. delete(start, end):
This method removes all characters from the specified start index to end-1. For instance, deleting characters
from index 1 to 4 in "Geeks" will result in "Gs".

7. capacity():
The capacity() method returns the current storage capacity of the sequence. It indicates how much data can
be stored before the sequence needs to resize itself.

8. replace(start, end, str):


This method replaces the characters between the specified start and end indices with a new string. For
example, replacing characters from index 1 to 4 in "GeeksForGeeks" with "Hello" will result in "GHelloGeeks".
Here is an example program to demonstrate working of the key functions:

class GfG

public static void main (String[] args) {

// StringBuilder or StringBuffer class

StringBuilder sb = new StringBuilder("dcba")

// Reversing the StringBuilder

sb.reverse();

System.out.println(sb);

// Appending to sb

sb.append("efg");

System.out.println(sb);

// Replacing the character at 1

// with h

sb.setCharAt(1, 'h');

System.out.println(sb);

// Delete the characters at 0, 1

sb.delete(0, 2);

System.out.println(sb);

// Inserts "efg" at 1

sb.insert(1, "efg");

System.out.println(sb);

Output

abcd

abcdefg

ahcdefg

cdefg

cefgdefg

You might also like