Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

diffrence between a++ and a=a+1

 
mridul makkar
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is there any diffrence between
a=a+1 and a++. i just need to know how a++ works.Just now i gone through a code
byte a=10;
a++;
a=a+1
second line wont give error whereas third line gives whats the reason.
 
Kristof Janssens
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are some rules:

For unary operators, there are 2 rules:

* if the operand is a byte, a short or a char, it is converted to an int (unless the operator is ++ or --, in which case no conversion happens)
* else there is no conversion

For binary operators, there are 4 rules:

* if one of the operands is a double, the other operands are converted to a double
* if one of the operands is a float, the other operands are converted to a float
* if one of the operands is a long, the other operands are converted to a long
* else both operands are converted to ints

so, with the unary operator ++ or --, there is no conversion. For the + operator, it is always converted to ints (unless one of the operands is a double, float, long)

so, if you want to make your code work, you need to cast the + operation to byte

a = (byte) a+1;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic