When working with classes in Java, you usually need to instantiate the class before you can access its members. However, you may come across a situation where you want to define a member of a class without instantiating a class.
is where the Java static keyword comes in. The Java static keyword is used to define the member class that you can access without creating an instance of a class.
This tutorial will discuss, with examples, the basics of the Java static keyword and how to use it in your Java programs.
Java classes
In Java, classes are projects for an object. For example, a class called OrderCoffee could include all functions related to ordering a coffee, such as placing an order, modifying an existing order, and adding new items to an order.
We can then create objects which are instances of this class. For example, an object called CoffeeOrder12 could use the CoffeeOrder class project to store data for a single coffee order. The CoffeeOrder12 object would have access to all functions and methods declared in the CoffeeOrder class. See image 1 for a visual representation of these ideas.
image 1: Classes, instances and functions.
Now that we have discussed the basics of Java classes, we will move on to exploring the Java static keyword.
Static Java Methods
I Static methods, also called class methods, are methods that belong to a class, not its instances. . Since static methods belong to a class, you can only call the method of the class itself and not from an object of the class
Here is the syntax for calling a static method:
Let’s look at an example to see how it works
Suppose you create a program that handles orders for a cafe. We want create a class called CoffeeOrder which stores all the functions for ordering a coffee.
We decide that we want to be able to print new order notifications on the barista console. We want this new notification in order to be static because it does not depend on any other code in the subject of the coffee order. We can use the following code to do this:
Our code returns:
break down our code step by step. First, we declare a class called CoffeeOrder. CoffeeOrder contains two methods:. CreateOrder () and orderImpr ()
CreateOrder () is an ordinary process that creates an order and returns a number control. orderImpr () is a static method that prints a message to the console to notify the barista that a new order has been placed
in our main program, we create a CoffeeOrder object called order92. This data stores the objects for order # 92. Then we use the CreateOrder () to get an order number and print that order number, preceded by order number:, on the console.
When we invoke < method code > CreateOrder (), we use order92.createOrder (). This is because CreateOrder () is not a static method, so we can access it while manipulating our object.
At the end of our main code, we use CoffeeOrder .printOrder () to print a message indicating that the order # [order number] has been placed on the console . In this message, order number is equal to the number associated with a specific order. Since PrintOrder () is a static method, we need to use CoffeeOrder (our class) to accept it.
If we tried using order92.printOrder () (which invokes an instance of our class), like we did when we used CreateOrder () , ours might give us a warning.
Java Static Variables
The static keyword in Java can also be used to create static instance variables. Static variables belong to a class and are initialized only once, at the start of a program execution.
Static variables do not belong to an object. This means that to access it, you must refer to the relevant category. Here is the syntax for declaring a static variable in Java:
In this example, we have declared a static variable called COFFEE_NAME, which we have assigned the value of express string.
Let’s take an example to show a static Java variable. Use
Suppose we create a program that processes orders for a coffee, this program should store the number of baristas in service and when an order is created , the program should associate this order with the name of the barista who will prepare this order.
We could use this code to create our own coffee processing program:.
Our code returns:
In our code we declare the following two variables:
baristasOnDuty. This is a standard variable, which means it is accessible all along our class. Name
. This is a static variable, which means we need to refer to the object it is associated with to retrieve its value.
In our main program, we create an instance of the CoffeeOrder class and we call it sorts111. Next, we print the message baristas in service: followed by the content of the baristasOnDuty variable. Since it’s a standard variable, we don’t need to refer to its class name
On the next line of our code, we print the assigned Barista message:. At the console, followed by the name of the barista to whom the order is assigned. However, the barista’s name is stored as a static variable.
This means that, to retrieve the name of the barista, you have to refer to the name of the object that is associated with the variable. In this case, we are using order111.name to retrieve the bartender’s name. Indeed, the variable name is static and therefore cannot be accessed by reference to the object order111
Java static block
The Java static keyword can also be used to create a static block. . If a class has multiple static variables that need to be initialized individually, you must use a static block
static blocks are executed once - when the class is first loaded into the memory of the computer. Here is the syntax of a static block of Java code:
Let’s take an example to demonstrate how a static block works Suppose we ask to print the message a new upcoming order ... on the console before the assignees of the program, it for a bartender if the bartenders know they are getting ready. We could do this by creating a static class. The static class will run the first time the program is run
Here is an example of a static class that prints the above message , then assigns an order to a barista.
Our code returns:
In our code, we first initialized baristasOnDuty and variable names . Then, the program prints the message A new order is coming ... to the console. This message was stored inside our static code block. Once the program ran the contents of the static block, it ran our main program, which returned the same result as the main program in our last example.
Conclusion
The static Java keyword has a number of uses. You can use the static keyword to create static methods, static variables, and static code blocks.
This tutorial has shown, with examples, the basics of the static keyword and how you can use the static keyword with methods, variables, and code blocks. After reading this tutorial, you are ready to start using Java Static Keywording like a pro.
Thanks for explaining! I was stuck with Javascript Static Variable for some hours, finally got it done 🤗. Will get back tomorrow with feedback
Walter Innsbruck
Prague | 2023-04-01
Simply put and clear. Thank you for sharing. Javascript Static Variable and other issues with PS PHP module was always my weak point 😁. Will get back tomorrow with feedback
Carlo Richtgofen
Massachussetts | 2023-04-01
Maybe there are another answers? What Javascript Static Variable exactly means?. Will get back tomorrow with feedback
Shop
Learn programming in R: courses
$FREE
Best Python online courses for 2022
$FREE
Best laptop for Fortnite
$399+
Best laptop for Excel
$
Best laptop for Solidworks
$399+
Best laptop for Roblox
$399+
Best computer for crypto mining
$499+
Best laptop for Sims 4
$
Latest questions
PythonStackOverflow
Common xlabel/ylabel for matplotlib subplots
1947 answers
PythonStackOverflow
Check if one list is a subset of another in Python
1173 answers
PythonStackOverflow
How to specify multiple return types using type-hints
1002 answers
PythonStackOverflow
Printing words vertically in Python
909 answers
PythonStackOverflow
Python Extract words from a given string
798 answers
PythonStackOverflow
Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?