• 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:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Operators and assignments

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a program I saw in Jarowski's book
class Sub
{
public static void main(String ards[])
{
int x = 0;
boolean b1, b2, b3, b4;
b1 = b2 = b3 = b4 = true;

x = ( b1 | b2 & b3 ^ b4) ? x++ : --x;
System.out.print(x);
}
}
The o/p is 0(zero). Can anybody pls explain me why ?
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
x = (b1|b2&b3^4) ? x++ : --x;
The expression can be solved in the following manner:
Using the following operator preceence:
1> & AND
2> ^ XOR
3> | OR
x = (true | ( true & true ) ^ true) ----- 1
x = (true | (true ^ true ) ) -------------2
x = (true | false) -----------------------3
x = true
x evaluates to true so the answer is 0.
Please correct if I am wrong!
Regards,
Milind
 
shatabdi
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Milind,
The expression x = (b1|b2&b3^b4) ? x++ : --x; means
if(b1|b2&b3^b4)
x = x++;
else
x = --x;
System.out.print(x)
Now the boolean codn (b1|b2&b3^b4) returns true. So x = x++ should execute. My question is then x should be 1 instead of zero(because of x++)in the o/p. I just don't know why it is showing zero !
shatabdi
 
Ranch Hand
Posts: 1467
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See this line CAREFULLY.
x=x++; //x = 0[1] which means the LHS is assigned a value 0 which is happened to be x itself. x is incremented and then again assigned to the pre-increment value.
 
shatabdi
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Maha Anna.
 
Getting married means "We're in love, so let's tell the police!" - and invite this tiny ad to the wedding:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic