+ 1

Java Reference and Scope

public class Swap { public static void main(String[] args) { int a = 10; int b = 20; swap(a, b); System.out.println(a + " " + b); int[] arr = {1, 3, 2, 45, 6}; change(arr); System.out.println(Arrays.toString(arr)); } static void swap(int num1, int num2) { int temp = num1; num1 = num2; num2 = temp; } static void change(int[] nums) { nums[0] = 99; } } // Why changes by change() function is done but if I do changes with swap() not happing Current Output 10,20 [99,3,2,45,6] My Expected Output 20,10 [99,3,2,45,6]

9th Nov 2022, 6:29 AM
ㅤㅤㅤㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤ - avatar
2 Answers
+ 1
These methods return void. change() modify values of an array, in java when you take an array in parameters of a method you get the array reference => array will be change globally. Swap() modify value of int, in java when you take an int (primitive data type) in parameters of a method you get the int value => int will be change only in the methode scope if you don't return something. In your case, you can take an array of two numbers to your swap method or pass the values num 1 and num2 as attributes of the class swap
9th Nov 2022, 7:07 AM
Roland
Roland - avatar
+ 1
Got it thanks
9th Nov 2022, 9:09 AM
ㅤㅤㅤㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤ - avatar