Which String methods come up most often in Java interviews, and what does each one actually do?
These are the ones that come up again and again, and it is worth knowing exactly what each one does.
length gives you the number of characters. It is a property and not a method, so you write text.length() with the brackets but no arguments. The method isEmpty tells you whether there are no characters at all, and it is the one to use when you want to check for empty text.
charAt gives you the character at one position. The position starts at zero, so the first character is at position zero.
indexOf gives you the position of the first place where some text appears, and it gives you -1 when the text is not there. The version lastIndexOf works from the end of the string backwards.
substring gives you a piece of the text. The first position is included and the last one is not, so text.substring(0, 5) gives you the first five characters. That rule catches everybody once, because it is the other way round from the way that people usually count.
toUpperCase and toLowerCase give you a new string in the other case.
trim and strip remove the whitespace at the ends. The method strip is the newer one and it understands more kinds of space.
equals compares two strings by their text, and equalsIgnoreCase does the same without caring about capital letters.
split cuts a string into an array of pieces, and replace swaps one piece of text for another.
public class Main {
public static void main(String[] args) {
String text = " Hello World ";
System.out.println("length : " + text.length());
System.out.println("trimmed : " + text.trim());
System.out.println("upper : " + text.trim().toUpperCase());
System.out.println("char at 0 : " + text.trim().charAt(0));
System.out.println("index of World: " + text.indexOf("World"));
System.out.println("not there : " + text.indexOf("Missing"));
System.out.println("substring : " + text.trim().substring(0, 5));
System.out.println("equals : " + text.trim().equals("Hello World"));
System.out.println("split count : " + text.trim().split(" ").length);
}
}
One warning is worth giving. The methods substring, toUpperCase and trim do not change the string. They give you a new one, and the original is untouched.
The next question in this topic looks at a common puzzle that uses the methods above.