Deli Irium
Deli Irium

Reputation: 45

Returning values in Java

I'm having some trouble understanding pretty basic Java code, I can't figure out how in the end of compiling x=2. Because through my logic it should be 4. The code itself:

public class eksami_harjutused {

public static int x=2;
   public static int y=2;  

   public static void main(String[] args) {     
     foo(bar(foo(x)));      
     System.out.println("main x,y: "+x+" "+y);
   }  

   public static int foo(int x) {     
     x++;
     y++;   
     System.out.println("foo x,y: "+x+" "+y);
     return x;
   }

   public static int bar(int x) {
     int z=0, y=10, u=0;    
     --y;
     for(y=1; y<(x*x); y++) {
       for(z=1; z<x; z++) { 
         u++;
       }
     }
     System.out.println("bar x,y: "+x+" "+y);
     return z;       
   }           
}

It prints out:

foo x,y: 3 3

bar x,y: 3 9

foo x,y: 4 4

main x,y: 2 4

Upvotes: 1

Views: 158

Answers (2)

fatma.ekici
fatma.ekici

Reputation: 2827

Because int is passed by value, you would not expect x to be incremented in foo(). You can try org.apache.commons.lang.mutable.MutableInt since Integer class is also immutable.

Upvotes: 0

nhahtdh
nhahtdh

Reputation: 56809

Well, x is passed by value - since it is int type, so any modification to x in the callee functions will not affect x in the caller function. You can think of giving a copy of value in x to the callee, and the callee can do whatever with it without affecting the x in the scope of the caller.

Passing by value is done for all the primitive types in Java. And passing by reference is done for the rest (Object - note that array is Object).

Another thing is the effect of variable shadowing in foo and bar methods: x is declared as parameter to foo and bar, so the class member x is shadowed. Any access to x in foo and bar methods will refer to the argument passed in, not the class member x.

The value of x printed in the main method is from the class member x, which is never touched during the execution of the program.

In contrast, you can see the variable y modified twice in 2 calls to the foo method, since y in foo method will refer to the class member y. The y in bar method, however, refer to the local variable y declared in the bar method.

Upvotes: 5

Related Questions