简体   繁体   中英

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?

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. (ie x + y + z is (x + y) + z ; if the type of x + y is String , then the second addition also becomes a string concatention.)

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

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

This line is doing integer arithmetic:

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

In other words, it is adding the unicode values of each character (ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM