0% found this document useful (0 votes)
0 views9 pages

Strings

This document provides an overview of Strings in Java, highlighting their immutability, creation methods, and the use of the String Pool. It also covers the CharSequence interface, string comparison, modification methods, and mutable string classes like StringBuffer and StringBuilder. Additionally, it explains common string operations such as searching, formatting, and converting other data types to strings.

Uploaded by

vakeelsaab4.2021
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)
0 views9 pages

Strings

This document provides an overview of Strings in Java, highlighting their immutability, creation methods, and the use of the String Pool. It also covers the CharSequence interface, string comparison, modification methods, and mutable string classes like StringBuffer and StringBuilder. Additionally, it explains common string operations such as searching, formatting, and converting other data types to strings.

Uploaded by

vakeelsaab4.2021
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/ 9

Strings in Java

Definition:
A String in Java represents a sequence of characters. It is a class in the java.lang
package. Strings are immutable, meaning once a String object is created, its content cannot be
changed.

String Creation:
Using string literal:
String str1 = "Hello";

The string is stored in the String Pool.


If a string with the same content exists in the pool, it will return a reference to the existing string,
saving memory.

Using new keyword:


String str2 = new String("Hello");

This creates a new string object in the heap, even if an identical string exists in the pool.

CharSequence Interface
The CharSequence interface represents a readable sequence of char values. Common classes
that implement CharSequence include String, StringBuffer, and StringBuilder.
Methods in CharSequence interface:
1. length(): Returns the length of the sequence.
2. charAt(int index): Returns the character at the specified index.
3. subSequence(int start, int end): Returns a new CharSequence from the sequence.

Class String
The String class is part of the java.lang package, and it represents a sequence of characters.
Key points:
String objects are immutable.
The String class implements Serializable, Comparable<String>, and CharSequence interfaces.

Methods for Extracting Characters from Strings


1. charAt(int index): Returns the character at the specified index.
2. substring(int beginIndex): Returns a new string starting from the specified index.
3. substring(int beginIndex, int endIndex): Returns a substring between beginIndex and
endIndex.
String Comparison
1. equals(): Compares the content of two strings. Returns true if they are equal.
2. equalsIgnoreCase(): Compares two strings, ignoring case considerations.
3. compareTo(): Compares two strings lexicographically. Returns:
0: if the strings are equal,
A positive integer: if the first string is lexicographically greater,
A negative integer: if the first string is lexicographically smaller.

Modifying Strings
Since String objects are immutable, Java provides other classes like StringBuffer and
StringBuilder to modify strings.
Common string modification methods:
1. replace(): Replaces all occurrences of a substring.
2. concat(): Concatenates two strings.
3. toUpperCase() / toLowerCase(): Converts the string to upper or lower case.

Searching in Strings
1. int indexOf(int ch): Finds the first occurrence of the specified character.
2. int indexOf(String str): Finds the first occurrence of the specified substring.
3. lastIndexOf(): Returns the index of the last occurrence of a substring.

Class StringBuffer
StringBuffer is a mutable sequence of characters.It can be modified after creation, unlike String.
Common methods:
append(): Adds data to the end of the StringBuffer.
insert(): Inserts data at a specified index.
delete(): Deletes a sequence of characters.
reverse(): Reverses the sequence of characters.
*************************************************************************************************************
*************************************************************************************************************
*************************************************************************************************************

String Pool:
String Pool is a special memory area in the heap used to store string literals.
If two string literals are the same, they share the same reference from the string pool.

Immutability of Strings:
Once a string is created, its value cannot be changed. Modifying operations return a new string.

String s = "Java";
s.concat(" Programming"); // Creates a new string "Java Programming"
System.out.println(s); // Outputs "Java", not "Java Programming"
Common String Methods:

Length of a string:

int len = str.length(); // Returns the length of the string

Character at a specific index:

char c = str.charAt(2); // Returns the character at index 2

Substring:

String subStr = str.substring(2, 5); // Extracts a substring from index 2 to 4

Concatenation:

String fullStr = str.concat(" World"); // Concatenates two strings

Equality Check:

equals(): Compares string content.

boolean isEqual = str1.equals(str2); // true if content is the same

Convert to Upper/Lower Case:

String upperStr = str.toUpperCase(); // Converts string to upper case


String lowerStr = str.toLowerCase(); // Converts string to lower case

Trim (removes leading and trailing whitespaces):

String trimmedStr = str.trim();

Replace Characters:

String replacedStr = str.replace('a', 'b'); // Replaces all 'a' with 'b'

String Comparison:
compareTo(): Lexicographically compares two strings.
int result = str1.compareTo(str2);
// Returns 0 if both strings are equal, a negative number if str1 is lexicographically less, and a
positive number if greater.

StringBuilder and StringBuffer:


StringBuilder and StringBuffer are mutable versions of String, meaning they can be modified
without creating new objects.

StringBuilder is not thread-safe but faster.


StringBuffer is thread-safe but slower due to synchronization.

StringBuilder sb = new StringBuilder("Hello");


sb.append(" World"); // Modifies the original object

String Interning:
The intern() method forces a string to refer to the string pool.

String str3 = new String("Hello");


String str4 = str3.intern(); // Forces str4 to reference the string in the pool

String Format:
Format strings using String.format(), similar to printf-style formatting.

String formattedStr = String.format("Hello %s!", "World"); // Output: "Hello World!"

String Splitting:
Split a string into an array based on a delimiter:
String[] parts = str.split(" ");

Converting Other Data Types to String:


Using valueOf() method:
String numStr = String.valueOf(123); // Converts integer to string "123"

StringBuffer class:
StringBuffer class is used to create mutable(modifiable) string objects.The StringBuffer class is
same as String class except StringBuffer class is mutable i.e., it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Mutable Strings:
A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.

Important Constructors of StringBuffer Class

Constructor Description

StringBuffer() It creates an empty String


buffer with the initial capacity
of 16.

StringBuffer(String str) It creates a String buffer with


the specified string..
StringBuffer(int capacity) It creates an empty String
buffer with the specified
capacity as length.

Important methods of StringBuffer class

Modifier and Type Method Description

public synchronized append(String s) It is used to append


StringBuffer the specified string
with this string. The
append() method is
overloaded like
append(char),
append(boolean),
append(int),
append(float),
append(double) etc.

public synchronized insert(int offset, It is used to insert


StringBuffer String s) the specified string
with this string at
the specified
position. The insert()
method is
overloaded like
insert(int, char),
insert(int, boolean),
insert(int, int),
insert(int, float),
insert(int, double)
etc.
public synchronized replace(int It is used to replace
StringBuffer startIndex, int the string from
endIndex, String str) specified startIndex
and endIndex.

public synchronized delete(int It is used to delete


StringBuffer startIndex, int the string from
endIndex) specified startIndex
and endIndex.

public synchronized reverse() is used to reverse


StringBuffer the string.

public int capacity() It is used to return


the current
capacity.

public void ensureCapacity(int It is used to ensure


minimumCapacity) the capacity at least
equal to the given
minimum.

public char charAt(int index) It is used to return


the character at the
specified position.

public int length() It is used to return


the length of the
string i.e. total
number of
characters.
public String substring(int It is used to return
beginIndex) the substring from
the specified
beginIndex.

public String substring(int It is used to return


beginIndex, int the substring from
endIndex) the specified
beginIndex and
endIndex.

//Java program using StringBuffer to delete,remove, insert and append character

public class StringBufferDemo


{
public static void main(String[] args)
{
// Create a StringBuffer object with an initial string
StringBuffer strbuffer = new StringBuffer("Hello CSE");

// Display the original string


System.out.println("Original String: " + strbuffer);

// Remove a character at a specific index


strbuffer.deleteCharAt(6);
System.out.println("After removing character at index 6: " + strbuffer);

// Delete a substring between two indices (e.g., removing "World")


strbuffer.delete(6,8);
System.out.println("After deleting substring from index 5 to 7: " + strbuffer);

// Append a new string


strbuffer.append("CSE");
System.out.println("After appending: " + strbuffer);

// Insert a string at a specific index


strbuffer.insert(5, " Welcome");
System.out.println("After inserting at index 5: " + strbuffer);
}
}
Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy