Originally posted by preeti dengri:
Ques 1.given the foll code which statements can be inserted at position 1 without causing the code to fail compilation?
public class q 67
{
int a;
int b=0;
static int c;
public void m()
{
int d;
int e=0;
//position 1
}
}
options are
1) a++
2) b++
3)c++
4)d++
5)e++
Ques 2.which statements can be inserted at the indicated position to make program write 1 on std output when run?
public class Q45
{
int a=1;
int b=1;
int c=1;
class inner {
int a=2;
int get()
{
int c=3;
//insert statement here
return c;
}
}
Q45()
{
inner i=new inner();
System.out.println(i.get());
}
public static void main(String args[])
{
new Q45();
}
}
options:
a)c=b;
b)c=this.a;
c)c=this.b;
d)c=Q45.this.a;
e)c=c;
please explain
Hello,
First Question:statements a++,b++,c++ and e++ can be inserted at position1 without causing the code to fail compilation.In
java instance or member variables of a class are automatically initialised eventhough the programmer provides no explicit value.
If the member variable is an int then it is initialised to 0
a++: a is a member variable of the class q67 and is initialised to 0.
c++:c is a static member variable of the class q67 and is initialised to 0.
d and e are local variables.A local variable has to be initial explicitly by the programmer before it's use.here e is initialised to 0 //int e=0;
but d is not initialised to or assigned a value before it is used in the statment d++.hence the compiler complains for the statement d++.
Second question:
The outer class Q45 has member variables a,b,c each initialised to 1.
The inner class has member variable a initialised to 2.It's method get() has a local variable c initialised with the value 3.
1)c=b; Since the inner class has no member variable named 'b' or it's method get() does not have a local variable 'b',this statement assigns the value of the member variable 'b' of class Q45 i.e 1 to c .Hence this assignment will write 1 to std output.
2)c=this.a; This statement assigns the value of member variable 'a' of inner class to c i.e 2.This will write 2 to std output.
3)c=this.b; This statement will generate an error as the inner class has no member variable 'b'.
4)c=Q45.this.a; Q45.this.a refers to the member variable 'a' of class Q45 .This statement assigns the value of 'a' of Q45 i.e 1 to c.This will write 1 to std output.
5)c=c;This statement assigns the value of local variable 'c' of get() method in the inner class to c i.e 3.The output in this case would be 3.
[This message has been edited by sai challa (edited March 30, 2001).]