Reputation: 418
I can't figure out why line 3 prints 1 in this Test class that I wrote. I thought it would print 2 instead of 1 because I was thinking line 2 has changed the value of x to 2.
Can anyone explain this to me please? Is this to do with java being pass by value or is it some other explanation?
public class Test{
public static void main(String[] args) {
int x = 1; // line 1
System.out.println(x+1); //line 2 prints 2
System.out.println(x); //line 3 but why does this line prints 1?
}
}
output:
2
1
Upvotes: 0
Views: 49
Reputation: 38910
It is expected.
You are just printing x+1. x+1 does not modify the value of x unless you explicitly assign the new value to x.
if you change the code as below, you will get desired output.
x= x+1;
System.out.println(x);
Upvotes: 0
Reputation: 1181
For Line 2 the output is 2 because x is already 1 and you're adding an other one that makes it 2 but not changing the value of x. So that is the reason for 1 on line 3 aswell.
Try with x++ on line 2 and see the result on line three.
Upvotes: 2
Reputation: 140299
The explanation is simply that x + 1
doesn't change the value of x
, but instead returns a completely separate int
whose value is one greater than x
.
Upvotes: 3