Damian Louden
Damian Louden

Reputation: 11

Why do these Print Statements Come Out Different?

String test = (String)String.valueOf(((char) 0 + 65));
System.out.println( test);
test = "A"; 
System.out.println(test);

The first one produces 65, the other produces A. They should produce the same thing.

Upvotes: 1

Views: 47

Answers (3)

Andrzej Doyle
Andrzej Doyle

Reputation: 103817

This is due to the operator precedence (of casting, relative to addition) not being what you expect.

You expect 0 + 65 to happen first, and then for the result to be cast to a char. However, the cast binds more tightly than addition, so (char) 0 happens first, and then it is added to 65.

Since this is two numbers being added together, the result is a numeric 65, and this is what gets converted into a String (so results in the two character string ['6', '5'].

You can make the casting happen later with brackets around the arithmetic expression:

String.valueOf((char)(0 + 65))

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533660

The first expression is the same as

(char) 0 + 65

is

`\0` + 65

which is

(int) `\0` + 65

or

65

This is because casting takes precedence.

To get a char type and A you need to cast after you do the calculation

char ch = (char) (0 + 65)
System.out.println(ch);

Upvotes: 0

kai
kai

Reputation: 6887

You do it in the wrong order. First you cast zero to char and the you add 65 which is an implicit cast to int. You first need to add the values and then do the cast.

 String test = String.valueOf((char)( 0 + 65));

Then your code produce the expected result:

A
A

Upvotes: 4

Related Questions