0

I have the following code

private static void modifyX(int x) {
 if (x!=0) {
  modifyX(--x);
 }
}

I want the value of my variable to be updated after the recursive call, so I wrote the following code:

public static void main(String... args) {
  int x = 5;
  modifyX(x);
  System.out.println("Modified value:\t" + x);
}

However, the value remains the same (5).

Why is my variable not updating?

Auro
  • 1,578
  • 3
  • 31
  • 62
  • You are not passing a reference. – Sterling Archer Apr 03 '18 at 22:18
  • 2
    The function isn't called with a variable, but rather with the value of the variable. In your main method there's a variable X whose value is 5. Then you call another method with five. That method cannot change the value to which the variable X is bound. – Joshua Taylor Apr 03 '18 at 22:19

1 Answers1

0

You are not passing the same instance of the value 5. Instead, the JVM is creating a new int with a value of 5, and passing that to your method.

See this thread for more information.

Sam
  • 2,350
  • 1
  • 11
  • 22
  • 1
    This answer isn't *wrong*, but it's misleading terminology to refer to primitive types as having instances. In the language of the Java specification, only types that are subtypes of `java.lang.Object` can have instances. Primitive types simply have *values*. – Daniel Pryden Apr 03 '18 at 22:22
  • I know, but I couldn't think of a better way to explain it – Sam Apr 03 '18 at 22:44
  • Even with this kind of metaphor, if you want to think of the number as something that has an instance, it actually could be the same instance getting passed around, and you could think of the decrement operator as being shorthand for x = x - 1, and the value of x-1 is a different number instance than the previous instance that was the value of x. – Joshua Taylor Apr 03 '18 at 22:48