0
public class midterm2 {
    static void methodOne(int[] a) {
        int[] b = new int[5];
        a=b;
        System.out.print(a.length);
        System.out.print(b.length);
    }
    public static void main(String[] args) {
        int[] a = new int[10];
        methodOne(a);
        System.out.print(a.length);

    }
}

The answer is 5510, and I don't understand why because I thought it would be 555. I thought the original array will be changed in this case.

Can anyone help me to understand this??

Thank you!

6 Answers 6

1

In main() method, a[] refers to int[10] array. When you passing int[10] array to methodOne(), new a[] variable creates for refer int[10] array and that variable is a[]. Now you have 2 a[] variables which refers int[10] array.

Now you create b[] and it refers int[5] array. You assign b[]'s array to a[] (which belongs to methodOne()). but a[] in main method still refers int[10] array.

Sign up to request clarification or add additional context in comments.

Comments

1

Since a is a array of primitive type it is a pass by value to the methodOne() and hence the variable a in the scope of the main method remains unaltered.

Comments

1

change methodOne parameter name to "int[] c" will make you understand easily. Parameter "a" in methodOne is totally different with variable "a" in main method.

Comments

1

a=b; statement assigns reference of "b" to "a".

If you code like a = new int[10]; it would print 5510 as output. So unless you use "new" it will act as call by value and changes made in the called method will not reflect in calling method.

Comments

1

The short answer is: The reference variable 'a' is local to functions 'main' and 'methodOne'.

Comments

1

In your: methodOne() 'a' is local to that method. so when you do a = b,

it doesnt do any change to varible 'a' in your main().

Then again you are going to print variable 'a' in main(): So it refers to local variable a an print it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.