• Post Reply Bookmark Topic Watch Topic
  • New Topic

anyone who can tell me?  RSS feed

 
Jin chengong
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here is the code:
public class Inc {
public static void main(String[] args) {
Inc inc = new Inc();
int i = 0;
inc.fermin(i);
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}

the answer is 0 not 1.why ?
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i++ is a postfix operator so first a value is assigned and then the value will be increased by one.
If you use a prefix operator the result will be as you will expect.



For more information over postfix operators see the following link


Operators and Assignments - Prefix and Postfix Operators
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
inc.fermin(i);

This call works on a local variable that is initialized with the value of i, 0. When in that method i++ is called, it increments that local variable, not the variable passed to the method.

i = i++;

Here's the real "magic". What happens here is something like the following:

Were you to write i++ it would have been 1. Had you written "i = ++i" it would have worked as well:

For more information, search for the difference between prefix and postfix increment.
 
Jin chengong
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
think you very much!
 
Jin chengong
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.
Remko Strating
Rob Prime
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!