Strings come with tools
A String is not just text – it comes with many built-in methods (tools). You use a method by writing a dot after the string: name.length().
public class Main {
public static void main(String[] args) {
String word = "Java Rocks";
System.out.println(word.length());
System.out.println(word.toUpperCase());
System.out.println(word.toLowerCase());
System.out.println(word.contains("Rock"));
System.out.println(word.replace("Rocks", "Rules"));
System.out.println(word.startsWith("Ja"));
}
}Output
10 JAVA ROCKS java rocks true Java Rules true
Positions start at 0
Every character in a string has a position number called an index. The first character is at index 0, not 1:
| J | a | v | a |
|---|---|---|---|
| 0 | 1 | 2 | 3 |
Think of it like this: Think of floors in some buildings: the bottom floor is the “ground floor” (0), then floor 1, floor 2...
public class Main {
public static void main(String[] args) {
String word = "Java";
System.out.println(word.charAt(0));
System.out.println(word.charAt(3));
System.out.println(word.indexOf("v"));
System.out.println(word.indexOf("z"));
}
}Output
J a 2 -1
indexOf gives the position of the first match, or -1 if it isn't there.
Cutting out a piece: substring
substring(start, end) gives the characters from start up to, but not including, end. With only one number, it goes to the end:
public class Main {
public static void main(String[] args) {
String email = "asha@vulntech.com";
int at = email.indexOf("@");
System.out.println(email.substring(0, at));
System.out.println(email.substring(at + 1));
}
}Output
asha vulntech.com
Cleaning and splitting
public class Main {
public static void main(String[] args) {
String messy = " hello ";
System.out.println("[" + messy.trim() + "]");
String fruits = "apple,banana,mango";
String[] parts = fruits.split(",");
System.out.println(parts[0]);
System.out.println(parts[2]);
System.out.println(parts.length);
}
}Output
[hello] apple mango 3
trim() removes spaces at both ends. split cuts a string into pieces – you'll learn more about the String[] (array) it gives back in the Arrays module.
Common mistake: Asking for an index that doesn't exist crashes the program:
public class Main {
public static void main(String[] args) {
String word = "Java";
System.out.println(word.charAt(4));
}
}Output (Java stops with an error)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4