aspose file tools*
The moose likes Beginning Java and the fly likes why..?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why..??" Watch "why..??" New topic
Author

why..??

rani bedi
Ranch Hand

Joined: Feb 06, 2001
Posts: 358
char x = 'a';
System.out.println( x + 1);
char y = 'a' + 1;
System.out.println( y);
Why is the output different in these two cases?
In the first case output = 98
and for the second case = b


Cheers,<br />Rani<br />SCJP, SCWCD, SCBCD
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Parmeet
In the first two lines:
char x = 'a';
System.out.println( x + 1);

You're taking a char literal and adding it to an int and printing the result. Remember that all integer addition with byte, char, and short is promoted to int. The int value of 'a' is 97 so it adds 1 to 97 and prints the answer.
In the second two lines:
char y = 'a' + 1;
System.out.println( y);

You're doing the addition in the first line and then putting it back into a char, then printing the char, not an int.
Keep in mind that this onlyworks without a cast because your using literals. If you did this it wouldn't compile:

hope that answers your questions

Dave

Dave
Cundra Mundra
Greenhorn

Joined: Apr 16, 2001
Posts: 11
OK Dave,
Shouldn't you get an error for demotion from int to char? You would have to cast it, wouldn�t you? I am not sure if I am pooling this now from C++ or something else.
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Cundra,
No you wouldn't get a compiler error because the 'a' + 1 is taken as a literal value by the compiler. In other words the 'a' + 1 is replaced by 98 by the compiler. So the compiler really sees:
c = 98;
which is a valid statement!
Regards,
Manfred.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why..??