• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt on "?" operator

 
ansuman mohapatra
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am completely lost on the following question


1. public class Test {
2. public static void main(String[] args) {
3. boolean b = false;
4. String s = (b=!b)?(b=!b)?"Hello":"hello" b=!b)?"world":"World";
5. System.out.println(s);
6. }
7. }

answer is hello...

i don understand how come hello is coming although it will be coming as

String s = true ? false? "Hello":"hello" so true or false should yield true rite...then "Hello" should come

and about the 2nd part im not able to get it how its operating.

please clarify
 
Kishore Kumar
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
boolean b = false;
String s = (b=!b)?(b=!b)?"Hello":"hello" b=!b)?"world":"World";

Terinary operators have assositivity from Right to left.
So, the above expression becomes

String s = (b=!b)?((b=!b)?"Hello":"hello") (b=!b)?"world":"World");
So first, this executes:-((b=!b)?"world":"World")
Result is: world and boolean b = true.
Expression becomes:
String s = (b=!b)?((b=!b)?"Hello":"hello"): world
Now, (b=!b)?"Hello":"hello" executes:
Result is: hello and boolean b = false.
So expression becomes: String s = (b=!b)? "hello":"world"
Finally out put is: hello.

I hope i explained clearly.
 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is that your expression :-

String s = (b=!b)?(b=!b)?"Hello":"hello":"World";

if this then it is evaluted as:



Is that helpfull !!!
 
Prabhat Gupta
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
boolean b = false;
String s = (b=!b)?(b=!b)?"Hello":"hello" b=!b)?"world":"World";


initially boolean b is "false". the ? operator works as
boolean-condition ? Experssion1:Expression2 ,if boolean condition is true it will evaluate the expression1 otherwise it will evaluate expression2.

Here boolean condition (b=!b) evaluated as b=!(false) =>b=true =>true
hence exprsesion1 (b=!b)?"Hello":"heelo" will be eavluated . Again here boolean condition (b!=b)will be evaluated as b=!(true)[since from last condition b is now "true" ]=>b=false =>false. Consequently the expression2 will be evaluated which is "hello",finally string s is assigned a value "hello".

hope it is clear to you.
 
ansuman mohapatra
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yea dats helped..thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic