JAVATECH NEWS

Java

CORE JAVA

Interview

OFF-CAMPUS

Monday 10 November 2014

Static variable and static methods in Java


Static Variable :
Static variable is also called class variable,a single copy of static or class variable is shared by all object in memory.Static variables are stored in method area.

Static method:static method are the method which does not work on instance variable because JVM gives static method higher preference and then create the object since objects are not present at the time of calling the static method so instance variables are not available to act on them ,static method is declared by static keyword,and these are called by Classname.methodname()
Here is an example:

class Static 
{
static double sum(double x,double y) //method should be declared as static
{
double result=x+y;
return result;
}
}

class StaticExample
{
public static void main(String args[])
{
double z=Static.sum(10.5,15.5); //Calling the static method by Classname.methodname()
System.out.print("Answer is : "+z);
}
}

No comments:

Post a Comment

Designed By Blogger Templates