CodesJava

Easy learning with example program codes

static keyword in java


Static is a keyword in java used to represent the class members. It can be used with variable, method, initializer block and nested class.

Types of class members:

  1. Static data members.
  2. Static initializer block.
  3. Static method.
  4. Static nested class.

1. Static data members:

Data members declared with static keyword are known as static data members. These are mainly used to represent those properties which are common to every object. At the time of class loading a single copy is created for static data members, which is shared by all objects.

Memory division in a java program execution.

In a java program execution memory is divided into three parts:

  1. Stack.
  2. Heap.
  3. Class/Method area.
  1. Stack: Stack is used to local variables of the methods.
  2. Heap: Heap is used to store objects.
  3. Class Area: Class area is used to store static data members.

Static data members are used to represent those properties which are common to every object.

Example: 

StaticExample1.java

/**
 * This program is used to show that static data members are
 * used to represent those properties which are common to every object. 
 * @author CodesJava
 */
class MCAStudent{
	//name and rollNo are not common for all students
	//so keep them as non-static data members.
	String name;
	int rollNo;
	//As course offered is same for all students
	//so keep it as static.
	String courseName = "MCA";
 
	//constructor
	MCAStudent(String n, int r){
		name = n;
		rollNo = r;
	}
 
	//display all values
	public void display(){
		System.out.println("Name = " + name);
		System.out.println("RollNo. = " + rollNo);
		System.out.println("Course Name = " + courseName);
		System.out.println("");
	}	
}
 
public class StaticExample1 {
	public static void main(String args[]){
		//create object of MCAStudent class.
		MCAStudent stu1 = new MCAStudent("jai", 6);
		MCAStudent stu2 = new MCAStudent("sunil", 15);
 
		//method call
		stu1.display();
		stu2.display();
	}
}

Output:

Name = jai
RollNo. = 6
Course Name = MCA
Name = sunil
RollNo. = 15
Course Name = MCA

Download this example.

Non-static data members have different memory locations for different objects.

Example:

StaticExample2.java

/**
 * This program is used to show that non-static data members
 * have different memory locations for different objects.
 * @author CodesJava
 */
class Test{
	int num = 0;
 
	//constructor
	Test(){
		num = num + 10;
		System.out.println("Number = " + num);
	}
}
 
public class StaticExample2 {
	public static void main(String args[]){
		Test obj1 = new Test();
		Test obj2 = new Test();
		Test obj3 = new Test();
		Test obj4 = new Test();		
	}
}

Output:

Number = 10
Number = 10
Number = 10
Number = 10

Download this example.

Static data members use the same memory locations for all objects.

Example:

StaticExample3.java

/**
 * This program is used to show that static data members
 * use the same memory locations for all objects.
 * @author CodesJava
 */
class Test{
	static int num = 0;
 
	//constructor
	Test(){
		num = num + 10;
		System.out.println("Number = " + num);
	}
}
 
public class StaticExample3 {
	public static void main(String args[]){
		Test obj1 = new Test();
		Test obj2 = new Test();
		Test obj3 = new Test();
		Test obj4 = new Test();		
	}
}

Output:

Number = 10
Number = 20
Number = 30
Number = 40

Download this example.

Note: Constructor is not used to initialize the static data members because constructor initializes many times but static data members only once. So instead of constructor static initialize block is used to initialize static data members.

Static initializer block: Click here for static initializer block.

Static methods:

Static methods represent the behavior of whole class. An instance of a class is not required to execute static methods. They can be called using class name.
Syntax: ClassName.methodName

Example:

StaticExample4.java

/**
 * This program is used to show that there is no need of an object
 * for accessing a static method. It can be called with class name.
 * @author CodesJava
 */
class Display {
	//static method
	public static void display(){
		System.out.println("Hello codesjava.com");
	}
}
public class StaticExample4 {
	public static void main(String args[]){
		//No need for object to call static method.
		Display.display();
	}
}

Output:

Hello codesjava.com

Download this example.

Note: We can execute a program without main method.

Example:

/**
 * This is java program without using main function.
 * @author CodesJava
 */
public class WithoutMain {
       static{
               System.out.println("Hello codesjava.com");
               System.exit(0);
       }
}

Output:

Hello codesjava.com

Limitations of static methods and static initialize blocks.

  1. Non-static data members can’t be accessed in static methods and static initialize blocks.
  2. Non-static methods can’t be invoked in static methods and static initialize blocks.
  3. This or super keyword can’t be refers in static methods and static initialize blocks.

1. Non-static data members can’t be accessed in static methods and static initialize blocks.

Example:

StaticExample5.java

/**
 * This program is used to show that non-static data members can’t 
 * be accessed in static methods and static initialize blocks. 
 * @author CodesJava
 */
class Test {
	//non-static data member
	int num = 10;
 
	static{
		//error because non-static data members can't be 
		//accessed in static initializer block.
		System.out.println("Num = " + num);
	}
 
	public static void display(){
		System.out.println("Hello codesjava.com");
		//error because non-static data members can't be 
		//accessed in static method.
		System.out.println("Num = " + num);
		show();
	}
 
}
 
public class StaticExample5 {	
	public static void main(String args[]){
		//creating object of Test class
		Test obj = new Test();
		//method call
		obj.display();
	}
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problems:
Cannot make a static reference to the non-static field num
Cannot make a static reference to the non-static field num
The method show() is undefined for the type Test
at com.codesjava.business.Test.(StaticExample5.java:15)
at com.codesjava.business.StaticExample5.main
(StaticExample5.java:31)

Download this example.

2. Non-static methods can’t be invoked in static methods and static initialize blocks.

Example:

StaticExample6.java

/**
 * This program is used to show that non-static methods can’t 
 * be accessed in static methods and static initialize blocks. 
 * @author CodesJava
 */
class Test {
	//non static method	
	public void show(){
		System.out.println("Hello world.");
	}
 
	static{
		//error because non-static methods can't be 
		//accessed in static initializer block.
		show();
	}
 
	public static void display(){
		System.out.println("Hello codesjava.com");
		//error because non-static methods can't be 
		//accessed in static method.
		show();
	}
 
}
 
public class StaticExample6 {	
	public static void main(String args[]){
		//creating object of Test class
		Test obj = new Test();
		//method call
		obj.display();
	}
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problems:
Cannot make a static reference to the non-static 
method show() from the type Test
Cannot make a static reference to the non-static 
method show() from the type Test
at com.codesjava.business.Test.(StaticExample6.java:17)
at com.codesjava.business.StaticExample6.main
(StaticExample6.java:32)

Download this example.

3. This or super keyword can’t be refers in static methods and static initialize blocks.

Example:

StaticExample7.java

/**
 * This program is used to show that this or super keyword can’t 
 * be refers in static methods and static initialize blocks.
 * @author CodesJava
 */
class Show {
	int num = 10;
}
 
class Display extends Show {
	int num = 20;
 
	public static void show(){
		//error because super can't be refers in static 
		//method or static initializer block.
		System.out.println("num of super class = " + super.num);
	}
 
	public static void display(int num){
		//error because this can't be refers in static 
		//method or static initializer block.
		this.num = num;
	}
 
}
 
public class StaticExample7 {
	public static void main(String args[]){
		Display obj = new Display();
		obj.show();
		obj.display(20);
	}
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problem:
Cannot use super in a static context
at com.codesjava.business.Display.show
(StaticExample7.java:18)
at com.codesjava.business.StaticExample7.main
(StaticExample7.java:32)

Download this example.
 
Next Topic: final in java with example.
Previous Topic: super in java with example.

Related Topics:

Package in java with example.
Access modifier in java with example.
Static import in java with example.
Package class in java with example.
this in java with example.
Instance initialize/ Anonymous block in java with example.
super in java with example.
Static in java with example.
final in java with example.

 

Core Java Tutorial

Programming language overview.
Overview of Java.
Java features
JVM architecture details.
JVM, JRE and JDK.
Java Coding Guidelines.
Some important definitions.
Variable and data types.
Hello world java program.
Core java examples programs.
Important Java Programs.
How to set permanent path in java?
OOPs Basics.
Object and Class in Java.
OOPs Principles/Concepts.
Abstraction in java.
Encapsulation in java.
Polymorphism in java.
Method overloading in java.
Method overriding in java.
Dynamic method dispatch.
Runtime polymorphism.
Association in java.
Inheritance in java.
Aggregation in java.
Command line arguments in java.
Command line argument program in eclipse.
Read input from command line using Scanner.
Java array programs
Java star pattern programs
Java number pattern programs
final in java.
Abstract class in java.
Interface in java.
Custom marker Interface in java.
Constructor in java.
Package in java.
Access modifier in java.
Static import in java.
Package class in java.
this in java.
Instance initialize block.
Anonymous block.
super in java.
Static in java.
final in java.
Java cloning deep and shallow
Shallow vs Clone copy
String handling in java.
String handling programs.
StringBuffer in java.
StringBuilder in java.
Exception Handling Tutorial.
Multithreading Tutoial.
Java input output stream tutorial.
Collections framework in java tutorial.
Collections framework programs.
Java Random class
Java annotations.
Java design principles.
Java 7 features
Java 8 features
Java networking tutorial
Java Reflection tutorial
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki