• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Modulo operator and unary operator

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1)Consider the following code
double d = 12.31;
float f = 12.31F;
System.out.println(d%f);
/*
This prints 12.31 not 0.0.WHY??
*/
System.out.println(f%d);
/*
This prints 4.196e-7
*/
byte b =12;
System.out.println(d%b);
/*
This prints 0.31000000005
*/
In all the above cases arithmetic promotion of operands must be taking place.
So why d%f gives the original number and not 0.0?And why d%b will give the right answer?
If byte b is being promoted to double then why not float?

2)Consider the following code:
int a=7;
a=a++;
System.out.println("a="+a);
This prints a=7 and not a=8.Then what happens to the unary increment operator?
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
1) While promoting the float value 12.31 to double it actually becomes 12.3100004196167 (!!! well this is bcoz of the way these nos are represented ) which is slightly larger that 12.31.
so
double d = 12.31;
float f = 12.31F; // ( cast to double makes it 12.3100004196167 )
System.out.println(d%f);
gives 12.31 ( d < f ) .. so floating point remainder becomes 12.31
whereas
System.out.println(f%d); gives the extra .0000004196167 )
2. Guess thats bcoz simple assignment is done in three steps
a) The LHS is evaluated to ptoduce a variable ( already a variable in this case )
b) the value of the RHS is evaluated ( == 7 ) .. the Right hand expression also makes the value of a to be 8 ..
c) the value of the RHS( 7 ) is assigned to the LHS. ( thus we assign 7 to a again )
cheers,
vivek
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey thanks vivek.Really appreciate it.Thanks again
 
Life just hasn't been the same since the volcano erupted and now the air is full of tiny ads.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic