• 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

Output of this...........?How you got that?

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Base{
public static void main(final String[] args){
int[] a = {1};
Base t = new Base();
t.increment(a);
System.out.println(a[a.length - 1]);
}
void increment(int[] i){
i[i.length - 1]++;
}


}
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You will get the output as 2.
The value of a[0] is 1.After calling increment method the value become 2 by post increment operator.
So the output is 2.

In the line below
-----------------
i[i.length - 1]++;
-----------------
the value of i.length is 1 so 1-1=0;i[0]=1;
after that i[0]++;so i[0]=1+1=2;


So the value of a[0]=2

Regards,
Premavenkat.
 
Ranch Hand
Posts: 44
1
Oracle Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answer is 2.

An array of any type is an object, and therefore the rules of using objects as parameters (and the manipulation there on) apply and not the rules that apply to primative data types.

If you had just a standard int value that is passed into the incement() method then the printed answer would have been 1.

Example with overloading method to demonstrate the diffence.
class Base{
public static void main(final String[] args){
int[] a = {1};
int b = 1;
Base t = new Base();
t.increment(a);
System.out.println(a[a.length - 1]); // displays 2
t.increment(b);
System.out.println(b); // displays 1
}
// method to work with an int array object
void increment(int[] i){
i[i.length - 1]++;
}

// overloading method to work with a primative data type
void increment(int i){
i++;
}
}
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic