Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Block

 
farrukh mahmud
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
------------------
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic