- What is a String in Java?
- Key Points about Strings in Java
- String Literal vs String Object
- Using String Literals
- What’s happening here?
- 📌 Key Point:
- Using new keyword:
- What’s happening here?
- 🧠 Why does it create a new object?
- 📌 Key Point:
- Let’s test it in code:
- Summary Table:
- Commonly Used String Methods in Java
- 1. length()
- 2. charAt(int index)
- 3. equals(String anotherString)
- 4. equalsIgnoreCase(String anotherString)
- 5. compareTo(String anotherString)
- 6. toLowerCase() / toUpperCase()
- 7. substring(int beginIndex)
- 8. substring(int beginIndex, int endIndex)
- 9. contains(CharSequence sequence)
- 10. indexOf(char)
- 11. lastIndexOf(char)
- 12. replace(char oldChar, char newChar)
- 13. startsWith() and endsWith()
- 14. trim()
- 15. split(String regex)
- 16. isEmpty() and isBlank() (Java 11+)
- String Immutability in Depth
- Mutable Alternative: StringBuilder and StringBuffer
- Summary Table: String Methods
- Quiz Time – Test Your Knowledge
- Final Thoughts
Java is a very powerful and versatile programming language. One of its most widely used classes is the String class. Almost every Java program works with strings—whether it’s a name, an address, or even input from the user. In this tutorial, we will go deep into the String class, its features, and the most commonly used string methods, all explained in a beginner-friendly way.
What is a String in Java?
In Java, a String is an object that represents a sequence of characters, such as words, sentences, or symbols. It is not a primitive data type, but a class provided by the java.lang package.
Unlike primitives like int or char, a String is a reference type and is internally implemented as a character array. It is immutable, meaning once a String object is created, its value cannot be changed.
String name = "Prakash";
Here, “Prakash” is a String literal, and name is a reference variable pointing to that string object.
Key Points about Strings in Java
- Strings are created using double quotes, e.g.,
"Hello, Java!" - Internally, Java uses a char[] array to store characters.
- The
Stringclass provides many built-in methods to manipulate and analyze text (e.g.,length(),substring(),toUpperCase()). - Strings are immutable — operations like
concat()orreplace()return a new String object instead of modifying the original one. - String literals are stored in the String Constant Pool for memory optimization.
- You can create strings using:
- String literals
newkeyword
String Literal vs String Object
Using String Literals
String s1 = "Hello";
String s2 = "Hello";
What’s happening here?
- In Java, string literals are stored in a special area of memory called the String Constant Pool (part of the method area).
- When you write:
String s1 = "Hello";
Java checks if the string "Hello" already exists in the pool.
- If it does, it reuses the same object.
- If not, it adds it to the pool and then
s1points to it.
Now when you write:
String s2 = "Hello";
Java again checks the pool.
Since "Hello" already exists, s2 points to the same object as s1.
📌 Key Point:
- No new object is created in memory for
s2. s1 == s2returnstruebecause both refer to the same object in memory (reference comparison).
Using new keyword:
String s3 = new String("Hello");
This creates a new object in the heap memory, even if "Hello" already exists in the pool.
What’s happening here?
- This line does two things:
- Looks for
"Hello"in the string pool (and adds it if not already there). - Creates a new String object in the heap memory, which contains the same value
"Hello".
- Looks for
🧠 Why does it create a new object?
Because you explicitly used the new keyword, you’re telling Java:
“I want a fresh, new object, regardless of whether an identical one already exists.”
So now:
"Hello"exists in the String pool.s3points to a different object in the heap with the same value"Hello".
📌 Key Point:
s1 == s3returnsfalse(different references, even though values are the same).s1.equals(s3)returnstrue(values are same).
Let’s test it in code:
public class TestStrings {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2); // true (same pool object)
System.out.println(s1 == s3); // false (different memory location)
System.out.println(s1.equals(s3)); // true (same content)
}
}
Output
true
false
true
Summary Table:
| Statement | Memory | Object Created? | Reference Equal (==)? | Value Equal (.equals())? |
|---|---|---|---|---|
String s1 = "Hello"; | String Pool | Yes (if not already) | – | – |
String s2 = "Hello"; | Reuses from Pool | No | true with s1 | true |
String s3 = new String("Hello"); | Heap (also refers to pool) | Yes | false with s1 | true |
Commonly Used String Methods in Java
Let’s now explore important methods in the String class. These methods are extremely useful in manipulating and working with strings.
1. length()
Returns the number of characters in the string.
String str = "Hello";
System.out.println(str.length()); // Output: 5
2. charAt(int index)
Returns the character at the specified index (starts from 0).
String str = "Java";
System.out.println(str.charAt(2)); // Output: v
3. equals(String anotherString)
Compares two strings for content, case-sensitive.
String s1 = "hello";
String s2 = "hello";
System.out.println(s1.equals(s2)); // Output: true
4. equalsIgnoreCase(String anotherString)
Compares two strings ignoring case.
String s1 = "hello";
String s2 = "hello";
System.out.println(s1.equals(s2)); // Output: true
5. compareTo(String anotherString)
Compares two strings lexicographically (dictionary order).
String s1 = "Apple";
String s2 = "Banana";
System.out.println(s1.compareTo(s2)); // Output: negative value
- Returns
0if equal. - Returns a positive value if s1 > s2.
- Returns a negative value if s1 < s2.
6. toLowerCase() / toUpperCase()
Converts the string to all lowercase or all uppercase.
String name = "Java";
System.out.println(name.toLowerCase()); // java
System.out.println(name.toUpperCase()); // JAV
7. substring(int beginIndex)
String text = "Programming";
System.out.println(text.substring(3)); // gramming
8. substring(int beginIndex, int endIndex)
Returns a part (sub-string) of the original string.
String text = "Programming";
System.out.println(text.substring(3, 7)); // gram
9. contains(CharSequence sequence)
Checks whether the given character or string is part of this string.
String text = "Hello World";
System.out.println(text.contains("World")); // true
10. indexOf(char)
Returns the position of the character’s first occurrence
String str = "Hello";
System.out.println(str.indexOf('l')); // 2
11. lastIndexOf(char)
Returns the position of the character’s last occurrence.
String str = "Hello";
System.out.println(str.indexOf('l')); // 2
System.out.println(str.lastIndexOf('l')); // 3
12. replace(char oldChar, char newChar)
Replaces all old characters with new characters.
String data = "aabbcc";
System.out.println(data.replace('a', 'x')); // xxbbcc
13. startsWith() and endsWith()
Checks if the string starts or ends with the specified text.
String url = "https://google.com";
System.out.println(url.startsWith("https")); // true
System.out.println(url.endsWith(".com")); // true
14. trim()
Removes leading and trailing white spaces from the string.
String msg = " Hello Java! ";
System.out.println(msg.trim()); // "Hello Java!"
15. split(String regex)
Splits the string based on a pattern (usually space, comma, etc.).
String data = "Java,Python,C++";
String[] languages = data.split(",");
for(String lang : languages){
System.out.println(lang);
}
16. isEmpty() and isBlank() (Java 11+)
isEmpty()– true if string length is 0.isBlank()– true if string contains only white spaces or is empty.
String a = "";
String b = " ";
System.out.println(a.isEmpty()); // true
System.out.println(b.isBlank()); // true
String Immutability in Depth
Once a string is created, it cannot be changed. All methods like replace, toUpperCase, etc. return a new string. The original remains unchanged.
String s = "Java";
String updated = s.toUpperCase();
System.out.println(s); // Java
System.out.println(updated); // JAVA
Mutable Alternative: StringBuilder and StringBuffer
If you want to modify strings repeatedly, use:
StringBuilder(Not Thread-Safe but Faster)StringBuffer(Thread-Safe)
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Hello World
Summary Table: String Methods
| Method | Description |
|---|---|
length() | Returns number of characters |
charAt(i) | Returns character at index i |
equals() | Compares content |
equalsIgnoreCase() | Ignores case during comparison |
compareTo() | Lexicographical comparison |
substring() | Extracts substring |
contains() | Checks if substring exists |
indexOf() | First position of character |
replace() | Replace characters |
startsWith() | Check string start |
endsWith() | Check string end |
trim() | Removes white spaces |
split() | Splits into array |
isEmpty() | Checks if string is empty |
isBlank() | Checks if only spaces (Java 11+) |
Quiz Time – Test Your Knowledge
- What is the difference between
==and.equals()in strings? - What does
String s = new String("Hello")do? - What method would you use to get a specific character?
- What does
substring(2, 5)return if the string is “Programming”? - Is String mutable or immutable in Java?
Final Thoughts
Understanding the String class is fundamental to mastering Java. Whether you’re dealing with user input, file names, error messages, or database queries—strings are everywhere. By learning these methods, you gain powerful tools to manipulate and analyze text easily.
Keep practicing by writing programs that involve user input, string parsing, and text formatting.