wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array" Watch "Array" New topic
Author

Array

sandhi mridul
Ranch Hand

Joined: Jan 25, 2008
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
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
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.


Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
sandhi mridul
Ranch Hand

Joined: Jan 25, 2008
Posts: 71
Thanks sunny. i got it now.
sitaram
Greenhorn

Joined: Jan 24, 2008
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

Joined: Jan 16, 2008
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

Joined: Feb 28, 2007
Posts: 274
In simple words,

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

Gitesh
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array
 
Similar Threads
I need Help
cannot find symbol
assignment of final member variables
SOS: i have some questions about Thread
++ Operator.......