Home Java Static keyword in Java with examples

Static keyword in Java with examples

In Java, the static keyword is responsible for the memory’s management. We can use the static keyword with variables, methods, blocks, and nested classes. The static keyword refers to a class rather than a specific class instance.

In Java, what is a static keyword?

If we wish to access class members in Java, we must first build a class instance. However, there will be times when we need to access class members without using variables. Java’s static keyword is also used in some cases. If we wish to access members of a class without creating a class instance, then we will need to declare these members as static. For instance, every member of the Math class is static. The implication is that members are accessible without instantiating the Math class. Below is an example illustrating this.

public class Codeunderscored {

public static void main( String[] args ) {

// accessing the methods of the Math class

System.out.println("The PI’s Value is = " + Math.PI);

System.out.println("The E’s Value is = " + Math.E);

System.out.println("The -38’s absolute value is = " + Math.abs(-38));

System.out.println("The value of 3 squared is: = " + Math.pow(3,2));

}

}

We have no instances of the Math class in the preceding example. However, we can use its abs() and pow() functions and the variables PI and E. Because the Math class’s methods and variables are static, this is possible.

The static can take the form of:

  • Variable (also known as a class variable)
  • Method (also known as a class method)
  • Block
  • Nested class

Static variable in Java

A static variable is defined as a variable that has been declared static. The static variable can refer to a property shared by all objects (but not unique to each object), such as an employee’s firm name or a student’s college name.

The static variable is only stored in memory once in the class area when the class is loaded.

Benefits of Static Variables

– It improves the memory efficiency of your Program (i.e., it saves memory).

Without using a static variable, it is possible to comprehend the situation.

class Employee {

int empID;

String name;

String workplace="ITS";

}

If your workplace has 300 employees, all instance data members will receive memory each time the object is created. Because each employee has a unique employee ID and name, an instance data member is helpful in this situation.

The term “workplace” denotes a property that all objects share. This field will only get the memory once if we make it static. Note that all objects in Java share a static attribute.

// Program for demonstrating the static variable in Java
class Employee{

int empID;//instance variable

String name;

static String workplace ="ITS";//static variable

//constructor

Employee(int r, String n){

empID = r;

name = n;

}

//method to display the values
void display (){System.out.println(empID+" "+name+" "+workplace);}

}

//Test class for demonstrating object’s values

public class TestStaticVariable1{

public static void main(String args[]){

Employee empOne = new Employee(01,"Tina");
Employee empTwo = new Employee(02,"Mike");

//we can change the workpalce of all objects by the single line of code

//Employee .workplace="remote";

empOne.display();

empTwo.display();

}

}

The counter project without using a static variable

We’ve generated a count instance variable in this example, which is incremented in the constructor. Each object will have a copy of the instance variable because it receives memory at the moment of object creation. It will not reflect other objects if it is incremented. As a result, the count variable will have a value of 1 for each item.

//Program for demonstrating the use of an instance variable in Java

//which gets memory each time we create an object of the class.

class CodeCounter{

int countVar=0;//will get memory each time when the instance is created

CodeCounter(){
countVar++;//incrementing value
System.out.println(countVar);

}

public static void main(String args[]){
//Creating objects
CodeCounter cCounterOne=new CodeCounter();
CodeCounter cCounterTwo=new CodeCounter();
CodeCounter cCounterThree=new CodeCounter();

}

}

Counter program using a static variable

As previously stated, a static variable will only receive memory once, but if the value of the static variable is changed, the value will be retained.

//Program illustrating the use of static variables shared with all objects in Java

class CounterCode{

// fetch memory once and keep its values
static int count=0;

CounterCode(){

count++;//incrementing the value of static variable
System.out.println(count);

}

public static void main(String args[]){

//creating objects
CounterCode cCode=new CounterCode();
CounterCode cCode=new CounterCode();
CounterCode cCode=new CounterCode();

}

}

Static method in Java

A static method is defined as one that employs the static keyword. Rather than the class’s object, a class’s static method belongs to the class. Further, a static method can be called without creating a class instance. In addition, a static method can access and update the value of a static data member.

// Program demonstrating the use of a static method in Java

class Employee{

int empID;
String name;
static String workplace = "IFMIS";

//To alter the value of a static variable, use the static method.
static void change(){
workplace = "remote";

}

//constructor to initialize the variable

Employee(int emp_id, String name){
empID = emp_id;
name = name;

}

//method to display values
void display(){System.out.println(empID+" "+name+" "+workplace);}
}

// Create and show object values with this test class.

public class TestStaticCodeMethod{

public static void main(String args[]){

Employee.change();//calling change method

//creating objects
Employee empOne = new Employee(111,"Karan");
Employee empTwo = new Employee(222,"Aryan");
Employee empTwo = new Employee(333,"Sonoo");

//calling display method

empOne.display();
empTwo.display();
empTwo.display();

}

}

Another static method that does a standard computation is

//Program for calculating the cube of a given number using the static method in Java

class CalculateCube{

static int cube(int x){
return x*x*x;

}

public static void main(String args[]){
int result=CalculateCube.cube(8);
System.out.println(result);
}

}

//Program demonstrating the restriction on static methods in Java
class CodeStaticMethod
{

// static variable
static int aVar = 20;
// instance variable
int bVar = 30;
// static method
static void methodOne()
{

aVar = 38;
System.out.println("from methodOne ");
// A static reference to bVar(non-static field) is not possible.
bVar = 12; // compilation error
// A static reference to the object is not possible.
// non-static method methodTwo() from the type Test

methodTwo(); // compilation error

// In a static context, you can't utilize super.
System.out.println(super.aVar); // compiler error occurs

}
// an instance method
void methodTwo()
{
System.out.println("from methodTwo ");

}
public static void main(String[] args)

{
// This is the main method
}

}

There are some limitations to the static technique

For the static technique, there are two fundamental constraints. They are as follows:

Static methods cannot use non-static data members or non-static methods, and static methods cannot call non-static methods directly.

In a static context, this and super cannot be utilized.

class Score{

int num=87;//non static

public static void main(String args[]){
System.out.println(num);

}

}

Static Classes

If a class is nested, it can only be made static. We can’t use the static modifier on top-level classes, but we can use it on nested classes. Nested static classes are an example of this type of class.

A reference to the Outer class is not required for a nested static class. In this scenario, a static class can’t access the Outer class’s non-static members.

//Program for demonstrating the use of static keywords with Classes in Java

import java.io.*;

public class Codeunderscored {

private static String str = "Codeunderscored";
// definition of the static class

static class CodeNestedClass {

// non-static method
public void disp(){

System.out.println(str);

}

}

public static void main(String args[])

{
Codeunderscored.CodeNestedClass cNested = new Codeunderscored.CodeNestedClass ();
cNested.disp();

}

}

Static Java block

It is used to set the static data member’s initial value. Further, it is called before the main function when the class is loaded.

Static block example:

class staticJavaBlock{

static{System.out.println("static block is invoked");}

public static void main(String args[]){

System.out.println("main method");

}
}

If you need to do the computation to initialize your static variables, you can create a static block executed when the class is first loaded. Consider the Java program below, which demonstrates the use of static blocks.

//Program demonstrating the use of static blocks in Java
class CodeBlock
{
// static variable

static int a = 10;
static int b;

// static block
static {

System.out.println("initializing the static block.");
b = a * 4;
}

public static void main(String[] args)
{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}

When is it appropriate to utilize static variables and methods?

For the property shared by all objects, use the static variable. For example, all employees have the same workplace name in class Employee. To change static variables, use static methods. Consider the Java program below, which demonstrates how to utilize static keywords with variables and methods.

// Program demonstrating the use of the static keyword with methods and variables
// Employee class
class Employee {

String name;
int empID;
// static variable

static String workplace;
// static counter to set unique roll no
static int counter = 0;

public Employee(String name)
{
this.name = name;
this.empID = setEmpID();
}

// getting unique empID
// through static variable(counter)
static int setEmpID ()

{
counter++;
return counter;
}

// static method
static void setWorkplace(String name) { workplace = name; }

// instance method
void getEmployeeInfo()
{
System.out.println("name : " + this.name);
System.out.println("empID : " + this.empID);
// accessing static variable
System.out.println("workplace : " + workplace);

}

}

// Driver class
public class StaticDemo {
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Employee. setWorkplace("remote");
Employee empOne = new Employee ("Mike");
Employee empTwo = new Employee("Joy");
empOne.getEmployeeInfo();
empTwo.getEmployeeInfo();
}
}

Frequently asked Questions

Why is the main method in Java presented as static?

This is because the object is not required to call a static method. If it were a non-static method, JVM would create an object first before invoking the main() method, causing an additional memory allocation problem.

Is it possible to run a program without using the main() method?

No, one of the methods was to use a static block. However, this was only feasible till JDK 1.6. A Java class cannot be executed without the main method since JDK 1.7.

class mainCode{

static{
System.out.println("static block is invoked");
System.exit(0);
}
}

Example: Program demonstrating the execution of static blocks and variables in Java

class Codeunderscored
{
// static variable
static int aVar = methodOne();
  
// static block
static {
System.out.println("Inside static block");
}

// static method
static int methodOne() {
System.out.println("from methodOne");
return 35;
}
// definiting the static method(main !!)
public static void main(String[] args)
{
System.out.println("Value of aVar : "+aVar);
System.out.println("this is from the main method ");
}
}

Example: Program demonstrating the use of static blocks in Java

class Codeunderscored
{
// defining a static variable
static int aVar = 25;
static int bVar;
  
// defining the static block
static {

System.out.println("Initializing the Static block .");
b = a * 4;
}

public static void main(String[] args)
{
System.out.println("from main");
System.out.println("Value of a Var: "+aVar);
System.out.println("Value of bVar : "+bVar);
}
}

Example: Program demonstrating that a static member can be accessed before instantiating a class in Java

class Codeunderscored
{
// static method
static void testCode()
{
System.out.println("this is from testCode");

}

public static void main(String[] args)
{
// calling testCode without creating
// any object of class testCode
testCode();
}

}

Example: Using the static block in Java

class Codeunderscored {
// static variables
static int aVar = 56;
static int bVar;
static int maxVar;

// static blocks
static {
System.out.println("First Static block.");
bVar = aVar * 3;

}

static {
System.out.println("Second Static block.");
maxVar = 65;
}

// static method
static void showValues() {
System.out.println("The value of aVar = " + aVar);
System.out.println("The value of bVar = " + bVar);
System.out.println("The value of maxVar is = " + maxVar);

}

public static void main(String args[]) {
// calling the static method
showValues();

}
}

Example: The static and non-static Java Methods

class StaticCode {
// Defining a method that is non-static
int multiplyValues(int aVar, int bVar){
return aVar * bVar;
}

// Defining a static method
static int addValues(int aVar, int bVar){
return aVar + bVar;
}
}

public class Codeunderscored {

public static void main( String[] args ) {
// create an instance of the StaticTest class
StaticCode sCode = new StaticCode();
// call the non-static method
System.out.println(" The result of 8 * 3 is = " + sCode.multiplyValues(8,3));
// call the static method
System.out.println("The result of 9 + 11 = " + StaticCode.addValues(9,11));

}

}

Conclusion

In Java, the static keyword is used chiefly to control memory. Further, Java’s static keyword shares an identical variable or procedure across many classes. Variables, methods, blocks, and nested classes can all employ static keywords. The static keyword denotes a class rather than a single instance of that class. The static keyword denotes a constant variable or a method that is the same for each class instance.

You may also like

Leave a Comment