Menu
Topics Index
...
`


final, static and others >
Siva Nookala - 03 Mar 2017
Apart from the use mentioned in Static Keyword In Java, there are other uses of static keyword. They are creating the constants, initializing them using static block and creating static methods.

Constants: The static variables of any class can be marked as final, so that they become constant or unmodifiable. Declaring the constants as public static final is a very common practice.
public static final double PI = 3.14;
public static final int NUMBER_OF_BALLS_IN_A_OVER = 6;
It is also a good coding practice, to declare the variables in the CAPITAL LETTERS instead of small letters, so that we can easily differentiate between a constant and a normal variable.

Static Blocks: We can use static blocks inside a class to initialize static variables or do any one time activities, we want to perform before the class is used.
class Temperature
{
    public static final double FEET_TO_METER_CONVERSION = 0.3048;
    public static final double METER_TO_FEET_CONVERSION;
    
    static
    {
        METER_TO_FEET_CONVERSION = 1 / FEET_TO_METER_CONVERSION;
        // Do other one time activities, like loading data from file, creating database connection pool etc.
    }

    static
    {
        // Do some more activities
    }
}
As shown above, we can have as many static blocks as needed and they will be called in the same order as they appear in the file. Also note that they will be called only once, no matter how many objects are created or how many times the class is accessed.

Static Methods: In any class, we can also define static methods. Similar to static variables, we can access static methods, using the class name and do not need any object for calling them. Usually we group utilities which are used across the application and create static methods for them. When we create static methods as shown below, we need not create unnecessary new objects, every time we want to make a conversion.
class ConversionUtils
{
    public static double convertToFeet(double meters)
    {
        ...
    }

    public static double convertToMeters(double feet)
    {
        ...
    }

    public static double convertToFahrenheit(double celsius)
    {
        ...
    }

    public static double convertToCelsius(double fahrenheit)
    {
        ...
    }
}
....
double meters = ConversionUtils.convertToMeters(300.25);
double fahrenheit = ConversionUtils.convertToFahrenheit(37.67);
Checkout the topic Static and Non Static Variables - Static and Non Static Methods to know more details about the static methods, non-static methods, static variables and non-static variables.

Dependent Topics : final Keyword In Java 

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App