0

Variables only work within a method?

The following code is given in Java _______________________ public class Question2 { public static void main(String[] args) { int a = 5; int b = 7; swap(a,b); System.out.println(a + ", " + b); } public static void swap(int a, int b) { int temp = a; a = b; b = temp; } } _________________ I was expecting the output to be 7.5. Inside the "swap" method it works and the output would be 7.5. But as soon as the method is processed and the two variables are output in the main class, the result is again, 5.7. As if the variables had never been swapped.

28th May 2022, 7:45 PM
Dodo
3 Answers
+ 3
When you call swap(), the variables "a" and "b" within the swap function are local to it and separate from the variables "a" and "b" within the main function. To fix this, make variables outside of the main function but within the class declaration that the swap function changes (and no parameters should be necessary for that).
28th May 2022, 8:48 PM
Daniel C
Daniel C - avatar
+ 2
If you want to change the value of global variables inside a function, use must give passe it reference. Actually you just passed it by value.
28th May 2022, 8:40 PM
Christian Fare T.
Christian Fare T. - avatar
+ 1
Yes. In your case swap uses local variables a and b. So swapping them works in your method but has no effect to your variables in your main method. In general: Primitives like int, double and so on: method gets values Objects: method get reference. If you would use an array (which is an object) and swap its values in your method then it would change the array in your main method.
28th May 2022, 8:40 PM
Denise RoƟberg
Denise RoƟberg - avatar