What is a Java String?
A Java String is an ordered, immutable sequence of characters. For example, “hello” or “Java” are strings. Immutability means you cannot change a String object after you create it.
Java Strings allow you to work with text. You need them for user input, data storage, and display.
For example, your Java program uses Strings to capture a user’s name and address from a form.
Learn Java with this course. It covers everything from basics like variables and control structures to advanced topics like classes, inheritance, and polymorphism.
How to Create Java Strings
You create Java Strings in two ways: using string literals or the new keyword.
1. Use String Literals
This is the most common way to create a String. Java treats text in double quotes as a String literal.
Here’s an example:
String greeting = "Hello, World!";
Java stores String literals in the String Pool. This saves memory. If you create the same String literal twice, Java points both variables to the same object in the pool.
2. Use the new Keyword
You can also create a String object using the new keyword. This creates a new String object in the heap memory. This happens even if an identical String exists in the String Pool.
Here’s how you do it:
String name = new String("Alice");
Key Java String Methods
Java provides methods to work with Strings. These methods manipulate and analyze text.
1. Get String Length
The length()
method returns the number of characters in a String.
String text = "Java";
int len = text.length(); // len will be 4
System.out.println(len);
2. Concatenate Strings
You can join two or more Strings. Use the +
operator or the concat()
method.
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // fullName is "John Doe"
System.out.println(fullName);
String message = "Welcome ".concat("Home"); // message is "Welcome Home"
System.out.println(message);
3. Access Characters
Use the charAt()
method to get a character at a specific index. Indexes start from 0.
String word = "Code";
char firstChar = word.charAt(0); // firstChar is 'C'
System.out.println(firstChar);
4. Compare Strings
The equals()
method compares two Strings. It checks if their content is the same. Use equalsIgnoreCase()
to ignore case differences.
String s1 = "hello";
String s2 = "Hello";
boolean areEqual = s1.equals(s2); // areEqual is false
System.out.println(areEqual);
boolean ignoreCaseEqual = s1.equalsIgnoreCase(s2); // ignoreCaseEqual is true
System.out.println(ignoreCaseEqual);
Do not use ==
to compare String content. The ==
operator checks if two String references point to the same object in memory.
5. Find Substrings
The indexOf()
method finds the first occurrence of a substring. It returns the index. If the substring is not found, it returns -1.
String sentence = "Learn Java Programming";
int index = sentence.indexOf("Java"); // index is 6
System.out.println(index);
6. Extract Substrings
The substring()
method extracts a portion of a String. You provide start and end indexes.
String original = "Programming";
String part = original.substring(3, 7); // part is "gram"
System.out.println(part);
7. Replace Characters or Substrings
Use replace()
to replace characters or substrings.
String text = "hello world";
String newText = text.replace('o', 'x'); // newText is "hellx wxrld"
System.out.println(newText);
String anotherText = "Java is fun";
String replaced = anotherText.replace("fun", "great"); // replaced is "Java is great"
System.out.println(replaced);
8. Convert Case
The toLowerCase()
and toUpperCase()
methods change the case of a String.
String upper = "HELLO";
String lower = upper.toLowerCase(); // lower is "hello"
System.out.println(lower);
String lower2 = "world";
String upper2 = lower2.toUpperCase(); // upper2 is "WORLD"
System.out.println(upper2);
9. Trim Whitespace
The trim()
method removes leading and trailing whitespace.
String padded = " leading and trailing ";
String trimmed = padded.trim(); // trimmed is "leading and trailing"
System.out.println(trimmed);
String Immutability: What It Means
When you perform an operation that appears to change a String, Java creates a new String object. The original String remains unchanged.
For example:
String original = "apple";
original.concat("pie"); // This creates a new String "applepie"
System.out.println(original); // Prints "apple", original is unchanged
String newString = original.concat("pie"); // Assign the result to a new variable
System.out.println(newString); // Prints "applepie"
This immutability offers benefits:
- Thread Safety: Multiple threads can access a String without synchronization problems. One thread cannot change a String while another reads it.
- Security: Immutability is important for security. When you use Strings for sensitive data like database credentials, their unchanging nature prevents unintended modifications.
- Performance: The String Pool relies on immutability. This helps save memory and improves performance by reusing existing String objects.
Best Practices for Using Java Strings
Follow these practices to use Java Strings effectively:
- Prefer String Literals: Use string literals (“text”) when possible. This uses the String Pool and saves memory.
- Use StringBuilder or StringBuffer for Modifications: If you need to modify Strings many times, use
StringBuilder
(for single-threaded use) orStringBuffer
(for multi-threaded use). These classes are mutable. - Compare Strings Correctly: Always use
equals()
orequalsIgnoreCase()
to compare String content. Do not use==
. - Handle null Strings: Always check if a String is
null
before performing operations on it. This preventsNullPointerException
s.String myString = null;
if (myString != null && myString.length() > 0) {
// Perform operations
}