wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt on Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt on "?" operator" Watch "doubt on "?" operator" New topic

doubt on "?" operator

ansuman mohapatra

Joined: Mar 04, 2008
Posts: 27

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

Cleared SCJP.....
Kishore Kumar
Ranch Hand

Joined: Oct 15, 2007
Posts: 71
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

Joined: Dec 17, 2007
Posts: 180

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

Joined: Jan 22, 2008
Posts: 135
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

Joined: Mar 04, 2008
Posts: 27
yea dats helped..thanks
I agree. Here's the link: http://aspose.com/file-tools
subject: doubt on "?" operator
It's not a secret anymore!