Tino APCS

String Query Methods

Query Method Sample Syntax
int length(); String str1 = "Hello!";
int len = str1.length(); // len == 6
char charAt(int index); String str1 = "Hello!";
char ch = str1.charAt(0); // ch == 'H'
int indexOf(String str); String str2 = "Hi World!";
int n = str2.indexOf("World"); // n == 3
int n = str2.indexOf("Sun"); // n == -1
int indexOf(char ch); String str2 = "Hi World!";
int n = str2.indexOf('!'); // n == 8
int n = str2.indexOf('T'); // n == -1


The int length() method returns the number of characters in the String object.

The charAt method is a tool for extracting a character from within a String. The charAt parameter specifies the position of the desired character (0 for the leftmost character, 1 for the second from the left, etc.). For example, executing the following two instructions prints the char value 'X'.

String stringVar = "VWXYZ"
System.out.println(stringVar.charAt(2));


The int indexOf(String str) method will find the first occurrence of str within this String and return the index of the first character. If str does not occur in this String, the method returns -1.

The int indexOf(char ch) method is identical in function and output to the other indexOf function except it is looking for a single character.

Dark Mode

Outline