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

3. String Handling

In Java, a String is an immutable object representing a sequence of characters, created either using string literals or the new keyword. The String Pool optimizes memory usage by storing string literals and reusing them when identical strings are created. Java provides various methods for string manipulation, including length, substring, and comparison, making it a powerful data type in programming.

Uploaded by

krishnapate2024
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

3. String Handling

In Java, a String is an immutable object representing a sequence of characters, created either using string literals or the new keyword. The String Pool optimizes memory usage by storing string literals and reusing them when identical strings are created. Java provides various methods for string manipulation, including length, substring, and comparison, making it a powerful data type in programming.

Uploaded by

krishnapate2024
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

STRING

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:

1. Using String Literals


String str1 = "Hello, Java!";

o
String literals are stored in the String Pool, which helps save memory.
2. Using the new Keyword
String str2 = new String("Hello, Java!");

o This creates a new object in the heap memory.

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.

How the String Pool Works:

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

System.out.println(s1 == s2); // true (both refer to the same object)


}
}

Since s1 and s2 refer to the same interned String object, s1 == s2 returns true.

Using new Keyword:


String s3 = new String("Hello");
String s4 = new String("Hello");

System.out.println(s3 == s4); // false (different objects)

Even though s3 and s4 contain the same value, they are different objects in heap memory.

Important Features of String Class

 String is an object, not a primitive data type.


 Methods allow manipulation without modifying the original string.
 Supports concatenation, searching, extraction, comparison, and conversion.
 Immutable: Once created, the value of a String cannot be changed.
 Stored in String Pool: Memory efficiency: Reusing Strings reduces memory consumption.
: Performance improvement: pooling avoids redundant object creation.

Common String Methods


Method Description
length() Returns the length of the string.
charAt(index) Returns the character at the specified index.
substring(start, end) Extracts a substring.
toUpperCase() Converts to uppercase.
toLowerCase() Converts to lowercase.
trim() Removes leading and trailing spaces.
equals(str) Checks if two strings are equal.
equalsIgnoreCase(str) Compares strings ignoring case.
contains(str) Checks if a string contains a substring.
replace(old, new) Replaces characters in a string.

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!");

// Comparing strings using '==' (checks memory reference)


System.out.println("str1 == str2: " + (str1 == str2)); // false, because str2 is in heap, not in
string pool

// Comparing strings using 'equals()' (checks content)


System.out.println("str1.equals(str2): " + str1.equals(str2)); // true, because content is the
same
// Finding the length of a string
System.out.println("Length of str1: " + str1.length()); // Output: 12

// Accessing characters in a string


System.out.println("Character at index 7: " + str1.charAt(7)); // Output: J

 Indexing in Java starts from 0.


 "Hello, Java" → H(0), e(1), l(2), l(3), o(4), (,)(5), (space)(6), J(7), a(8), v(9), a(10), !(11)
 So, str.charAt(7) returns 'J'.

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

// Converting to uppercase and lowercase


System.out.println("Uppercase: " + str1.toUpperCase()); // Output: HELLO, JAVA!
System.out.println("Lowercase: " + str1.toLowerCase()); // Output: hello, java!
// Checking if the string contains a substring
System.out.println("Contains 'Java': " + str1.contains("Java")); // true

// Replacing characters in a string


System.out.println("Replace 'Java' with 'World': " + str1.replace("Java", "World")); // Output:
Hello, World!

// Removing leading and trailing spaces using trim()


String strWithSpaces = " Hello, Java! ";
System.out.println("Trimmed String: '" + strWithSpaces.trim() + "'");
//Output ;- Trimmed String: 'Hello, Java!'

// Splitting a string into an array


String sentence = "Java is fun to learn";
String[] words = sentence.split(" ");
System.out.println("Words in sentence:");
for (String word : words) {
System.out.println(word);
}
O/P
Words in sentence:
Java
is
fun
to
learn

concat(): Joins two strings together.


String s1 = "Java";
String s2 = "Programming";
System.out.println(s1.concat(s2)); // Output: JavaProgramming

 substring(int beginIndex): Extracts substring from given index.


 substring(int beginIndex, int endIndex): Extracts substring from a range.
String str = "HelloWorld";
System.out.println(str.substring(5)); // Output: World
System.out.println(str.substring(0, 5)); // Output: Hello

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

You might also like