why we use static keyword in java code example
Example 1: static keyword in java
class EmployeeDetails
{
int empID;
String empName;
static String company = "FlowerBrackets";
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 2: static in java
static keyword is a non-access modifier. static keyword can be used with
class level variable, block, method and inner class or nested class.
Example 3: static in java
The static keyword in Java is used for memory management mainly. We can apply static keyword with
variables, methods, blocks and nested classes. The static keyword belongs to the class
than an instance of the class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class
Example 4: what is static keyword in java
Static keyword is used a lot in java.
Static means, you
can access those static variables
without creating an object,
just by using a class name.
This means that only one instance of
that static member is created which
is shared across all instances of the class.
Basically we use static keyword when
all members share same instance.
Example 5: static keyword in java
import java.util.*;
public class OuterClass
{
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();
}
}