| Author |
Question on static block and static variable
|
Srinivasan Mani
Ranch Hand
Joined: Apr 03, 2002
Posts: 36
|
|
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
Joined: Jun 06, 2002
Posts: 1056
|
|
|
Have you tried compiling and running it? What exactly do you not understand after doing so?
|
Ron Newman - SCJP 1.2 (100%, 7 August 2002)
|
 |
Srinivasan Mani
Ranch Hand
Joined: Apr 03, 2002
Posts: 36
|
|
Why not A.. Member variable i and the i inside static block is not in same scope?
|
 |
Alfred Kemety
Ranch Hand
Joined: Aug 14, 2002
Posts: 279
|
|
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 ]
|
Alfred Raouf - Egypt - SCJP 1.4<br />Kemety.equals(Egyptian) // returns true
|
 |
Srinivasan Mani
Ranch Hand
Joined: Apr 03, 2002
Posts: 36
|
|
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
Joined: Apr 03, 2002
Posts: 36
|
|
This is clear.so static is like method block. Thanks Alfred.
|
 |
 |
|
|
subject: Question on static block and static variable
|
|
|