3. String Handling
3. String Handling
In Java, a String is an object that represents a sequence of characters. It is part of the java.lang package
and is immutable, meaning once a String object is created, its value cannot be changed.
String handling is important in Java because strings are one of the most commonly used data types in
programming. Java provides a rich set of features for working with strings efficiently, making string
manipulation easier, safer, and more powerful.
Creating a String
Strings in Java can be created in two ways:
o
String literals are stored in the String Pool, which helps save memory.
2. Using the new Keyword
String str2 = new String("Hello, Java!");
In Java, the String Pool (or String Intern Pool) is a special memory area in the heap where String literals
are stored to optimize memory usage and improve performance.
1. When a String literal is created, Java checks if an identical String already exists in the String Pool.
2. If it exists, the reference to the existing String is returned.
3. If it does not exist, a new String is created and added to the pool.
Example:
public class StringPoolExample {
public static void main(String[] args) {
String s1 = "Hello"; // Stored in String Pool
String s2 = "Hello"; // Reuses the same object from the pool
Since s1 and s2 refer to the same interned String object, s1 == s2 returns true.
Even though s3 and s4 contain the same value, they are different objects in heap memory.
Example
public class StringExample {
public static void main(String[] args) {
// Creating a string using a string literal
String str1 = "Hello, Java!";
// Creating a string using the 'new' keyword
String str2 = new String("Hello, Java!");
// Extracting a substring
String subStr = str1.substring(7, 11); // Extracts from index 7 to 10
System.out.println("Substring from index 7 to 11: " + subStr); // Output: Java
1. indexOf(String str)
o Returns the index of the first occurrence of the specified substring.
o If the substring is not found, it returns -1.
2. lastIndexOf(String str)
o Returns the index of the last occurrence of the specified substring.
o If the substring is not found, it returns -1.
o In Java, the lastIndexOf(String str) method returns the index of the last occurrence of the
specified substring in a given string
Example:
public class Main {
public static void main(String[] args) {
String str = "Java";
System.out.println(str.indexOf("a")); // Output: 1
(first occurrence of 'a')
System.out.println(str.lastIndexOf("a")); // Output: 3
(last occurrence of 'a')
}
}
Breakdown of Outputs:
J a v a
0 1 2 3
}
}