Jump to content


 


Register a free account to unlock additional features at BleepingComputer.com
Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.


Click here to Register a free account now! or read our Welcome Guide to learn how to use this site.

Photo

JAVA: ERROR IN STATIC INITIALIZATION BLOCKS


  • Please log in to reply
4 replies to this topic

#1 msrrahul

msrrahul

  • Members
  • 32 posts
  • OFFLINE
  •  
  • Local time:08:22 AM

Posted 27 July 2011 - 07:03 AM

why does compiler produce an error in the following static initialization blocks?

class Manager3 
{
	
	static
	{
		System.out.println(i);
		i=10;
	}
	
	public static void main(String[] args) 
	{
		System.out.println(i);
	}
	static int i;
}

Edited by groovicus, 27 July 2011 - 07:18 AM.


BC AdBot (Login to Remove)

 


#2 groovicus

groovicus

  • Security Colleague
  • 9,963 posts
  • OFFLINE
  •  
  • Gender:Male
  • Location:Centerville, SD
  • Local time:10:22 AM

Posted 27 July 2011 - 07:19 AM

It would be helpful if you didn't make us guess what the error is. <_<

#3 msrrahul

msrrahul
  • Topic Starter

  • Members
  • 32 posts
  • OFFLINE
  •  
  • Local time:08:22 AM

Posted 27 July 2011 - 08:10 AM

line 1 in the static initialization block in the following program produces an error. what is the explanation??

but if this line is commented then there is no error.. seeking help in understanding this.

thanks



class Manager3
{

static
{
/* line 1 */ System.out.println(i); // can not reference a field before it is defined.
i=10;
}

public static void main(String[] args)
{
System.out.println(i);
}
static int i;
}

#4 groovicus

groovicus

  • Security Colleague
  • 9,963 posts
  • OFFLINE
  •  
  • Gender:Male
  • Location:Centerville, SD
  • Local time:10:22 AM

Posted 27 July 2011 - 11:26 AM

You are using the variable 'i' before it has been declared. Static methods run in the order they appear. You are not actually declaring it until the end of the file. By then, the static method has already ran.

#5 msrrahul

msrrahul
  • Topic Starter

  • Members
  • 32 posts
  • OFFLINE
  •  
  • Local time:08:22 AM

Posted 29 August 2011 - 05:26 AM

thanks a lot !!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users