0

enter image description here

I this code, the out put is 6, But i think that it should be 4

Why output is 6?

slhck
  • 36,575
  • 28
  • 148
  • 201
Sajad
  • 2,273
  • 11
  • 49
  • 92

6 Answers6

1

No. Your assumption is wrong.

You are are passing array to a method an modifiying there so the array pointing to the same reference and value has been changed.

Where as in case of a which is a primitive does'nt have a reference and a copied value passed to the method and original value remains same.

System.out.println(a+array[0]);
// a is still 1 and array madofied in method which is 5. so 1+5

In short:

  • When you pass primitives to the methods, changes wont effect on original variable.

  • When you pass object(here array) to the methods, changes effects
    to original object since they pointing to the same reference.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

This is where using your debugger would answer this question but in short you have

int a = 1;
// inside f()
// a = 4 doesn't change the value of a in main()
array[0] = 5;

So a + array[0] is 1 + 5 or 6

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

That happens because the int array is not a native type in Java, but an Object.

So, when you call the method f(), the method receives a copy of the variable a, and a copy of a pointer to the int array. When you change a value inside the array, you are modifying the object to which the pointer it received refers to. But when you change the value of a, you're just modifying the copy of a.

andreban
  • 4,621
  • 1
  • 20
  • 49
0

a will be passed as a copy of value while array will be passed as a copy of reference. So when you modify what you can access with that reference you modify the actual array. While for a you are just modifying value of the copy which will not modify your original a.

AbhinavRanjan
  • 1,638
  • 17
  • 21
0

In this case, the a within f() is a local copy of the value passed via the method call. Doing something within f() to a will not change the a in main(). On the other hand, when you pass array in to f(), you are passing a reference to the array object called array. Thus, both array names point to the same underlying object, and changing that object will change what each array reference points to.

seanoftime
  • 186
  • 3
0

Arrays in Java are also objects they are passed by value and not passed by reference.

Just like any other class object, when an array is passed to another method that method can still change the contents of the array itself. But, what is being passed to the method is a copy of the reference address that points to the array object.

Just take a look at your example above – the same exact principles apply to arrays since they are objects in Java, and are passed by value.

Sudz
  • 4,268
  • 2
  • 17
  • 26