Java Strings
A String in Java is an object representing a sequence of characters. Strings are immutable — once created, their content cannot change; operations like concatenation create new String objects.
The String class provides many useful methods like length(), charAt(), substring(), toUpperCase(), and equals() for comparing content.
String s = "text";
s.length();
s.substring(0, 3);Creating and using strings
Strings can be created with a literal ("text") or with `new String(...)`. Use + or concat() to join strings together.
Common String methods
length() returns character count, charAt(i) gets a character, substring() extracts part of a string, and equals() compares content (never use == for strings).
public class Main {
public static void main(String[] args) {
String name = "Java";
System.out.println(name.length());
System.out.println(name.toUpperCase());
System.out.println(name.equals("Java"));
}
}4
JAVA
truelength() returns 4 characters, toUpperCase() converts case, equals() compares content.
Key points
- Strings are immutable objects.
- Use equals() to compare string content, not ==.
- length(), charAt(), substring() are common methods.
- Concatenation with + creates a new String.
