Strings and Object References in Java
16. charAt()
Answer:
|None but the brave deserves the fair.|
charAt()
charAt()
The charAt(int index)
method returns a single character at the specified index. If the index is negative, or greater than length()-1
, an IndexOutOfBoundsException
is thrown (and for now
your program stops running).
The value returned by charAt(int index)
is a char
, not a String
containing a single character. A char
is a primitive data type, consisting of two bytes that encode
a single character.
Expression | Result |
---|---|
String source = "Subscription"; |
"Subscription" |
source.charAt(0) |
'S' |
source.charAt(1) |
'u' |
source.charAt(5) |
'r' |
source.charAt(source.length()-1) |
'n' |
source.charAt(12) |
IndexOutOfBoundsException |
Question 16:
What is output by the following fragment:
System.out.println( ("Orange " + "Soda").charAt( 7 ) );