This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Little Book of Impediments (e-book only) and have Tom Perry on-line!
See this thread for details.
Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Bug in Java Compiler

 
rksrathour
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
See the code
try find out the Out put
it gives 5 instead of 7
Can any body give the explanation
Then pls reply to
rksrathour@rediffmail.com
class test
{
public static void main(String[] args){
int i=5;
i=i++;
i=i++;
System.out.println(i);
}}
 
Francisco A Guimaraes
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it�s not a bug, when you write "i=i++", the value of i is passed to itself, than incremented. if you want the output to be 7, you should write "i=++i" or just "i++".
Francisco
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
rksrathour,
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner!
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Francisco pointed out, this is not a bug in your Java compiler. It's my understanding that, with such an expression, some C/C++ compilers would behave similarly to Java and some would behave as you were expecting your Java compiler to behave.
A nice feature of the forums here at JavaRanch is the ability to search past conversations for lots of very useful information. If you're after more depth on this subject, I'd recommend a search on the Programmer Certification Study forum.
The important consideration with your example is the order of operations and that the assignment operation is the last operation performed. Looking at the right side of the expression, i++ returns the initial value of i and then it does increment i by 1. This return value (the initial value of i) is then assigned to the identifier i - and thus i is effectively unchanged. The expression i = ++i ; would behave as you were expecting i = i++ ; to behave.
Good Luck.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic