Unexpected java charAt output

The code is

String veggie = "eggplant";
int length = veggie.length();
char zeroeth = veggie.charAt(0);
char third = veggie.charAt(4);
String caps = veggie.toUpperCase();
System.out.println(veggie + " " + caps);
System.out.println(zeroeth + " " + third + " " + length);
System.out.println(zeroeth + third + length);

The output reads:

eggplant EGGPLANT   
e 1 8   
217

This doesn't make sense to me. Referencing a charAt outputs numbers instead of characters. I was expecting it to output the characters. What did I do wrong?

Jon Skeet
people
quotationmark

The second line should actually be:

e l 8

(note that the second value is a lower-case L, not a 1) which probably doesn't violate your expections. Although your variable is confusingly called third despite it being the fifth character in the string.

That just leaves the third line. The type of the expression

zeroeth + third + length

is int... you're performing an arithmetic addition. There's no implicit conversion to String involved, so instead, there's binary numeric promotion from each operand to int. It's effectively:

System.out.println((int) zeroeth + (int) third + (int) length);

It's summing the UTF-16 code units involved in 'e', 'l' and 8 (the length).

If you want string conversions to be involved, then you could use:

System.out.println(String.valueOf(zeroeth) + third + length);

Only the first addition needs to be a string concatenation... after that, it flows due to associativity. (i.e. x + y + z is (x + y) + z; if the type of x + y is String, then the second addition also becomes a string concatention.)

people

See more on this question at Stackoverflow