Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Array

sandhi mridul
Ranch Hand
Posts: 71
I am weak in array. Please do help me with this question

the output is 2.
I am not getting how?

thanks
sandhya

Deepak Chopra
Ranch Hand
Posts: 433
Sandhi,

you need to understand two logic here..!!

when you wrote this:

int[] a = {1};

What is the meaning of this:
this means:
a ---> refers to an int array on heap ---> size of array is 1 ---> a[0] refers to 1

when you call method by passing a that means you are passing the reference to that array Object, if you pass a[0] you are passing the value 1.

Inside Method:

Now i is also referring to one array object.
i ---> refers to an int array on heap ---> size of array is 1 ---> i[0] refers to 1

In fact both a and i refers to same object.

you increment the i[0] by 1, so now..
i ---> refers to an int array on heap ---> size of array is 1 ---> i[0] refers to 2

Or we can say that:
a ---> refers to an int array on heap ---> size of array is 1 ---> a[0] refers to 2

As both were referring to same object.

sandhi mridul
Ranch Hand
Posts: 71
Thanks sunny. i got it now.

sitaram
Greenhorn
Posts: 26
public static void main(String[] args){
int[] a = {1};
Test5 t = new Test5();
t.increment(a);
System.out.println(a[a.length - 1]); // o/p is 2
}
void increment(int[] i){
System.out.println(i[i.length - 1]++); // o/p is 1
}

sridhar row
Ranch Hand
Posts: 162
I think because of the post increment operator it first prints 1 and then increments by 1. since both a and i are referring to the same object, a[0] will be 2 and hence prints 2 the second time.

Gitesh Ramchandani
Ranch Hand
Posts: 274
In simple words,

increments the value of the element in the array, by 1.

Gitesh