Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

What is Static Keyword in Java? Various Applications Explained

Updated on 03 July, 2023

6.5K+ views
9 min read

Static is a reserved keyword in Java. This blog will explain how we can apply a static keyword in Java to various programming aspects, including variables, blocks, methods, and nested classes.

What is a Static Keyword in Java Programming Language?

In Java, when a static member indicates that it belongs to a type itself instead of being an instance of that type. It means that only one instance of a static member is created and shared across all class instances.

The primary method of the class is generally static. The static keyword in Java is used for a constant variable or a method that is the same for all class instances. The keyword is primarily used for memory management. Learn more about Java architecture and components.

What is the use of Static Keyword in Java?

  • Shared Data

One of the primary use cases of static variables is maintaining shared data across class instances. For instance, if we have a class representing a bank, a static variable can keep track of the total number of bank accounts created, as it is information shared among all account objects.

  • Constants

Static variables are commonly used to define constants in Java. By declaring a variable as static final, we ensure that its value remains constant throughout the execution of the program. These constants can be accessed without creating an instance of the class, making them easily accessible in various parts of the program.

  • Utility Methods

The static keyword is also used to define utility methods that perform specific tasks and are not associated with any particular object. Utility methods often provide common functionality and can be called using the class name. Examples include mathematical calculations, string manipulation, and file operations.

  • Singleton Pattern

The static keyword is employed in implementing the Singleton design pattern, where only one instance of a class should exist in the entire program. By defining the constructor as private and providing a static method to access the single instance, we ensure that no other instances can be created. The static instance variable stores the sole instance of the class.

  • Improving Performance

The use of static methods and variables can lead to performance improvements. Since static members belong to the class, they are loaded and initialized once, reducing memory consumption and avoiding redundant memory allocation for each object.

The Usage of the Static Keyword in Java Examples

In Java, the static keyword plays a crucial role in defining class-level members and their behaviour. Static variables enable the sharing of data among all instances of a class, while static methods provide utility and common functionality accessible without object instantiation. Understanding the purpose and applications of the static keyword is essential for writing efficient and well-structured Java programs. By leveraging static members effectively, developers can design scalable applications with optimized memory usage and improved performance.

A few examples pf the usage of static keywords in Java includes: 

Static Variable:

public class Counter {
    private static int count;
    public void increment() {
        count++;
    }
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        c1.increment();
        System.out.println("Count: " + c1.count); // Output: 1
        c2.increment();
        System.out.println("Count: " + c2.count); // Output: 2
    }
}

Static Method:

     public class MathUtils {
    public static int sum(int a, int b) {
        return a + b;
    }
    public static void main(String[] args) {
        int result = MathUtils.sum(5, 10);
        System.out.println("Sum: " + result); // Output: 15
    }
}

Static Constant:
    public class Constants {
    public static final double PI = 3.14159;
    public static void main(String[] args) {
        System.out.println("The value of PI is: " + Constants.PI); // Output: The value of PI is: 3.14159
    }
}


Singleton Pattern:
    public class Singleton {
    private static Singleton instance;
    private Singleton() {
        // Private constructor to prevent direct instantiation
    }
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Similarly, if you’re wondering what is static variable in Java, it is a variable that belongs to the class, not the instance of the class. This means that only one copy of the static variable exists, no matter how many instances of the class exist in your program. Static variables are typically used for constants or for maintaining state information within a class across all its instances. They can also be used to provide access control by making them private and then providing public static methods to manipulate them. Furthermore, static variables can be used to optimize memory usage since multiple objects will share the same variable rather than having each object store its own copy.

How do you create Static Members?

Static members can be created by preceding their declarations with the keyword static. Any member declared as static can be accessed before any objects of its class are created without referencing any object.

The static keyword in Java is a non-access modifier. It can be used for –

  • Variables
  • Methods
  • Blocks
  • Nested Classes

Static Variable

Static variables are primarily global variables. When you define a variable as static, a single copy of the variable is created and shared among all objects at the class level. Static variables are created at the class level, and all the instances of the class share the same static variable.

Using Static Variables

  • When the value of the variables needs to be shared across all objects.
  • When the value of the variables is independent of the objects.

Things to Remember

  • Static variables can be declared only at the class level.
  • To access static variables, you do not need to initialize objects.
  • Static variables don’t need any object reference. They can be directly accessed using the class name.
  • Though static variables can be accessed using an object reference, it should be avoided to prevent confusion between a class variable or an instance variable. Always refer to them by using the class name.

Read: Pattern Programs in Java

Static Method

When a method is declared with the keyword static, it’s known as a static method. Static methods have the following restrictions –

  • Static methods can call other static methods only.
  • Static methods can directly access static data.

If you want to share specific code across all class instances, you need to write the code in a static method.

Static methods are also used to create helper or utility classes so that one doesn’t need to create a new object of these classes for obtaining them.

Using Static Methods

  • To manipulate or access other static methods and static variables that don’t depend upon objects.
  • They are widely used in helper and utility classes.

Things to Remember

  • Static methods can’t use ‘super’ or ‘this’ keywords.
  • Abstract methods can’t be static.
  • Static methods in Java are resolved at compile time and hence, can’t be overridden.
  • Static methods can’t access instance methods or instance variables directly. They need some object reference for doing this.

Why is the Main Method in Java Static?

As static methods don’t need an object for invoking Java, the main method is static. Had it not been static, JVM would need to have created an object before calling the main(), leading to extra memory allocation.

Static Block

Static blocks make it easy to initialize variables with predefined values. The following code demonstrates the usage of a static block that contains a variable declaration that is executed exactly once when the class is loaded.

Using Static Block

  • When static variables initialization needs some additional logic except assignment
  • When static variables initialization is error-prone and needs exception handling

Things to Remember

  • Static variables and static blocks are resolved and executed in the same order as they appear in the class.
  • Multiple static blocks can be present in a class.

Must Read: Java Project Ideas & Topics

Static Class

Only a nested class can be made static. A nested static class doesn’t need a reference for the outer class.

Using Static Nested Class

  • Increases encapsulation
  • Makes the code more manageable and increases readability
  • If the nested class doesn’t need any access to the instance members of its enclosing class, it’s a good idea to declare it as static. That way, it won’t be coupled to the outer class and won’t need any stack or heap memory.

Things to Remember

  • Static nested classes can’t access any instance members of the enclosing classes.
  • They can access all static members of the enclosing class.
  • The top-level class can’t be static.

Enroll in Software Engineering Courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusion

This blog explained the static keyword in Java and its use in variables, methods, blocks, and nested classes. 

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. How is the static keyword different from the final keyword?

A static variable or method can be accessed directly in the program without using an instance of that class. A final variable in Java can only be initialised once, and its value remains the same throughout the program, whereas a static variable can be initialised again. A final variable cannot be inherited by a variable or a subclass method. Also, classes cannot override final variables. On the other hand, static methods can call other static methods but can only access the static members of the class. A static class cannot have any objects; it will only consist of static variables and methods.

2. Explain the relevance of every keyword in public static void mainString args?

Firstly, we use public, an access modifier that specifies that any variable or method can access the main() method. Then, we use the static keyword, which identifies the main() method as class-based. The main() can be accessed without instantiating the class. The compiler will throw an error if you do not declare the main() method static. main() is called by the JVM (Java Virtual Machine) before all the objects are made. The return type of the main() method in Java is void which means it doesn’t return a value, and args refer to the arguments passed to the main() method while we run the code.

3. How are interfaces different from abstract classes?

The interfaces can only consist of abstract methods, whereas abstract classes can contain abstract and non-abstract methods. Interfaces in Java can only have static and final variables, whereas abstract classes can have both non-static and non-final variables. Interfaces enable Java developers to achieve multiple inheritance which is not possible through the conventional way in Java. Abstract classes are not used to achieve inheritance. By default, all the variables that are data members of an interface are of public visibility, whereas abstract classes can declare them as protected or private. Implementation of a interface using an abstract class is easily possible but not vice-versa.

RELATED PROGRAMS