Strings
The basics
public class Main {
public static void main(String[] args) {
String course = "Java Programming";
System.out.println(course.length()); // 16
System.out.println(course.charAt(0)); // J
System.out.println(course.indexOf("Pro")); // 5
System.out.println(course.substring(5)); // Programming
System.out.println(course.substring(0, 4)); // Java
System.out.println(course.toUpperCase()); // JAVA PROGRAMMING
System.out.println(course.contains("gram")); // true
}
}Positions start at 0. substring(start, end) includes start and stops just before end. indexOf returns -1 when the text isn't found.
Strings never change
public class Main {
public static void main(String[] args) {
String name = "asha";
name.toUpperCase(); // makes a new String, which is thrown away
System.out.println(name); // asha
name = name.toUpperCase(); // keep the new String
System.out.println(name); // ASHA
}
}Strings are immutable: methods like toUpperCase and replace return a new String and leave the original untouched.
Comparing: equals, not ==
public class Main {
public static void main(String[] args) {
String a = "hello";
String b = new String("hello");
System.out.println(a == b); // false: two different objects
System.out.println(a.equals(b)); // true: the same text
System.out.println("Hello".equalsIgnoreCase("HELLO")); // true
System.out.println("apple".compareTo("banana") < 0); // true: apple sorts first
}
}== asks whether two variables refer to the same object. equals asks whether the text is the same, which is nearly always what you mean.
Everyday methods
public class Main {
public static void main(String[] args) {
String raw = " Learn Java Today ";
System.out.println("[" + raw.trim() + "]"); // [Learn Java Today]
System.out.println(raw.trim().replace("Java", "Python")); // Learn Python Today
System.out.println("ha".repeat(3)); // hahaha
System.out.println("report.pdf".endsWith(".pdf")); // true
System.out.println("".isEmpty() + " " + " ".isBlank()); // true true
String csv = "Asha,Leo,Mei";
String[] names = csv.split(",");
System.out.println(names.length + " names, first is " + names[0]);
System.out.println(String.join(" | ", names)); // Asha | Leo | Mei
}
}Building strings in a loop: StringBuilder
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.toString()); // 1, 2, 3, 4, 5
System.out.println(sb.reverse()); // 5 ,4 ,3 ,2 ,1
}
}Because Strings never change, every + creates a brand-new String. In a loop that runs thousands of times, that's a lot of waste. A StringBuilder is a growable buffer: append as much as you like, then call toString() once.
Formatted output
public class Main {
public static void main(String[] args) {
String name = "Mei";
double score = 92.456;
int rank = 3;
System.out.println(String.format("%s scored %.1f (rank %d)", name, score, rank));
System.out.printf("%-8s|%6.2f|%n", name, score);
System.out.printf("%05d%n", 42);
}
}| Specifier | Means |
|---|---|
%s | a String (or anything, via toString) |
%d | a whole number |
%.2f | a decimal number with 2 places, rounded |
%n | a line break |
%-8s | left-aligned in a column 8 characters wide |
%05d | padded with zeros to 5 digits |
Text blocks
Since Java 15, three double quotes start a multi-line text block, with no \n or + needed:
public class Main {
public static void main(String[] args) {
String json = """
{
"course": "Java",
"lessons": 23
}
""";
System.out.print(json);
}
}The indentation shared by every line is removed, so the block can be indented to match your code.