Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reinitialize the int array in java

Tags:

java

arrays

c#

int

class PassingRefByVal 
{
    static void Change(int[] pArray)
    {
        pArray[0] = 888;  // This change affects the original element.
        pArray = new int[5] {-3, -1, -2, -3, -4};   // This change is local.
        System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
    }

    static void Main() 
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]);

        Change(arr);
        System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]);
    }
}

I have to convert this c# program into java language. But this line confuse me

pArray = new int[5] {-3, -1, -2, -3, -4}; // This change is local.

How can i reinitialize the java int array? Thanks for help.

like image 792
Shashi Avatar asked Dec 17 '25 23:12

Shashi


2 Answers

pArray = new int[] {-3, -1, -2, -3, -4};

i.e., no need to specify the initial size - the compiler can count the items inside the curly brackets.

Also, have in mind that as java passed by value, your array won't 'change'. You have to return the new array.

like image 179
Bozho Avatar answered Dec 20 '25 12:12

Bozho


You can't "reinitialize" the array from within the other method because Java is pass by value. You can solve this in C# by using the ref keyword, but this is not available in Java. You will only be able to change the elements in the existing array from the calling method.

If you only want the array to be changed locally then Bozho's solution will work.

like image 42
Taylor Leese Avatar answered Dec 20 '25 13:12

Taylor Leese