Usage of Static Keyword in java

Static keyword is used in following three scenarios.

  • To define Class variables
  • To define Static block
  • To define Class methods

Class variables

Class variable are used to share common properties among objects. Class variables are created while loading of class. Like Company Name,College Name can be shared with employee object or student objects.Class variable can be created using static keyword within the class outside any method. We can initialize class variables using static block.

Static block

Static block is used to initialize static data members.Here companyName is static data member initialized with value “ABC Company”.

Syntax to define static block


static{

static data member1=value1;

static data member2=value2;

}

Example to use static keyword to create Class Variable

Employe.java


package com.startwithjava;
public class Employee {
private int id;
private static String companyName;
private int salary;
static{
companyName = "ABC Company";
}
public Employee() {
super();
}
public Employee(int id, int salary) {
super();
this.id = id;
this.salary = salary;
}
public static String getCompanyName(){
  return companyName;
}
public void display(){

System.out.println("Id:"+id+" \tSalary:"+salary+" \tCompany: "+companyName);
}

}

ClassVariableTest.java


package com.startwithjava;
public class ClassVariableTest {
public static void main(String args[]){
Employee e = new Employee(1,40000);
Employee e2 = new Employee(2,50000);
e.display();
e2.display();
}

}

Output

Id:1     Salary:40000     Company: ABC Company
Id:2     Salary:50000     Company: ABC Company

Class Methods

Class methods are same as class variable can be shared to all objects.Class methods can be accessed through class name without creating object.Static methods can only static data members.Here getCompanyName() is static method which returns the CompanyName static data member.

Syntax to access class methods.


ClassName.methodName(argument1,argument 2,...argument n);

Employee.java


package com.startwithjava;

public class Employee {
private int id;
private static String companyName;
private int salary;
static{
companyName = "ABC Company";
}
public Employee() {
super();
}
public Employee(int id, int salary) {
super();
this.id = id;
this.salary = salary;
}
public static String getCompanyName(){
return companyName;
}
public void display(){

System.out.println("Id:"+id+" \tSalary:"+salary+" \tCompany: "+companyName);
}
}

TestMain.java

package com.startwithjava;
public class TestMain {
	public static void main(String args[]){
		Employee e = new Employee(1,40000);
		e.display();
		String cmpName = Employee.getCompanyName();
		System.out.println("Company Name: "+cmpName);
	}

}
  

Leave a Reply