Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

post increment operator  RSS feed

 
Sukhadev Patil
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test
{
public static void main(String[] args)
{
int i=0;
i=i++;
System.out.println("Hello World!"+i);
}
}
When we run the above program it prints

Hello World!0

i think it should print

Hello World!1

why is it so

thanks
 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the Javaranch FAQ.

Henry
 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I dont really know why its not working either, but you could use i+=1;
 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi sukhadev

In post increment ++ Operator works like this
i++ is equivalent to :
result = i
i+=1
return result

So what happens is :
int i = 0
i = i++ // On right hand side i is incremented and the original value of i which is in result(0) is returned back to LHS i (which resets i to 0).

Hope this helps you

Cheers
[ April 13, 2006: Message edited by: faisal usmani ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also see this thread.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!