• 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 » Classes » Static Fields in Java with Example
Next →
← Prev

Static Fields in Java with Example

By Dinesh Thakur

In each object of a class will have its own copy of all the fields of the class. However, in certain situations, it may be required to share a common copy of fields among all the objects of the same class. This is accomplished by declaring the field(s) to be static and such fields are known as static field(s). If a field is declared static then there is one field for the entire class instead of one per object. A static field of a class is often referred to as a class variable because static field is associated with a class and not with individual instances of the class. A static field gets memory only once for the whole class no matter how many objects of a class are created. To declare a static field, prefix the field declaration in the class with the static modifier. Its syntax is,

static datatype fieldName;

class Rectangle 
{
     int length; //length of rectangle
     int breadth; //breadth of rectangle
     static int rectCount =0; //count rectang objects
  
    void setData(int l,int b)
     {
     
        length=l;
        breadth=b;
        rectCount++;
     }
     //method to calculate area of rectangle
     int area()
     {
        int rectArea;
        rectArea = length * breadth;
        return rectArea;
       
     }
}
  //class to create Rectangle objects and access static field
  class StaticField
  {
     public static void main(String[] args)
     {
        //create first rectangle object
       Rectangle firstRect =new Rectangle();
       firstRect.setData(5,6);
       System.out.println("Area of Rectangle 1 : "+firstRect.area());
       //create second rectangle object
       Rectangle secondRect =new Rectangle();
       secondRect.setData(10,20);
       System.out.println("Area of Rectangle 2 : "+secondRect.area());
       // access static field of rectangle class
       System.out.println("Total Number of Objects : "+ Rectangle.rectCount);
       }
   }

Static Fields in Java with Example

In the above example, the class Rectangle has two instance variables length and breadth and one class variable rectCount. When we create firstRect and secondRect objects of type Rectangle, each has its own copy of length and breadth instance variables but both share a single copy of class variable rectCount. The class variable rectCount is initialized to 0 only when the class is first loaded, not each time a new object is made. When the object firstRect is created and the setData () method is invoked, the static variable rectCount is incremented by 1 and it is set to 1 (= 0+ l). Similarly, when the object secondRect is created and the setData () method in invoked the value of rectCount variable is set to 2 (= 1+l). Finally, the statement,

System.out.println(“Total Number of Objects : “+ Rectangle.rectCount);

prints the total number of objects.

From the above example, we find that one use of class variable is to keep a count of how many objects of a class have been created in your program another use of class variable is to define constants which are shared by all the objects of the class. To understand this, let us consider a problem which maintains account information of multiple customers by updating the balance periodically with the same interest. In order to simulate it, we create a Account class which contains the fields like account number, balance, rate of interest etc. To represent individual customer, we need to create an object. Each object will store all its fields in separate memory location. As we have different account number and balance for every Account object but the rate of interest for all the account object is the same. So allocation of separate memory to data member rate of interest for all the objects will cause the following problems.

a) Wastage of memory space will occur because the same value of rate of interest is maintained by all the objects of Account class.

b) If the value of rate of interest changes over time, then each copy would have to be updated that can lead to inefficiency, wastage of time and greater potential of errors.

So in order to overcome this problem, we need to store the rate of interest only once in memory which can be shared by all the objects of the same class. This problem can be solved by declaring the ‘rate of interest’ as a static field. But this may lead to accidental modification as it may be accessed from outside the class and lead to undesirable effects on the efficiency and reliability of the program. In such a case, you have to use the final keyword along with static so that this field can never have its value changed.

Properties of Static Field

A static field of a class has the following characteristics:

1. There is only one copy of static field in a class which is shared among all the objects of the class.

2. A static field can be accessed before any object of a class is created, without reference to any object.

3. To make a static field constant in Java, make a variable as both static and final.

4. The static field is similar to static variable. The main difference is that a static variable is used to retain information between calls whereas static field is used to share information among multiple objects of a class.

You’ll also like:

  1. Static Method and Static Variable in Java Example
  2. What is Static Data Members and Static Member Functions
  3. Static Methods in Java Examples
  4. Text Fields in Java Example
  5. Java Static Variables 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