*
The moose likes Java in General and the fly likes Static Block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Static Block" Watch "Static Block" New topic
Author

Static Block

farrukh mahmud
Ranch Hand

Joined: Feb 13, 2001
Posts: 47
i made a class
class Init
{
static String b="abc";
Static
{
String b=new String("xyz")'
}
public static void prt(String s)
{
System.out.println(s);
}
public static void main(String args[])
{
Init obj=new Init();
obj.prt(a);
//obj.prt(b);
}
}
teh code compiles good but when i wana String b then it creates compile time error that b is not declared as it is declared in a static block. I want that should be printed on my call not on static block as i did print in static block?
now is there nay way to access that String b from main? so i can display it???
thankyou!
------------------

Regards<BR>Farrukh Mahmud
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi,
There are numerous compiler errors in the code that you have given. Once those are corrected the program runs fine. The corrected code:

produces the result: "abc". The reason is that in the static block you are declaring a String b that has only scope inside the static block. The following code will produce the result: "xyz".

Regards,
Manfred.
farrukh mahmud
Ranch Hand

Joined: Feb 13, 2001
Posts: 47
oh sorry for that mistakes it was typed in a hurry. but can we
utilize string a & string b as well
or not?

if not thanks for reply i stuck my head many times with this matters now i got the ans
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static Block
 
Similar Threads
When is a String a constant?
local varible scope
Instance Initializer means what
Execution Order of Static, Init, Instance Blocks
static variable