Java Strings - Complete Notes
1 Introduction to Strings
• Strings in Java are objects that represent sequences of characters.
They are immutable, meaning once created, they cannot be
changed.
• Java provides the `String` class in the `[Link]` package to work
with strings.
2 String Constant Pool and Memory Storage
• In Java, strings are stored in a special memory area called the String
Constant Pool (SCP).
• When a string is created using a string literal, it is stored in this pool
to avoid memory duplication.
Example:
String s1 = "Hello";
String s2 = "Hello"; // s1 and s2 both refer to the same object in SCP
However, when a string is created using the `new` keyword, it is
stored in the heap memory:
String s3 = new String("Hello"); // Stored outside the SCP
3. Ways to Create Strings
1. Using string literals (stored in SCP)
2. Using `new` keyword (stored in Heap)
3. From character arrays: new String(char[])
4. From byte arrays: new String(byte[])
char[] chars = {'J','a','v','a'};
String s1 = new String(chars);
[Link](s1);
Output: Java
4. Advantages of Strings in Java
- Strings are immutable, which makes them thread-safe and secure.
- Java optimizes memory usage via the String Constant Pool.
- The String class has many useful built-in methods.
- Easy to use and integrate with other APIs and libraries.
- Strings are widely used in file handling, networking, and user input.
5. Important String Methods with Examples
Method: length()
String str = "Hello";
[Link]([Link]());
Output: 5
Method: charAt()
String str = "Hello";
[Link]([Link](1)); Output: e
Method: substring()
String str = "HelloWorld";
[Link]([Link](5));
Output: World
Method: contains()
String str = "OpenAI ChatGPT";
[Link]([Link]("Chat"));
Output: true
Method: equals()
String a = "Java";
String b = "Java";
[Link]([Link](b));
Output: true
Method: equalsIgnoreCase()
String a = "Java";
String b = "java";
Output: true
[Link]([Link](b));
Method: toLowerCase()
String str = "HELLO";
[Link]([Link]());
Output: hello
Method: toUpperCase()
String str = "hello";
[Link]([Link]());
Output: HELLO
Method: trim()
String str = " Hello ";
[Link]([Link]());
Output: Hello
Method: replace()
String str = "banana";
[Link]([Link]('a', 'o'));
Output: bonono
Method: split()
String str = "a,b,c";
String[] parts = [Link](",");
[Link](parts[1]);
Output: b
Method: indexOf()
String str = "programming";
[Link]([Link]('g')); Output: 3
Method: lastIndexOf()
String str = "programming";
[Link]([Link]('g'));
Output: 10
Method: startsWith()
String str = "Java";
[Link]([Link]("Ja"));
Output: true
Method: endsWith()
String str = "Java";
[Link]([Link]("va"));
Output: true