Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arithmetic promotion

 
Raj Neets
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai
The following is a piece of code, in which i try to use x=x"op"y operator. I have a doubt , whether there is any Arithmetic promotion applied when two different type of primitive date type is involved.
double b= 8.0;
byte c=10;
c+=b;
i tried this, but there is no compiler error.
Thanx
raj
 
Jasper Vader
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there Raj,
it is sort of the same as this situation...
byte b;
b++; // no problem...
byte b = b + 1; // compiler error
so if you want to make a compiler error, rearrange the wording of your code like this...
class MathStuff {
public static void main(String args[]) {
double b= 8.0;
byte c=10;
c = c + b; // compiler error here!
}
}
so the compiler does a short cut for you, in that it casts it as a byte for you when you type the addition the way you did.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no compiler error because this happens:
 
Jasper Vader
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
congrats Barry on a somewhat more succinct answer
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is suitable JLS 5.6 Numeric promotions
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic