wood burning stoves 2.0*
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array..." Watch "Array..." New topic
Author

Array...

Sunitkumar Survase
Greenhorn

Joined: Feb 23, 2001
Posts: 5
Hi...
This is Sunit .... for the first time.
I got this question from one mock test....Iam confused.
Anyone plzz explain this to me.
Thanxx lot.
S U N I T
//code starts..
public class Testarr
{
public static void main(String args[ ] )
{
int i = 1;
int[] iArr = {1};
incr(i) ;
incr(iArr) ;
System.out.println( "i = " + i + " iArr[0] = " + iArr [ 0 ] ) ;
}
public static void incr(int n ) { n++ ; }
public static void incr(int[ ] n ) { n [ 0 ]++ ; }
}

// The o/p is :
// i =1 and iArr[0]=2
WHY???
huiying li
Ranch Hand

Joined: Feb 12, 2001
Posts: 68
The important thing to remember is "Java pass by VALUE".
The first call incr(i), 1 is passed to parameter n in incr() method, n is local to the method, so even though n is increased to 2 in the method, it has no affect on i in the main() method, i is still 1, unchanged.
The second call incr(iArr), the array object reference iArr is passed by value to the method, now the method parameter n and the reference iArr both are referencing/pointing to the same array object. In the incr() method, the first array element is increased to 2, this change happended in the object. So after the method returned n is out of scope, but iArr is still referencing the array object whose first element is now 2.

[This message has been edited by huiying li (edited February 28, 2001).]


SCJP
Sunitkumar Survase
Greenhorn

Joined: Feb 23, 2001
Posts: 5
Thanxx a lot.I got it.
Cheers..
Sunit.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array...