• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

javaprepare.com question

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi friends,
here are some questions from www.javaprepare.com :
1. public class example {
int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
change_i(i);
System.out.println(i[0]);
}
public static void change_i(int i[]) {
int j[] = {2};
i = j;
}
}
What will be the output:
a. The program does not compile.
b. The program prints 0.
c. The program prints 1.
d. The program prints 2.
e. The program prints 4.
correct answer is : C
I've compiled and executed this code and answer is right, but since we are passing array object to the method, it means that reference is passed, and thus any change in the referred object will be visible in the calling method.
please correct me.
Thnks..
 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Of course reference itself is passed. But if you change content of reference then same will be reflected in calling program. for e.g. i have changed your code ,

===============================
public class Test {
int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
change_i(i);
System.out.println(i[0]);
}
public static void change_i(int i[]) {
int j[] = {2};
i[0]+=3;
i = j;
}
}
======================================
This will print 4.
if you make change to reference itself will not be reflected because you are not returning the refrence back. If you are not returning the refrence then in calling program refrence is not reflected.
Regards
R V Holla.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes,
As Holla told, if the object is been returned then you can expect the actual change which you have passed as an argument.
Here is the changed code
public class example {
int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
i=change_i(i);
System.out.println(i[0]);
}
public static int[] change_i(int i[]) {
int j[] = {2};
i = j;
return i;
}
}
reply
    Bookmark Topic Watch Topic
  • New Topic