Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Mock Exam Problem  RSS feed

 
Mukti Bajaj
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
The following code gives the out put as 1 0 1...But, I am unable to understand how it works.Can someone please explain.
public class TestAnswer {
int a;
int b;
public void f()
{
a=0;
b=0;
int[] c ={0};
g(b,c);
System.out.println(a + " "+ b + " "+ + c[0]);
}
public void g(int b,int c[])
{
a=1;
b=1;
c[0] =1;
}
public static void main(String args[])
{
TestAnswer tA = new TestAnswer();
tA.f();
}
}
Thanks in advance.
Mukti

 
Sridevi Shrikanth
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mukti Bajaj:
Hello,
The following code gives the out put as 1 0 1...But, I am unable to understand how it works.Can someone please explain.
public class TestAnswer {
int a;
int b;
public void f()
{
a=0;
b=0;
int[] c ={0};
g(b,c);
System.out.println(a + " "+ b + " "+ + c[0]);
}
public void g(int b,int c[])
{
a=1;
b=1;
c[0] =1;
}
public static void main(String args[])
{
TestAnswer tA = new TestAnswer();
tA.f();
}
}
Thanks in advance.
Mukti

The value of 'a' is accesible to method g since they are in the same class. hence 'a' gives out '1'.
According to the scope rules, the local variables are scanned first. Hece the value of 'b' is the local copy obtained from the argument, which in turn is a copy of the variable 'b' and not the actual value. hence the change to b is not reflected.
For the argument c[], a copy of the 'reference to the array' c is passed. Hence the actual array values gets modified. And so the change in c[0] is shown.
I hope this helps.

 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!