user3712088
user3712088

Reputation: 11

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?

Upvotes: 1

Views: 270

Answers (4)

David SN
David SN

Reputation: 3519

You can use the method of the wrapper class Character to display the string values of char variables:

System.out.println(Character.toString(zeroeth) + Character.toString(third) + length);

This way, you always work with String values and there are no possibilities for the numeric values of the chars to be displayed or added and you don't need to concatenate with empty strings ("") to convert the char variables to String values.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500385

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

Upvotes: 5

Edwin Torres
Edwin Torres

Reputation: 2864

This line is doing integer arithmetic:

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

In other words, it is adding the unicode values of each character (i.e. e is 101, l is 108, 8 is 8). To do String concatenation, you can add an empty String to the front:

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

Since it is evaluated left-to-right, it will first do String concatenation (not addition). It will continue to do this for third and length. Adding "" at the end won't work, because addition will occur first.

Upvotes: 0

TinkerTank
TinkerTank

Reputation: 5805

The compiler interprets all variables as values rather than a string.

Try System.out.println("" + zeroeth + third + length);

Upvotes: 0

Related Questions