Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock Exam Problem

 
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic