what is static keyword in java
Static keyword is used a lot in java. We use static keyword
mainly for memory management. In Java Static means, you
can access them without creating an object, just by using a
class name.
The best-known static method is main, which is called
by the Java runtime to start an application. The main
method must be static, which means that applications
run in a static context by default.
// example on static block in java.
public class StaticBlockExample
{
// static variable
static int a = 10;
static int b;
// static block
static
{
System.out.println("Static block called.");
b = a * 5;
}
public static void main(String[] args)
{
System.out.println("In main method");
System.out.println("Value of a : " + a);
System.out.println("Value of b : " + b);
}
}
// example on static variable in java.
class EmployeeDetails
{
// instance variable
int empID;
String empName;
// static variable
static String company = "FlowerBrackets";
// EmployeeDetails constructor
EmployeeDetails(int ID, String name)
{
empID = ID;
empName = name;
}
void print()
{
System.out.println(empID + " " + empName + " " + company);
}
}
public class StaticVariableJava
{
public static void main(String[] args)
{
EmployeeDetails obj1 = new EmployeeDetails(230, "Virat");
EmployeeDetails obj2 = new EmployeeDetails(231, "Rohit");
obj1.print();
obj2.print();
}
}
// example on static class in java.
import java.util.*;
public class OuterClass
{
// static class
static class NestedClass
{
public void show()
{
System.out.println("in static class");
}
}
public static void main(String args[])
{
OuterClass.NestedClass obj = new OuterClass.NestedClass();
obj.show();
}
}