Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm basically refining, completing and trying to compile a test code from a reference book for java beginners. The objective is to learn the job of static block.
Java
class TimePass3 
{
	void show1()
	{
		int a;
		static
		{	
			System.out.println("Hi1");
		}	
	}
	void show2()
	{
		static
		{	
			System.out.println("Hi2");
		}	
	}

	public static void main(String[] args) 
	{
		show1();
		show2();
		static
		{	
			System.out.println("Hi2");
		}	
	}
}

While compiling this code I am getting a error at
"Illegal start of expression static"

What is the mistake in this code?

What I have tried:

Please help me resolve this.
Thanks.
Posted
Updated 30-May-17 0:38am
v2

As far as I know, such static blocks (inside methods) are illegal in Java programming language. Instead, you may have a static blocks as class initializers, see, for instance: Java - Static Class, Block, Methods and Variables[^].
 
Share this answer
 
Comments
palak22 30-May-17 7:56am    
are you sure static blocks inside methods are illegal?
CPallini 30-May-17 8:02am    
Pretty sure, albeit I am not a Java expert. Do you have a working example of a static block in a method?
Richard MacCutchan 30-May-17 8:32am    
CPallini is correct. You cannot just drop static blocks anywhere inside methods like this. Please follow the link I provide above (and the one in your other question) and learn Java properly.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900