• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Question Mock  RSS feed

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!