This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operators

 
Swati Thorve
Ranch Hand
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody tell me the order of evaluation for string s

public class Question49 {
public static void main(String[] args) {
boolean b = false;
String s =
(b=!b)?(b=!b)?"Hello":"hello": ( b=!b)?"world":"World";
System.out.println(s);
}
}


The options are
A.Prints: Hello
B. Prints: hello
C. Prints: Helloworld
D. Prints: helloWorld
E. Compilation error.

Correct answer is B

Plzz explain this.

[ January 05, 2006: Message edited by: Swati Thorve ]

[ January 05, 2006: Message edited by: Swati Thorve ]
[ January 05, 2006: Message edited by: Swati Thorve ]
 
Mehul Sanghvi
Ranch Hand
Posts: 134
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s =
(b=!b)?(b=!b)?"Hello":"hello": ( b=!b)?"world":"World";

The first (b=!b) is evaluated to true and hence the control comes to second (b=!b) which will now be evaluated to false and hence the value of "hello" will be assigned to String s.

A possible catch here is = vs. ==
The expn (b=!b) is actually an assignment operation rather then a conditional statement (which is generally expected in ternary operators).

Regards.
 
Thomas De Vos
stable boy
Ranch Hand
Posts: 425
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's play compiler here ...


1. I'm adding brackets



2. I'm adding more brackets




3. I'm assigning !b to b




4. I'm evaluating the first condition ...



5. I'm assigning !b to b again






6. Got my result

 
Swati Thorve
Ranch Hand
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Mehul
 
Swati Thorve
Ranch Hand
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Thomas,For such a wonderful explanation.Thank u very much
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic