Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • 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
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

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

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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++;
}
}
 
What's a year in metric? Do you know this metric stuff tiny ad?
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic