Reputation: 151
I came across this coding... and just want confirmation about what I understood how the output 121 is received.
System.out.print(i++ + obj1.operation(i));
In the above code, i
is zero, but i
becomes one when it is passed as parameter to the operation method. In method operation the system.out.print prints out one and returns the post increment value 2 to above system.out.print
.
In the above code, the initial value of i and return value of method is added i.e. 0+2=2
, and it prints out 2. And the local variable i in the main method has increased to one in the above code so the next print statement prints 1. Is this the right explanation?
public class CalculatorJava {
public static void main(String[] args) {
int i = 0;
CalculatorJava obj1 = new CalculatorJava();
System.out.print(i++ + obj1.operation(i));
System.out.println(i);
}
public int operation(int i) {
System.out.print(i++);
return i;
}
}
Upvotes: 2
Views: 95
Reputation: 127
public class CalculatorJava {
public static void main(String[] args) {
int i = 0;
CalculatorJava obj1 = new CalculatorJava();
System.out.print(i++ + obj1.operation(i));
//In the above statement, the variable i has a value 0,
//then it is incremented by 1 and becomes 1,
//when passed as an argument in the operation() method.
//So, it is: print(0 + operation(1))
//operation(1) returns 2
//Therefore, the above statement **prints 2**
//i++ will basically use the initial value of i and
//then increment its value by 1
System.out.println(i);
//Since i=1, the above statement **prints 1**
}
public int operation(int i) {
//i=1
System.out.print(i++);
//The above statement **prints 1** and then increments the value of i by 1
//So, it is: print(1), i=1+1=2
//2 is returned
return i;
}
}
Hence, the overall output is: 121
Upvotes: 1
Reputation: 101
Not only the main method but also the operation method is using a local variable in this case. So we can consider them as two different variables. Let's call "i" in main as "mi" and "i" in operation as "oi". A simplified algorithm of the code above would be as follows:
1: assign 0 to mi
2: increase mi by one
4: assign the value of mi to oi
5: increase oi by one
6: print mi and oi
7: print mi
I assume you know that the plus sign inside the print method is not algebraic.
As you can see in the example code below, if we change the scope of i, that would let both methods use the same variable. And the output would be 122
instead of 121
public class CalculatorJava {
static int i = 0;
public static void main(String[] args) {
CalculatorJava obj1 = new CalculatorJava();
System.out.print(i++ + obj1.operation());
System.out.println(i);
}
public int operation() {
System.out.print(i++);
return i;
}
}
For further reading: Local Variables and Scope
Upvotes: 0