String
indexing and the charAt
method
String name = "Brandon";
// 0123456
char letter = name.charAt(0);
System.out.println(letter); // prints B
letter = name.charAt(2);
System.out.println(letter); // prints a
letter = name.charAt(name.length() - 1);
System.out.println(letter); // prints n
// Each of the lines below throws a StringIndexOutOfBoundsException.
letter = name.charAt(name.length()); // name.length() returns 7
letter = name.charAt(7);
letter = name.charAt(-1);
The characters in a String
are indexed from 0 up to but not including the length.
The charAt
method returns the character at the specified position in a String
as a char
. Working with char values demonstrates the char
type.
Material covered on other site
String
objects are used extensively on the AP CS A Exam. The pages linked below cover the parts of the String
class featured on the AP CS A Exam.
Strings on the AP CS A Exam has demonstrations of these topics.
- Comparing
String
objects for equality using theequals
method - The
length
method - Getting part of a
String
using the 2substring
methods - Finding a
String
inside anotherString
using theindexOf
method - Concatenating (putting together)
String
objects using the+
and+=
operators, including converting other types String
immutability
compareTo on the AP CS A Exam demonstrates how to compare String
objects for order (see which comes first).
Converting a char
into a String
char letter = 'a';
String str = "" + letter;
After this code segment, str
stores a reference to "a"
(a String
).
String
concatenation can be used to convert a char
into a String
. ""
is the empty String
. When at least 1 operand of the +
operator is a String
, the operator behaves as concatenation.