Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on static block and static variable

 
Srinivasan Mani
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain the answer for this question.
What is the output of the following program?
class Stat1{
static int i=100;
static {
System.out.println("Static Block");
int k=100;
int i=50; //1
System.out.println(i);
}
};
class StatTest1{
public static void main(String[] args) {
System.out.println("Hello World,"+Stat1.i);
Stat1 a= new Stat1();
System.out.println(Stat1.i);
}
}
A.Compilation Error stating variable i is already defined
B.Runtime Error
C.Output of Hello World,Static Block 50 100 100
D.Output of Hello World,Static Block 50 50 50
E.Output of Hello World,100 Static Block 50 100
F.None of the above

Thanks in advance
Srini
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried compiling and running it? What exactly do you not understand after doing so?
 
Srinivasan Mani
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not A..
Member variable i and the i inside static block is not in same scope?
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No they're not in the same scope, static and instance initializer scops are like the methods scopes, you can define instances with the same name as the member variables.
Do you understand how is F the right answer??
I should always quote the message while answering, I miss with the names and the letter answers..
[ November 25, 2002: Message edited by: Alfred Kemety ]
 
Srinivasan Mani
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's compiling and giving the output of StaticBlock 50 HelloWorld,100 100.So Answer is F.
But my doubt is why not A?
Does this mean static variable i and variable i in static block will not be in same scope?
 
Srinivasan Mani
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is clear.so static is like method block.
Thanks Alfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic