Java String Introduction
In this page:
Creating Strings
A String in Java is an object representing an immutable sequence of characters, and you can create one either with a literal ("hello") or explicitly with new String("hello"), though the literal form is almost always preferred. Both approaches produce a fully usable String object with the same methods available.
Example: Creating Strings
public class Main {
public static void main(String[] args) {
String a = "hello";
String b = new String("hello");
System.out.println(a);
System.out.println(b);
}
}
Login to try C/C++/Java/PHP code in the editor
Understanding the String Pool
To save memory, Java stores string literals in a special region called the string pool, so two literals with identical text actually point to the exact same object in memory rather than two separate copies. You can see this with == comparing true for two identical literals, which is precisely why == is the wrong tool for comparing string content.
Example: Understanding the String Pool
public class Main {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
System.out.println(a == b); // true: same pooled object
}
}
Login to try C/C++/Java/PHP code in the editor
String Immutability
Strings are immutable: once created, a String object's characters can never be changed in place. Every method that appears to "modify" a string — toUpperCase(), concat(), replace() — actually returns a brand-new String object, leaving the original untouched.
Example: String Immutability
public class Main {
public static void main(String[] args) {
String original = "hello";
String upper = original.toUpperCase();
System.out.println(original); // unchanged
System.out.println(upper); // new string
}
}
Login to try C/C++/Java/PHP code in the editor
Checking String Length
The length() method returns the total character count of a String, including spaces, punctuation, and digits, not just letters. Since it's a method (not a field like an array's length), remember the parentheses: str.length().
Example: Checking String Length
public class Main {
public static void main(String[] args) {
String text = "Hello World";
System.out.println(text.length());
}
}
Login to try C/C++/Java/PHP code in the editor
Accessing Single Characters
charAt(index) retrieves a single character at a given zero-based position, so charAt(0) gets the first character. Calling it with an index equal to or beyond the string's length throws a StringIndexOutOfBoundsException.
Example: Accessing Single Characters
public class Main {
public static void main(String[] args) {
String text = "Hello";
System.out.println(text.charAt(0));
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: