Java String Methods
String methods are actions that a string value can perform. Each method takes the text it runs on and returns a result.
Count the characters and change the case
The length call counts the characters in the word. The other two calls return the word in a new case.
public class Main {
public static void main(String[] args) {
String word = "Java";
System.out.println(word.length());
System.out.println(word.toUpperCase());
System.out.println(word.toLowerCase());
}
}Find a position and read a character
The indexOf call finds where a part of the text starts. The charAt call reads the character at one position.
public class Main {
public static void main(String[] args) {
String word = "Java";
System.out.println(word.indexOf("va"));
System.out.println(word.charAt(0));
}
}Case decides the equality verdict
The equals call counts the case difference as a difference. The equalsIgnoreCase call treats the two texts as the same.
public class Main {
public static void main(String[] args) {
String first = "Java";
String second = "JAVA";
System.out.println(first.equals(second));
System.out.println(first.equalsIgnoreCase(second));
}
}Example
public class Main {
public static void main(String[] args) {
String city = "Lisbon";
System.out.println(city.length());
System.out.println(city.charAt(0));
System.out.println(city.toUpperCase());
System.out.println(city.indexOf("bon"));
}
}Key points
- The length method counts the characters in a string.
- The toUpperCase method returns the text in capital letters.
- The toLowerCase method returns the text in small letters.
- The indexOf method returns the position of the first match.
- The charAt method returns the character at one position.
- The equals method compares text exactly, case included.
- The equalsIgnoreCase method compares text without matching the case.
In this example, city holds Lisbon. The length call counts 6 characters, and the charAt call reads L at position 0. The remaining calls print LISBON and the position 3, where bon starts.
Note
Positions in a string count from 0, so the first character sits at position 0.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does the length method return for the string "Java"?