• Post Reply Bookmark Topic Watch Topic
  • New Topic

Basic Arithmetic Operator's Behavior  RSS feed

 
dinesh Venkatesan
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

The Java Language Spec says that, the arithmetic operators +(Binary additive) and ++(increment) both return a integer value.
So, while using a code like this,

byte a=5;
byte b = a+1;
The compiler throws an error which is perfectly valid. But the same should happen when we use
b = ++a;
But the compiler does not throw any error.
Can anybody explain about this?
Thanks in advance!

Dinesh.V
 
Petrus Pelser
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ++ operator and the compound assignment operators (such as +=) contain an implicit cast to the type of the operand they are used on.
 
Abdul Rehman
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a different view on this. Binary and/or unary numeric promotion does not occur when you use ++ or -- operators. It only occurs on a few specific kind of operators, which are clearly enumerated in the JSL. So, when you write something like "++a", its type is not promoted at all. Thus if "a" was of type byte or short, it will remain the same.

The first example which you mentioned was:

Firstly, bear in mind that the Java compiler performs an implicit narrowing conversion during an assignment, if -
(i) the type of the expression is int
(ii) the expression is a compile-time constant expression
(iii) the datatype of the variable (to be assigned a value) is byte, short or char
(iv) the value to be assigned, is within the range of the datatype of the variable, to which the value will be assigned

Keeping these rules in mind, you can understand why the above example is giving an error. The reason is that the expression "a+1" is not a compile-time constant expression.

If we re-write the above example as below, it will compile smoothly.


See this similar thread: Byte and Char.

Regards,
Abdul Rehman.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!