We may not have the course you’re looking for. If you enquire or give us a call on +852 2592 5349 and speak to our training experts, we may still be able to help with your training requirements.
Training Outcomes Within Your Budget!
We ensure quality, budget-alignment, and timely delivery by our expert instructors.
Java is one of the most popular programming languages worldwide because of its flexibility and ease of use. One of the key features that makes it versatile is the ability to use different keywords, including the Static Keyword in Java.
According to Statista, over 65% of programmers and coders use JavaScript worldwide because of its scalability and the possible benefits it can bring to an organisation. One of the key pillars of advanced coding is Static Keyword in Java, and hence understanding this is necessary for any aspirants interested in a future with Java.
Static Keyword in Java is a keyword used to share the same variable or method. Read ahead to learn how to use Static Keyword in Java, its working, methods, and examples!
Table of Contents
1) What is a Static Keyword in Java?
2) Applications of Static Keyword in Java with examples
3) Static Nested Classes in Java
4) The distinction between Static and Non-Static Keywords in Java
5) Conclusion
What is a Static Keyword in Java?
Static Keyword in Java creates variables or methods shared by the class rather than any specific class instance. If you declare a variable as “static”, it is shared by all instances of the class, meaning that any changes made to the variable by one instance will be visible to all other instances. Upon declaring a method as “static”, it can be called directly on the class itself rather than on a class instance.
Learn to build applications from scratch with our course on Java Programming!
Applications of Static Keyword in Java with examples
The Static Keyword in Java defines a variable, method, or block of code that belongs to a class rather than an instance of the same class. Here are some of the applications of the Static Keyword in Java:
1) Static variables
Static variables need to be declared by the "static" keyword and shared by all class instances. These variables can be accessed without creating an instance of the class. For example:
public class MyClass
{
static int count = 0;
public MyClass()
{
count++;
}
}
In the above example, the "count" variable is declared as Static, which means all instances of MyClass will share it. Each time an instance of MyClass is created, the constructor increments the count variable, which will be the same for all instances.
MyClass obj1 = new MyClass();
System.out.println(MyClass.count); // prints 1
MyClass obj2 = new MyClass();
System.out.println(MyClass.count); // prints 2
MyClass obj3 = new MyClass();
System.out.println(MyClass.count); // prints 3
As you can see, the value of count has incremented each time a new object of MyClass is created, and the value is visible to all instances of the class.
2) Static methods
Static methods need to be declared using the "static" keyword and can be called without creating an instance of that class. They are typically used for utility methods that do not require any state from the instance. For example:
public class MathUtils
{
public static int add(int a, int b)
{
return a + b;
}
}
In the above example, the "add" method is declared as Static, which means it can be called without creating an instance of the MathUtils class. The method simply takes two integer arguments and returns their sum.
int sum = MathUtils.add(3, 5);
System.out.println(sum); // prints 8
As you can see, the add method can be called directly on the MathUtils class without creating an instance of the class.
3) Static blocks
Static blocks are used to initialise Static variables and are executed only once when the class is loaded into memory. For example:
public class MyClass
{
static int count;
static
{
count = 0;
}
}
In the above example, the Static block initialises the "count" variable to zero when the class is loaded into memory. This is useful for initialising Static variables that require complex calculations or external resources.
4) Singleton pattern
Singleton pattern is a design pattern that ensures that there is only one instance of the class and serves as a global point of access to that class instance. Shown below is an example of a Singleton class:
public class Singleton
{
private static Singleton instance = null;
private Singleton()
{}
public static Singleton getInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
In this example, the Singleton class has a private constructor, meaning it cannot be instantiated directly from outside the class. Instead, the class provides a static method called getInstance, which returns the single instance of the class. The getInstance method first checks if the instance variable is null, and creates a new instance if necessary.
Some key points to note about Static Keyword in Java are as follows:
1) Static variables are initialised only once at the start of the program execution. They are initialised before any object of the class is created, and they remain in memory throughout the program's lifetime.
2) Static methods have the ability to be called on the class itself rather than on an instance of the class. For example, if you have a class called MyClass with a Static method called myMethod, you can call the method like this: MyClass.myMethod()
3) Static methods can only access the class's other Static members (variables or methods). They cannot access non-static members, because non-static members belong to specific instances of the class.
Boost your knowledge of Java by learning more about Static Keywords. Sign up for the Java Programming course now!
Static Nested classes in Java
In Java, a Static Nested class is a class that is defined inside another class and has the "static" modifier. When a nested class is declared Static, it can be accessed without needing to create an instance of its enclosing class. A Nested class can also access private members of its enclosing class.
A Static Nested class can be useful for organising related classes together, and can also be used to create helper classes that are only used by the enclosing class.
Here’s an example of Static Nested class in Java:
public class OuterClass
{
private static int outerStaticVariable = 10;
private int outerInstanceVariable = 20;
static class NestedStaticClass
{
public void printVariables()
{
System.out.println("Outer static variable: " + outerStaticVariable);
// Cannot access outerInstanceVariable since it is not static
}
}
public static void main(String[] args)
{
OuterClass.NestedStaticClass nestedStaticObj = new OuterClass.NestedStaticClass();
nestedStaticObj.printVariables(); // Output: Outer static variable: 10
}
}
In this example, we have an outer class OuterClass with a Static Nested class NestedStaticClass. The Nested class has a method printVariables() that can access the Static variable outerStaticVariable of the enclosing class, but cannot access the non-Static instance variable outerInstanceVariable.
In the main method of OuterClass, we create an instance of NestedStaticClass and call its printVariables() method to print the value of outerStaticVariable.
The distinction between Static and Non-Static Keywords in Java
Let’s discuss the differences between Non-Static and Static Keywords in Java. This can primarily be divided into two heads: variables and methods.
The difference between Static and Non-Static variables are:
Basis of difference |
Static variables |
Non-Static variables |
Accessibility |
Static variables can be accessed using class names. |
Non-Static variables can be accessed only using objects. |
Methods of accessibility |
Static variables can be accessed using both Static and Non-Static methods. |
Non-Static variables can be accessed only using Non-Static methods. |
Allocation of memory |
Static variables can be allocated memory only while loading the class. |
Non-Static variables have one memory allocated per object. |
Sharing |
All instances or objects of the class share static variables. |
Each object has a copy of the Non-Static variables. |
Scope |
There is global scope for Static variables. |
Non-Static variables have local scope. |
The difference between Static and Non-Static methods are:
Basis of difference |
Static methods |
Non-Static methods |
||
Support |
Static methods support compile-time or early binding. |
Non-Static methods support dynamic, run-time or late binding. |
||
Accessibility |
Static methods can only access Static variables of their own class or Static variables of other classes. |
Non-Static methods can access both Non-Static and Static members. |
||
Ability to be overridden |
Static methods cannot be overridden. |
Non-Static methods can be overridden. |
||
Allocation of memory |
Static methods need much less memory consumption as they are allocated only when the class is being loaded. |
Non-Static methods require relatively more memory allocation as memory is allocated for each object. |
Conclusion
Wrapping up, you have been walked through an extensive introduction to the concept of Static Keyword in Java and the applications of Static Keyword in Java. You also explored the primary distinctions between Static and Non-Static methods and variables in Java.
Understanding this concept is fundamental to any aspirant looking to build a career in Java coding and JavaScript. We hope this blog has helped you get hands-on education with Static Keywords and start with the advanced Java concepts.
Sign up for Objected-Oriented Fundamentals Training in Virtual to build your fundamentals on programming languages now!
Frequently Asked Questions
We use Static Keyword in main method in Java because it allows JVM to call it without creating an object of the class. This saves memory and simplifies the execution process. Static methods are also class-related, which means they can access other static members of the class.
The String args[] parameter in the main method is used to pass command-line arguments to the program. It is compulsory because the Java runtime system looks for this signature to start the execution. The arguments are stored as an array of String objects, which can be converted to other types if needed.
The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.
Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.
The Knowledge Academy offers various Java Courses, including Java Programming, Hibernate Training and Introduction to Java EE Course. These courses cater to different skill levels, providing comprehensive insights into Latest Java Technologies Trends.
Our Programming and DevOps blogs cover a range of topics related to Java Programming, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Java Programming skills, The Knowledge Academy's diverse courses and informative blogs have you covered.
Upcoming Programming & DevOps Resources Batches & Dates
Date
Mon 6th Jan 2025
Mon 17th Mar 2025
Mon 12th May 2025
Mon 7th Jul 2025
Mon 15th Sep 2025
Mon 3rd Nov 2025
Mon 15th Dec 2025