Advertisement



< Prev
Next >



Java static keyword





The main feature of using the static keyword is, when a component of a class is marked with the static keyword, it belongs only to the class and not to the objects of the class. Now, let us see the components of a class that can be marked by the static keyword.




In Java, static keyword is used to mark and create:







A static variable/static method of a class can be accessed in two places:



//Java - A single copy of static variable is shared by all the objects of the class

class A
{

static int value=10;	            	     //Static variable of class A

public void setValue(int v)
{
	value=v;
}

public int getValue()
{
	return value;
}


public static void main(String... ar)
{
	A ob1= new A();
	ob1.setValue(20); 		    //Setting the value of static variable using ob1

	A ob2= new A();
	ob2.setValue(30);		    //Setting the value of static variable using ob2

	System.out.println(ob1.getValue()); //Accessing value of static using ob1
	System.out.println(ob2.getValue()); //Accessing value of static using ob2
}

}


Output is :


30
30


Program Analysis






Please share this article -




< Prev
Next >
< final keyword
this keyword >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement