File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why..??

 
rani bedi
Ranch Hand
Posts: 358
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dave Vick
Ranch Hand
Posts: 3244
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Cundra Mundra
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1492
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic