C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: For a three-character string, the valid indexes are 0, 1 and 2. The last index is equal to the length minus 1.
Java program that uses charAt, for-loop
public class Program {
public static void main(String[] args) {
String value = "cat";
// Loop through all characters in the string.
// ... Use charAt to get the values.
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
System.out.println(c);
}
}
}
Output
c
a
t
Java program that uses first, second, last characters
public class Program {
public static void main(String[] args) {
String value = "intercept";
// First two characters.
System.out.println(value.charAt(0));
System.out.println(value.charAt(1));
// Last two characters.
System.out.println(value.charAt(value.length() - 1));
System.out.println(value.charAt(value.length() - 2));
}
}
Output
i
n
t
p
Note: In real programs, it is typically faster to check before accessing an index. Causing an exception is slow.
Java program that causes charAt exception
public class Program {
public static void main(String[] args) {
String value = "abc";
// Access a character out-of-range.
char error = value.charAt(100);
System.out.println(error); // Not reached.
}
}
Output
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException:
String index out of range: 100
at java.lang.String.charAt(Unknown Source)
at Program.main(Program.java:6)
Version 1: This version of the code uses charAt to test a character in a string. It also uses an if-statement.
Version 2: Here we use substring: we get a 1-character substring from the string, and test it in an if-statement.
SubstringResult: Using charAt to test a character is many times faster than taking a 1-character substring.
Java program that times charAt versus substring
public class Program {
public static void main(String[] args) {
// The example string.
String value = "cat";
// Test results of our methods.
System.out.println(value.charAt(2));
System.out.println(value.substring(2, 3));
long t1 = System.currentTimeMillis();
// Version 1: use charAt to test characters in a string.
int count = 0;
for (int i = 0; i < 10000000; i++) {
if (value.charAt(2) == 't') {
count++;
}
}
long t2 = System.currentTimeMillis();
// Version 2: use substring to test characters in a string.
count = 0;
for (int i = 0; i < 10000000; i++) {
if (value.substring(2, 3) == "t") {
count++;
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(count);
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
t
t
0
5 ms: charAt
114 ms: substring