static keyword java code example
Example 1: static in java
//Java Program to get the cube of a given number using the static method
using static before a method or variable we can access it by not creating a
instance of it.in the program we directly used student.cube(5)
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Example 2: 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 3: static keyword in java
// example on static method in java.
public class StaticMethodExample
{
static void print()
{
System.out.println("in static method.");
}
public static void main(String[] args)
{
StaticMethodExample.print();
}
}
Example 4: static keyword in java
// 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 5: static keyword in java
// 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 6: 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.