Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and where to use Static modifier in Java?

Tags:

java

static

How and where should we use a Static modifier for:

1. Field and
2. Method?

For example in java.lang.Math class, the fields methods like abs(), atan(), cos() etc are static, i.e. they can be accessed as: Math.abs()

But why is it a good practice?

Say, I don't keep it static and create an object of the class and access it, which anyways I can, I will just get a warning that, you are trying to access a static method in a non static way (as pointed out by @duffymo, not in case of Math class).

UPDATE 1:

So, utility method, should be static, i.e. whose work is only dependent on the method parameters. So, for example, can the method updateString(String inputQuery, String highlightDoc) should have been a static method in this question?

like image 665
zengr Avatar asked Oct 18 '10 22:10

zengr


People also ask

When should we use static modifier?

You can add the static modifier to a local function. A static local function can't capture local variables or instance state. Beginning with C# 9.0, you can add the static modifier to a lambda expression or anonymous method. A static lambda or anonymous method can't capture local variables or instance state.

Why do we use static modifier in Java?

The static keyword in Java is a non-access modifier. The static modifier makes a member (variables or methods) of a class independent of the objects of the class and is used when we are defining properties that are common to all objects in the class.

Where do we use static in Java?

In Java, static keyword is mainly used for memory management. It can be used with variables, methods, blocks and nested classes. It is a keyword which is used to share the same variable or method of a given class. Basically, static is used for a constant variable or a method that is same for every instance of a class.

Where can static be used?

The most important reason why static keywords are heavily used in Java is to efficiently manage memory. Generally, if you want to access variables or methods inside a class, you first need to create an instance or object of that class.


2 Answers

You can think of a 'static' method or field as if it were declared outside the class definition. In other words

  1. There is only one 'copy' of a static field/method.
  2. Static fields/methods cannot access non-static fields/methods.

There are several instances where you would want to make something static.

The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.

Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.

In C#, you can also have static classes which, as you might guess, contain only static members:

public static class MyContainer
{
    private static int _myStatic;

    public static void PrintMe(string someString)
    {
        Console.Out.WriteLine(someString);
        _myStatic++;
    }

    public static int PrintedInstances()
    {
        return _myStatic;
    }
}
like image 104
Alex Avatar answered Oct 11 '22 10:10

Alex


Static uses less memory since it exists only once per Classloader.

To have methods static may save some time, beacuse you do not have to create an object first so you can call a function. You can/should use static methods when they stand pretty much on their own (ie. Math.abs(X) - there really is no object the function needs.) Basically its a convenience thing (at least as far as I see it - others might and will disagree :P)

Static fields should really be used with caution. There are quite a few patterns that need static fields... but the basics first:

a static field exists only once. So if you have a simple class (kinda pseudocode):

class Simple {
 static int a;
 int b;
}

and now you make objects with:

Simple myA = new Simple();
Simple myB = new Simple();
myA.a = 1;
myA.b = 2;
myB.a = 3;
myB.b = 4;
System.out.println(myA.a + myA.b + myB.a + myB.b);

you will get 3234 - because by setting myB.a you actually overwrite myA.a as well because a is static. It exists in one place in memory.

You normally want to avoid this because really weird things might happen. But if you google for example for Factory Pattern you will see that there are actually quite useful uses for this behaviour.

Hope that clears it up a little.

like image 27
Niko Avatar answered Oct 11 '22 09:10

Niko