• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

when arithmetic opearations are performed

 
Vaibhav Chauhan
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was is happy with my concept that arithmetic operations are performed at runtime and compiler doesn't bother about it until i see the output of following code:

public class TestFinalVariables {

public static void main(String []argv)
{
final int firstInt=12, secondInt=5;
byte b=firstInt+secondInt;

System.out.println("7 + 5: "+b);
}
}

compiler doesn't complain anything wrong in the code and output is
"7 + 5= 12"

but compiler starts complaining that int can't be converted to byte when i make following changes:

final int firstInt=125, secondInt=5;

it means that arithmatic operations are performed at compile time ???
confused
 
Chetan Raju
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since you are using final constants and adding them up and assigning them to a byte variable, the checking is performed at compile time itself since they are constant evaluations. And since the addition operation goes out of range you get a compiler error.
 
Vaibhav Chauhan
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for reply, chetan

you mean that if i add variables (which are not final) then the addition is performed at runtime otherwise at compile time.
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
15.28 Constant Expression
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic