Static variable type in java

Java – static variable with example

A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that only a single copy of static variable is created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded in the memory.
Like variables we can have static block, static method and static class, to read about them refer: static keyword in java.

Static variable Syntax

static keyword followed by data type, followed by variable name.

static data_type variable_name;

As I mentioned above that the static variables are shared among all the instances of the class, they are useful when we need to do memory management. In some cases we want to have a common value for all the instances like global variable then it is much better to declare them static as this can save memory (because only single copy is created for static variables).

lets understand this with an example:

Static variable example in Java

class VariableDemo < static int count=0; public void increment() < count++; >public static void main(String args[]) < VariableDemo obj1=new VariableDemo(); VariableDemo obj2=new VariableDemo(); obj1.increment(); obj2.increment(); System.out.println("Obj1: count is="+obj1.count); System.out.println("Obj2: count is Age is: "+age); System.out.println("Name is: "+name); >// This is also a static method public static void main(String args[]) < age = 30; name = "Steve"; disp(); >>

Static variable initialization

  1. Static variables are initialized when class is loaded.
  2. Static variables are initialized before any object of that class is created.
  3. Static variables are initialized before any static method of the class executes.

Default values for static and non-static variables are same.
primitive integers( long , short etc): 0
primitive floating points( float , double ): 0.0
boolean: false
object references: null

Static final variables

The static final variables are constants. Lets have a look at the code below:

Читайте также:  Тест SpeechKit Cloud API от компании Yandex.

Note: Constant variable name should be in Caps! you can use underscore(_) between.
1) The above code will execute as soon as the class MyClass is loaded, before static method is called and even before any static variable can be accessed.
2) The variable MY_VAR is public which means any class can use it. It is a static variable so you won’t need any object of class in order to access it. It’s final so the value of this variable can never be changed in the current or in any class.

Key points:
final variable always needs initialization, if you don’t initialize it would throw a compilation error. have a look at below example-

Error: variable MY_VAR might not have been initialized

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Static Variables in Java – Why and How to Use Static Methods

Edeh Israel Chidera

Edeh Israel Chidera

Static Variables in Java – Why and How to Use Static Methods

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.

Читайте также:  Static int java error

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.

Читайте также:  Html css блок слева

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.

Источник

Оцените статью