Digital Stronghold - Software Engineering, Musicality and Facts of Life…



August 22, 2008

Static Methods and Variables in Java

Static methods and variables are shared by all instances of the class. Static variables are initialized when a class is loaded whereas instance variables are initialized when an instance of the class is created. Static methods belong to a class, therefore, it can only access static members of the class and it can be called before instantiating the class.

class StaticCase {
	static int staticCounter = 0;
	int nonStaticCounter = 0;
	
	StaticCase() {
		staticCounter++; //class level
		nonStaticCounter++; //instance level
	}
}
	
class StaticCaseImpl {
	
        //static method, entry point
	public static void main(String... args) {
                //StaticCase.nonStaticCounter, error, not a static variable
	
		StaticCase sc1 = new StaticCase();
		StaticCase sc2 = new StaticCase();
	
		System.out.println("staticCounter sc1: " + sc1.staticCounter);
		//output is staticCounter sc1: 2
                //or in static context, StaticCase.staticCounter
		System.out.println("nonStaticCounter sc1: " + sc1.nonStaticCounter);
		//output is nonStaticCounter sc1: 1
	
		System.out.println("staticCounter sc2: " + sc2.staticCounter);
		//output is staticCounter sc2: 2
                //or in static context, StaticCase.staticCounter
		system.out.println("nonStaticCounter sc2: " + sc2.nonStaticCounter);
		//output is nonStaticCounter sc2: 1
	}
}

Comments »

The URI to TrackBack this entry is: http://eradicus.blogsome.com/2008/08/22/static-methods-and-variables-in-java/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.

Theme designed by Joset Anthony Zamora


Digital Stronghold

↑ Get Headline Animator