Click here to Skip to main content
15,905,913 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
import java.util.*;
class Main {
    public static Scanner scanner=new Scanner(System.in);
    public static int[] arr;
    public static void main(String[] args) {
        InsertElements(arr);
        PrintUnsortedArray(arr);
    }
    public static void InsertElements(int[] barr){
        System.out.println("Enter the size of array:");
        int size=scanner.nextInt();
        barr=new int[size];
        System.out.println("Enter the array elements:");
        for(int i=0;i<barr.length;i++){
            barr[i]=scanner.nextInt();
        }
    }
    public static void PrintUnsortedArray(int[] arr){
        System.out.println("The unsorted array is:"+Arrays.toString(arr));
    }
}

/*My output is:
Enter the size of array:
5
Enter the array elements:
5 4 3 2 1
The unsorted array is:null*/


What I have tried:

//I know this is right
import java.util.*;
class Main {
    public static Scanner scanner=new Scanner(System.in);
    public static int[] arr;

    public static void main(String[] args) {
        System.out.println("Enter the size of array:");
        int size=scanner.nextInt();
        arr=new int[size];
        InsertElements(arr);
        PrintUnsortedArray(arr);
    }

    public static void InsertElements(int[] barr){
        System.out.println("Enter the array elements:");
        for(int i=0;i<barr.length;i++){
            barr[i]=scanner.nextInt();
        }
    }

    public static void PrintUnsortedArray(int[] arr){
        System.out.println("The unsorted array is:"+Arrays.toString(arr));
    }
}
Posted
Updated 26-Dec-21 8:48am

1 solution

Java uses pass by value for parameters - which means when you call InsertElements with arr as the parameter:
Java
public static void main(String[] args) {
    InsertElements(arr);
    PrintUnsortedArray(arr);
}
the value in the variable is copied - null - and passed to the function.
The function then overwrites that value with the new array, fills it and returns - which doesn't affect the external variable at all.

If you think about it, that's the only sensible way to do it. What would happen if it didn't work like that, but the variable was passed instead?
Java
void Foo(int x) {
   x = x + 10;
}
...
int val = 56;
Foo(val);
System.out.println(val);
Would work fine - 66 would be printed.
But ... if we do this:
Java
void Foo(int x) {
   x = x + 10;
}
...
Foo(56);
System.out.println(56);
What happens? Does the value of a constant get changed? Logically, yes, it would - and that would make coding very, very difficult!

So just remember: Java always copies the content of a variable and passes that to a function, not the variable itself.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900