0

Why does the following code print out 6 and not 20?

public class ClassA {
    public static void main (String [] args ) {
        int k = 5;
        doub ( k );
        doub ( k );
        if ( k <= 19) {
            k ++;
        }
        System. out . println ( k );
    }
    public static void doub (int x ) {
        x *= 2;
    }
}

Thanks in advance.

Henieheb
  • 13
  • 2
  • 1
    Why do you expect 20? – Eran Dec 10 '19 at 10:53
  • This might be a better one: [function won't change value of variable in java?](https://stackoverflow.com/questions/32293640/function-wont-change-value-of-variable-in-java) – Ivar Dec 10 '19 at 10:56
  • I recommend in closing this issue as it is clearly related to *Is Java "pass-by-reference" or "pass-by-value"* – D. Lawrence Dec 10 '19 at 11:01

2 Answers2

1

Because the object inside the methods is a different object to the original K, you need to get double() to return the result and set K to that result

Public static int doub(int x) { return x* 2}

K = doub(k)

Brandon
  • 1,158
  • 3
  • 12
  • 22
  • There's a primitive inside the methods, not an `Object`... If it were a mutable object this would actually work (`AtomicInteger`, for example...). – BeUndead Dec 10 '19 at 11:33
0

Try

public class ClassA {
    public static void main (String [] args ) {
        int k = 5;
        k = doub ( k );
        k = doub ( k );
        if ( k <= 19) {
            k ++;
        }
        System. out . println ( k );
    }

    public static int doub (int x ) {
       return x *= 2;
    }
}