- Understanding Class Members
- Class Variables
- Class Methods
- Constants
- The Bicycle Class
- Static Variable in Java: What is Static Block & Method [Example]
- What is Static Variable in Java?
- What is Static Method in Java?
- Example: How to call static variables & methods
- What is Static Block in Java?
- Example: How to access static block
- Static Variables in Java – Why and How to Use Static Methods
- The Static Keyword in Java
- Conclusion
Understanding Class Members
In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.
Class Variables
When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Bicycle class, the instance variables are cadence , gear , and speed . Each Bicycle object has its own values for these variables, stored in different memory locations.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles , as follows:
Class variables are referenced by the class name itself, as in
This makes it clear that they are class variables.
You can use the Bicycle constructor to set the id instance variable and increment the numberOfBicycles class variable:
public class Bicycle < private int cadence; private int gear; private int speed; private int id; private static int numberOfBicycles = 0; public Bicycle(int startCadence, int startSpeed, int startGear)< gear = startGear; cadence = startCadence; speed = startSpeed; // increment number of Bicycles // and assign ID number id = ++numberOfBicycles; > // new method to return the ID instance variable public int getID() < return id; >. >
Class Methods
The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
instanceName.methodName(args)
A common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:
public static int getNumberOfBicycles()
Not all combinations of instance and class variables and methods are allowed:
- Instance methods can access instance variables and instance methods directly.
- Instance methods can access class variables and class methods directly.
- Class methods can access class variables and class methods directly.
- Class methods cannot access instance variables or instance methods directlythey must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
Constants
The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI , whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).
Note: If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.
The Bicycle Class
After all the modifications made in this section, the Bicycle class is now:
public class Bicycle < private int cadence; private int gear; private int speed; private int id; private static int numberOfBicycles = 0; public Bicycle(int startCadence, int startSpeed, int startGear) < gear = startGear; cadence = startCadence; speed = startSpeed; >public int getID() < return id; >public static int getNumberOfBicycles() < return numberOfBicycles; >public int getCadence() < return cadence; >public void setCadence(int newValue) < cadence = newValue; >public int getGear() < return gear; >public void setGear(int newValue) < gear = newValue; >public int getSpeed() < return speed; >public void applyBrake(int decrement) < speed -= decrement; >public void speedUp(int increment) < speed += increment; >>
Static Variable in Java: What is Static Block & Method [Example]
Let’s look at static variables and static methods first.
What is Static Variable in Java?
Static variable in Java is variable which belongs to the class and initialized only once at the start of the execution. It is a variable which belongs to the class and not to object(instance ). Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
- A single copy to be shared by all instances of the class
- A static variable can be accessed directly by the class name and doesn’t need any object
What is Static Method in Java?
Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data. It is a method which belongs to the class and not to the object(instance). A static method can access only static data. It cannot access non-static data (instance variables).
- A static method can call only other static methods and can not call a non-static method from it.
- A static method can be accessed directly by the class name and doesn’t need any object
- A static method cannot refer to “this” or “super” keywords in anyway
Note: main method is static, since it must be accessible for an application to run, before any instantiation takes place.
Example: How to call static variables & methods
Step 1) Copy the following code into a editor
public class Demo < public static void main(String args[])< Student s1 = new Student(); s1.showData(); Student s2 = new Student(); s2.showData(); //Student.b++; //s1.showData(); >> class Student < int a; //initialized to zero static int b; //initialized to zero only when class is loaded not for each object created. Student()< //Constructor incrementing static variable b b++; >public void showData()< System.out.println("Value of a = "+a); System.out.println("Value of b text-align:center">
Following diagram shows, how reference variables & objects are created and static variables are accessed by the different instances.
Following diagram shows, how reference variables & objects are created and static variables are accessed by the different instances.
Step 4) It is possible to access a static variable from outside the class using the syntax ClassName.Variable_Name. Uncomment line # 7 & 8 . Save , Compile & Run . Observe the output.
Value of a = 0 Value of b = 1 Value of a = 0 Value of b = 2 Value of a = 0 Value of b = 3Step 5) Uncomment line 25,26 & 27 . Save , Compile & Run.
error: non-static variable a cannot be referenced from a static context a++;Step 6) Error = ? This is because it is not possible to access instance variable “a” from java static class method “increment“.
What is Static Block in Java?
The static block is a block of statement inside a Java class that will be executed when a class is first loaded into the JVM. A static block helps to initialize the static data members, just like constructors help to initialize instance members.
Following program is the example of java static block.
Example: How to access static block
Static Variables in Java – Why and How to Use Static Methods
Edeh Israel Chidera
Static variables and static methods are two important concepts in Java.
Whenever a variable is declared as static, this means there is only one copy of it for the entire class, rather than each instance having its own copy. A static method means it can be called without creating an instance of the class.
Static variables and methods in Java provide several advantages, including memory efficiency, global access, object independence, performance, and code organization.
In this article, you will learn how static variables work in Java, as well as why and how to use static methods.
The Static Keyword in Java
The static keyword is one of the most essential features in the Java programming language. We use it to define class-level variables and methods.
Here is an example of how to use the static keyword:
public class StaticKeywordExample < private static int count = 0; // static variable public static void printCount() < // static method System.out.println("Number of Example objects created so far: " + count); >>
As you can see above, we declared the count variable as a static variable, while we declared the printCount method as a static method.
When a variable is declared static in Java programming, it means that the variable belongs to the class itself rather than to any specific instance of the class. This means that there is only one copy of the variable in memory, regardless of how many instances of the class are created.
Here's an example. Say we have a Department class that has a static variable called numberOfWorker . We declare and increment the static variable at the constructor level to show the value of the static variable whenever the class object is created.
The results of the above code show that as we create new Department objects, the static variable numberOfWorker retains its value.
When we print out the value of numberOfWorker in the console, we can see that it retains its value across all instances of the Department class. This is because there is only one copy of the variable in memory, and any changes to the variable will be reflected across all instances of the class.
Department dpt1 = new Department("Admin"); System.out.println(Department.numberOfWorker); // output: 1 Department dpt2 = new Department ("Finance"); System.out.println(Department.numberOfWorker); // output: 2 Department dpt3 = new Department ("Software"); System.out.println(Department.numberOfWorker); // output: 3
We can also use the static keyword to define static methods.
Static methods are methods that belong to the class rather than to any specific instance of the class. Static methods can be called directly on the class itself without needing to create an instance of the class first. See the code below:
public class Calculation < public static int add(int a, int b) < return a + b; >public static int multiply(int a, int b) < return a * b; >>
In the above code, the Calculation class has two static methods. The declared static methods can be called directly on the Calculation class without creating an instance of the class first. That is to say, you do not need to create an object of the Calculation class before you access the static add and multiply classes.
int result = Calculation.add(5, 10); System.out.println(result); // Output: 15 int result2 = Calculation.multiply(5, 10); System.out.println(result2); // Output: 50
The main() method in Java is an example of a static method. The main() method is a special static method that is the entry point for Java applications. The Math class in Java also provides many static methods that perform mathematical operations.
public class Main < public static void main(String[] args) < System.out.println("Hello, World!"); >> int result = Math.max(5, 10); System.out.println(result); // Output: 10
The above code shows that the entry point for Java applications is a static method. It also shows that the max() method is a static method of the Math class and does not require an instance of the Math class to be created.
As you can see, static methods can be useful in providing utility functions that do not necessitate the creation of a class object.
Conclusion
The static keyword is a powerful tool in Java that can help solve many programming challenges. It aids in memory consumption management, improves code consistency, and helps speed up applications.
To prevent unforeseen issues from cropping up in the code, it is crucial to use the static keyword wisely and be aware of its limitations.
Code that relies heavily on static variables and methods can be harder to test because it introduces dependencies between different parts of the program. Static variables and methods can introduce hidden dependencies between different parts of the program, making it harder to reason about how changes in one part of the code might affect other parts.
Code that relies heavily on static variables can also be less flexible and harder to extend over time. Static variables can also lead to concurrency issues if multiple threads access and modify the same variable at the same time.
Lastly, if a static variable is not properly released or disposed of when it is no longer needed, it can lead to memory leaks and other performance issues over time.
By using static variables and methods appropriately, you can create efficient and maintainable code that will be easier to work with over time.