String and its methods
Text is probably the data you will handle the most: names, messages, files, addresses. In Java text is represented by the String class. Although it looks like a basic type, it is an object, which means it has methods you call with a dot: name.length(), name.toUpperCase(). Learning the most common String methods gives you a toolbox to solve hundreds of real problems.
The most used methods
A fundamental property: Strings are immutable. No method changes the original text; all of them return a new String. That is why writing text.toUpperCase(); without storing the result does nothing visible. Positions (indexes) start at 0, so the first character of "Java" is at index 0 and the last at length() - 1.
public class Main {
public static void main(String[] args) {
String text = " Hello, Java World ";
System.out.println(text.length()); // 21
String clean = text.strip(); // removes outer spaces
System.out.println("[" + clean + "]"); // [Hello, Java World]
System.out.println(clean.toUpperCase()); // HELLO, JAVA WORLD
System.out.println(clean.charAt(0)); // H
System.out.println(clean.indexOf("Java")); // 7
System.out.println(clean.indexOf("xyz")); // -1 means not found
System.out.println(clean.substring(7, 11)); // Java (end is exclusive)
System.out.println(clean.substring(7)); // Java World
System.out.println(clean.replace("Java", "Kotlin"));
System.out.println(clean.contains("World")); // true
System.out.println(clean.startsWith("Hello")); // true
System.out.println("ab".repeat(3)); // ababab
System.out.println(" ".isBlank()); // true
text.toLowerCase(); // result thrown away!
System.out.println(text.length()); // still 21
}
}Comparing text: equals, not ==
This is the number one mistake with String. The == operator checks whether two variables point to the same object in memory, not whether the content is equal. It sometimes seems to work because Java reuses identical literals, but it fails with texts created at run time, for example those the user types. Always use equals to compare content, or equalsIgnoreCase if case does not matter, and compareTo to sort alphabetically.
public class Main {
public static void main(String[] args) {
String a = "java";
String b = new String("java"); // forces a new object
System.out.println(a == b); // false: different objects
System.out.println(a.equals(b)); // true: same content
System.out.println("JAVA".equalsIgnoreCase(a)); // true
System.out.println("apple".compareTo("banana") < 0); // true
// Splitting and joining
String csv = "ana,luis,marta";
String[] names = csv.split(",");
System.out.println(names.length); // 3
System.out.println(names[1]); // luis
System.out.println(String.join(" | ", names)); // ana | luis | marta
// Formatting
String line = String.format("%s has %d points (%.1f%%)", "Ana", 42, 87.456);
System.out.println(line); // Ana has 42 points (87.5%; 87,5% in some locales)
// Text block (Java 15+)
String json = """
{
"name": "Ana",
"age": 30
}
""";
System.out.print(json);
}
}Formatting, text blocks and StringBuilder
String.format uses placeholders: %s for text, %d for integers, %.2f for decimals with two digits and %% for a literal percent sign. Text blocks (three double quotes) let you write several lines without concatenating or escaping quotes; Java trims the common indentation. If you need to build a large text inside a loop, use StringBuilder: since String is immutable, concatenating hundreds of times creates hundreds of intermediate objects, while StringBuilder changes a single buffer.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i);
if (i < 5) sb.append("-");
}
System.out.println(sb); // 1-2-3-4-5
System.out.println(sb.reverse()); // 5-4-3-2-1
String result = sb.toString(); // back to a String
System.out.println(result.length()); // 9
// Palindrome check using only String methods
String word = "Level";
String lower = word.toLowerCase();
String reversed = new StringBuilder(lower).reverse().toString();
System.out.println(lower.equals(reversed)); // true
}
}Frequent mistakes with String
- StringIndexOutOfBoundsException: using charAt or substring with an index out of range. Always check length() first.
- Forgetting that substring(start, end) excludes the end position: "Java".substring(0, 2) gives "Ja".
- split takes a regular expression: to split on a dot you must write split("\\."), not split(".").
- Concatenating with + inside a long loop: use StringBuilder.
- Comparing with == instead of equals.
With these methods you can already solve real tasks: clean the user input with strip, check whether an email contains an at sign with contains, extract the domain with substring and indexOf, or break a file line apart with split. Practice each method in jshell before using it in a program; seeing the result instantly is the best way to fix what it does in your mind.
Testez vos acquis
Question 1 sur 1How do you compare the content of two Strings?
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères