wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question Mock 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 "Question Mock" Watch "Question Mock" New topic
Author

Question Mock

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi!
What will be the result of attempting to compile and run the following class?
public class TestClass
{
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 ]++ ; }
}
I think that iArr[0] = 1 but the code will print i = 1 iArr[0] = 2. Why?
Thank you in advance.
Roopa Bagur
Ranch Hand

Joined: Nov 03, 2000
Posts: 267
It is because a copy of the value of primitive datatypes are passed to a method but array is an object & its reference value is passed.Therefore whenever a change is made to a primitive type variable in a method it is not reflected in the main variable but it is the opposite in object datatypes.
I hope I explained well.. else somebody please explain in detail.

Originally posted by Jordi Marqu�s:
Hi!
What will be the result of attempting to compile and run the following class?
public class TestClass
{
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 ]++ ; }
}
I think that iArr[0] = 1 but the code will print i = 1 iArr[0] = 2. Why?
Thank you in advance.

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Question Mock
 
Similar Threads
Incrementor operator
pass by value
a confused concept
JQ+ Arrays[0]++
can anyone explain this?