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
• Liutauras Vilda
• Tim Cooke
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Devaka Cooray
• Ron McLeod
• paul wheaton
Saloon Keepers:
• Tim Moores
• Piet Souris
• Tim Holloway
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Frits Walraven
• Scott Selikoff

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

Ranch Hand
Posts: 65
• Number of slices to send:
Optional 'thank-you' note:
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
• Number of slices to send:
Optional 'thank-you' note:
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
• Number of slices to send:
Optional 'thank-you' note:

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.

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]++;
}