Getting the nth character in a String

suggest change
String str = "My String";

System.out.println(str.charAt(0)); // "M"
System.out.println(str.charAt(1)); // "y"
System.out.println(str.charAt(2)); // " "
System.out.println(str.charAt(str.length() - 1)); // Last character "g"

length is not a field. The method is length().

To get a UTF-16 code unit by index, call charAt(n). n starts at 0. An index past the last unit, or a negative index, throws StringIndexOutOfBoundsException. A code point above U+FFFF occupies two indexes, so charAt can return one half of a surrogate pair.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents