Java Static
In Java language, the static keyword is mainly used for memory management. The static variable is shared by all the objects of that class. It is visible only within the class, but its lifetime is the entire program.
The static keyword can be used:
- Static Variable
- Static Method
- Static Block.
Static Variable
To declare a variable as static is called as static variable.
Syntax:
static data_type variable_name;
Example:
public class Staticvariable
{
static int a=5;
public static void main(String args[])
{
System.out.println("Area of the square: "+ a*a);
}
}
Static Method
Method of a class can also be declared as static. But the static method can access only static data member.
Syntax:
static data_type method_name()
{
...
}
Example:
public class Staticmethod
{
static int a=6;
static void square() //Static method
{
a=5;
}
public static void main(String args[])
{
Staticmethod.square();//calling square method
System.out.println("Area of the square: "+(a*a));
}
}
Static Block
Static block always executed before the main method.
Syntax:
static
{
....
}
Example:
public class Staticblock
{
static //Static block
{
System.out.println("Welcome");
}
public static void main(String args[])
{
System.out.println("ProgramTpoint.com");
}
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com