-2
public class lalak
{
    public static void m1(int[] array)
    {
         array= new int[]{1,2,3,4,5};
        System.out.println(array[2]);
    
    
    }
    
    public static void main(String[] args)
    {
        int[] array = {1,1,1,1,1};
        m1(array);
        System.out.println(array[2]);
        
        
        
    }


}

why answer is 1, not 3?

i expected the program to print 3 but i got 1 as output. i thought method would change my original array but it turned out to be false. does anyone know the reason for this?

  • You're not modifying the original array - you're modifying the *new* array that you've created within `m1`. You've changed the value of the parameter to refer to a different array, but that doesn't change the value of the *argument* (the `array` variable in `main`). (This is the same as with any other reference type...) – Jon Skeet Dec 08 '22 at 19:36
  • If you replace the first line of `m1` with just `array[2] = 3;` then you'll see your expected output. – Jon Skeet Dec 08 '22 at 19:36
  • (https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html)Here is a javadoc for pass by value for primitive types and pass by reference for objects. So if you want to see value 3 instead of 1 you can change the array to ArrayList. – Java Samurai Dec 08 '22 at 19:43

1 Answers1

-1

You're creating a new array which makes the reference to your array in main redundant. You could either, replace the first line like Jon Skeet said

Or another option would be, to have m1 return an array and assign it to your array in main

public class lalak
{
    public static int[] m1(int[] array)
    {
        array= new int[]{1,2,3,4,5};
         System.out.println(array[2]);
    }

public static void main(String[] args)
    {
        int[] array = {1,1,1,1,1};
        array = m1(array);
        System.out.println(array[2]);  
    }
}
LuxSt
  • 1
  • 1