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.
3 odpowiedzi
+ 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).
+ 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.
+ 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.