Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

operstor conversions  RSS feed

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI EVERY BODY,
can you please tell me the output of the following programs.... i was just going through some java mock question papers....

class A {
public static void main(String[] args) {
char a = 'a', b = 'b'; // 'a' = 97, 'b' = 98
System.out.print(a + b + "" + a + b);
}}

thanks
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
output is: 1959798

+ is work as following ways

1) if 2 operands are numeric it will work as a addition operator

2) if atleast one is string then it will work as a concatnation operator
 
rahul mehra
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi raghu... thanks for your reply... i saw the answer and it says that the answer would be '195ab' what i dont understand is why the first two operators are taken as the ascii values given and the rest as the characters as they are assigned in the program......
 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The compilator reads from left to right.
So first we have a + b so it treats them like numbers
97 + 98 = 195
then it has :
195 + "" -> so the otput is String "195"
next

we have "195" + a - so if one of the element is String, the compilator treats + as concatenation, so it changes a to String;

and last:
"195a" + b = "195ab";
 
rahul mehra
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks... Kuba...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!