charAt()

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        
String dryden = "   None but the brave deserves the fair.   " ;
System.out.println( "|" + dryden.trim() + "|" );

Answer:

|None but the brave deserves the fair.|

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).

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

The return values are primitive char data, hence the values are delimited by single quotes, as in 'S'. String literals would be delimited by double quotes, as in "R".

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. It has no methods or other data.

QUESTION 16:

What is the output of the following fragment:

String singleA = "A" ;
String singleB = new String( "B" );

System.out.println( singleA.length() );
System.out.println( singleA.concat( singleB ) );

What is wrong with the following fragment:

char oneC = 'C' ;
char oneD = new char( 'B' );

System.out.println( oneC.length() );
System.out.println( oneD.concat( oneC ) );