• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » DataType » Static keyword in Java (With Examples)
Next →
← Prev

Static keyword in Java (With Examples)

By Dinesh Thakur

We use the static keyword mostly for memory management, and the keyword goes with the class itself, not with a class instance. It may be:  

• A variable, or class variable
• A method, or class method
• A block
• A nested class
• Static Variable

Static variables used for referencing common properties of every object – these are properties that are not unique to any one object. An example would be the name of the organization for a group of employees or the name of a college for a  group of students.
Static variables are only allocated memory when they are in the class at the time the class load. Because of this, they increase the efficiency of your program memory. Here’s an example that does not have a static variable:

class Student{
int
rollno;
   String name;
   String college=“DAV”;
}
Now let’s assume that our college has 500 students in it. Every one of the instance data members allocated memory every time the object gets created. Every student has their unique name and roll number, so the use of the instance data member is good enough. In the code above, the word ‘college’ is referencing the property commonly shared between each object. If we were to change that to a static variable, the memory would allocate just once because the static property gets shared among every object.

Here’s the example:
//This will demonstrate the use of a static variable

class Student{
    int rollno;
    //instance variable
    String name;
    static String college =“DAV”;
    //static variable
    //constructor
Student(int r,String n)  {
rollno = r;
name = n;
    }
      //this method will display the values
      void display ()  {
          System.out.println(rollno+” “+name+” “+college);
       }
}
    //this test class will show the object values
     public class TestStaticVariable1 {
         public static void main(String args[])  {
Student s1 = new Student(111,“Dinesh”);
Student s2 = new Student(222,“Punardeep”);
            //we can use one line of code to change the college property for all the objects
           //Student.college=”D.A.V”;
s1.display();
s2.display();
     }
}
The output of this will be:
111 Dinesh DAV
222 Punardeep DAV

We’ll be covering the following topics in this tutorial:

  • Counter Program – No Static Variable
  • Counter Program – With Static Variable
  • Static Method in Java
  • Static Method Restrictions
  • Static Block in Java

Counter Program – No Static Variable

Here, we are creating an instance variable with a name of the count. This variable has increment within the constructor. Because the variable is going to be allocated memory when the object created, each of the objects contains a copy of that instance variable. Incrementation does not affect the other objects, leaving the  count variable in each one with a value of 1:

//this shows you how to use an instance variable
//which are allocated memory whenever a class object created
class Counter{
int count=0;
     //this will be given memory at the time the instance is created
Counter(){
count++;
     //incrementing value
    System.out.println(count);
}
    public static void main(String args[]){
      //Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
   }
}
The output of this: 1 1 1

Counter Program – With Static Variable

As we saw above, the static variable is allocated memory just once; if any of the objects modify the static variable value, the object retains its value:

//This will demonstrate how a static variable is used
//and which is shared between all the objects
class Counter2 {
static int count=0;
          //is only allocated memory once and retains its value
Counter2()  {
count++;
         //increments the static variable value
        System.out.println(count);
    }
   public static void main(String args[]){
      //creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
The output of this: 1 2 3

Static Method in Java

If the static keyword applied to a method, it becomes known as a static method and, like the variable, it belongs to the class and not the class instance. There is no need to create a class instance to invoke a static method, and the method may access a static data member and modify its value.
Here’s an example:

//This shows you how a static method is used
class Student {
    int rollno;
    String name;
    static String college =“DAV”;
    //This static method modify the static variable value
    static void change() {
college =“D.A.V”;
    }
    //This constructor initializes the variable
Student(int r,String n) {
rollno = r;

       name = n;
    }
    //This method displays the values
void display()  {
        System.out.println(rollno+” “+name+” “+college);
    }
}
   //This is a test class that creates and displays object values
public class TestStaticMethod {
    public static void main(String args[]) {
Student.change();
         //calling change method
         //creating objects
Student s1 = new Student(001,“Dinesh”);
Student s2 = new Student(002,“Punardeep”);
Student s3 = new Student(003,“Sandeep”);
           //calling display method
s1.display();
s2.display();
s3.display();
    }
}
The output of this will be:
001 Dinesh D.A.V
002 Punardeep D.A.V
003 Sandeep D.A.V
Here’s an example of a static method carrying out a normal calculation:
//This will use the static method to retrieve the cube of a specified number
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);
     }
}
The output of this will be:125

Static Method Restrictions

The static method has 2 main restrictions:
• A static method may not directly call a non-static method or use a non-  static data member
• The keywords, this and super, cannot be used in any static context  Here’s an example:

class A  {
int
a=40;
    //non static
    publicstaticvoid main(String args[]){
        System.out.println(a);
    }
}
The output of this will be: Compile Time Error

Static Block in Java

Static blocks in Java are used for initializing the static data members and are executed at class loading time before execution of the main method.
Here’s an example:

class A2 {
    static {
        System.out.println(“static block is invoked”);
    }
    publicstaticvoid main(String args[]) {
System.out.println(“Hello main”);
    }
}
The output of this will be: static block is invoked
Hello main

You’ll also like:

  1. Static Methods in Java Examples
  2. Static Fields in Java with Example
  3. Static Variable in Java Example
  4. Static Method and Static Variable in Java Example
  5. Java this keyword with example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW