Use of Static keyword in java


Static keyword

In this section we discuss the clear use of static keyword, this static keyword can be used in both variable (excludes local variable) and methods.

The variable or method declared a static will be associated with class rather than objects of the class.

 

Static variable or class variable

Static variable will always have a single value at runtime, assume you have few objects created for a class each objects will have their own copies of member variables but these static variables are shared between the objects and will have only one copies all time.

 class Student {

	String name;

	String gender;

	static int currentYear;

} 

Here name and gender will be associated with objects, whereas currentYear will be associated with class since they are common to all objects.

 

Accessing static variable

                You can access static variable with object or using class name Ex: ob.currentYear=2016 or Student.currentYear=1026

But accessing using object is discouraged because it does not make it clear that they are class variables.

 

Static Methods or Class Methods

                Static method can be used to do any operation that doesn?t depends on member variable or to access static fields

Syntax

ClassName.methodName(args)

 

Example 1:

class Student
{
	String name;
	String gender;
	static int currentYear;

	public static void cube(int i)
	{
		System.out.println(i * i * i);
	}

	public static int getCurrentYeat()
	{
		return currentYear;
	}
} 


Accessing static methods

You can access the static method using object or class name, but accessing using object is discouraged because it does not make it clear that they are static method.

Example

int year=Student.getCurrentYear();

Student.cube(3); // prints 27



Related Post

Comments


©candidjava.com