• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question Mock

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.


 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic