• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Ternary Operator

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please go through the following code:
public class TerOp{
public static void main(String asd[]){
int x=0;
x=(true) ? x++ : x--;
System.out.println("x= "+x);//1
}
}
It gives the value of x as 0 at line 1.
Can somebody explain why this is so?
Thanks.
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The statement
x=(true) ? x++ : x--;
can be reduced to
x = x++;
The expression x++ will return the value of x which is zero. Before the assignment operation is complete the value of x is incremented. After the increment operation is complete the previous value of x, which was zero, is assigned to x.
The following code example demonstrates that the value of x is indeed incremented before the expression is completely evaluated.


The answer is b, "Prints: 1.0".


The statement contains an addition operation. The left operand is a postfix operation and it is evaluated first. The result of the postfix operation is zero, but variable i is incremented as a side effect. The right hand operand of the addition operation is the result of method m. As a side effect, method m prints the current value of variable i which is one. Method m then returns the value zero. The result of the addition operation is zero and that is the value that is assigned to variable i.

 
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First <condition>? <expression1> : <expression2>
If condition is true, then expression 1 is evaluated and expression 2 is not.
x++ will use the original value of x (0) and then increment x to be equal (1)
Yet the equality operator (=) will assign the value (0) that came out of the ? : to x after all this happen, so x becomes back 0 after it was incremented to 1
if you change the x++ to ++x it will print 1
HTH
 
sunetra sen
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks guys !javascript: x()
 
reply
    Bookmark Topic Watch Topic
  • New Topic