• 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

Casting before or after operation and main method

 
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi everybody,
Consider the following piece of code :

double h=0.0;
int f=2,g=5;
h=3+f/g+2;
The value of h printed is 5.0. But I think it should be 5.4
because the casting is done before operation.So, the int f & g willbe cast to double before addition.
One more question
If the main method calls another method then is main method called that method's parent? Is the main method always called by the system during start up?
 
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Assignment operator has lower precedence than arithmetic operations. So the arithmetic operations are performed first (hence the integer division) and the result is promoted to double when the assignment happens.
Hope this helps.
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This should hopefully explain why.
<pre>
class PrimConvert {
double h = 0.0, k = 2.0;
int f = 2, g = 5;
public static void main (String[] args) {
PrimConvert pc = new PrimConvert();
pc.h = 3+pc.f/pc.g+2;
System.out.println(pc.h);
pc.h = 3+pc.k/pc.g+2;
System.out.println(pc.h);
}
}
OUTPUT:
5.0
5.4
</pre>
promotion is done based on the operand types. In this case, the division operation has precedence. Both operands are integers. Hence, 2/5 will result in 0. The addition operations are done left to right so 3+0+2 results in 5.
Now, my second example uses a double in place of the integer in the division operation. So we have 2.0/5 which causes the compiler to promote 5 to a double. This results in 0.4. Doing addition left to right. 3+.4 will cause 3 to be promoted to 3.0. This results in 3.4. The last addition will be 3.4+2. Same scenario as before with the promotion. Final result is 5.4 and gets assigned to h which is a double already.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic