File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Conditional if Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Conditional if" Watch "Conditional if" New topic
Author

Conditional if

Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 477

class EBH023 {
static String m1(boolean b){
return b?"T":"F";
}
public static void main(String [] args) {
boolean b1 = false?false:true?false:true?false:true;
System.out.prinln(b1);
}
}
[/CODE]


When I work on that b1

B1 = false?false:true?false:true?false:true;

b1 = true ?false:true?false:true;
b1 = false ?false:true;
b1 = true;

but this b1 output is false ?How?

Please help me.
Henrik Engert
Ranch Hand

Joined: Apr 26, 2005
Posts: 70


I would think you go from right to left:

true?false:true = true
true?false:true = true
false?false:true = false

Maybe you can see it this way:

(false?false true?false true?false:true)));


m1 returns "F"

Not sure...I am still learning.


SCJP 5.0, SCWCD
Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 477
Henrik,thanks.You are right.I also figured it.
mohit junejaa
Ranch Hand

Joined: Feb 24, 2006
Posts: 41
Originally posted by Shiva Mohan:

class EBH023 {
static String m1(boolean b){
return b?"T":"F";
}
public static void main(String [] args) {
boolean b1 = false?false:true?false:true?false:true;
System.out.prinln(b1);
}
}
[/CODE]


When I work on that b1

B1 = false?false:true?false:true?false:true;

b1 = true ?false:true?false:true; //THIS STATEMENT WILL MAKE B1
FALSE
BECAUSE CONDITION IS TRUE

b1 = false ?false:true;
b1 = true;

but this b1 output is false ?How?

Please help me.


scjp 1.4
Chandra Sagi
Ranch Hand

Joined: May 05, 2005
Posts: 162
The terinary operator behaves similar to && and ||. These operators does not evaluate the second expression if they are satisfied with the first expression itself. For example if the first expression is false in an && operator, the second expression is not evaluated, because it expects both to be true. In your expression for the second time when it sees a true?false:........., it takes only false and not evaluate the second part.

Thanks
Chandu
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
How does the associativity of the ?: operator factor in to the evaluation of the expression?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Conditional if
 
Similar Threads
Whats the answer FFT how?
group conditional operators
Operators - Dan Chisholm question
Conditional Operator ?:
conditional expression chaining