Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Conditional if

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henrik,thanks.You are right.I also figured it.
 
mohit junejaa
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chandra Sagi
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How does the associativity of the ?: operator factor in to the evaluation of the expression?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic