Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking a method on a static object in Java evaluates some incorrect value

Tags:

java

The following simple program retrieves the current year (2011) from the system and then simply subtracts 1950 from the current year.

package calculation;

import java.util.Calendar;

final public class Main
{
    private static final Main INSTANCE = new Main();
    private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR);
    private final int beltSize=CURRENT_YEAR - 1950;

    private int beltSize()
    {
        return beltSize;
    }
    public static void main(String[] args)
    {
        Main  main=new Main();
        System.out.println("Wears a size " + main.beltSize() + " belt.");
        System.out.println("Wears a size " + INSTANCE.beltSize() + " belt.");
    }
}

The following statement from the code above returns a correct value.

Main  main=new Main();

System.out.println("Wears a size " + main.beltSize() + " belt.");

It invokes the beltSize() method which returns correctly the evaluation of CURRENT_YEAR - 1950 which is 61.


private static final Main INSTANCE = new Main();

System.out.println("Wears a size " + INSTANCE.beltSize() + " belt.");

The above statement invokes the same method beltSize() using the static final object INSTANCE which is a class member and it returns incorrectly -1950 (negative) rather than the correct value of 61. Why?

like image 807
Lion Avatar asked Feb 05 '26 07:02

Lion


1 Answers

Order of evaluation matters for static variables. so change the order as

private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR);
private static final Main INSTANCE = new Main();   // order of evaluation matters for static variables

Since INSTANCE has evaluated before CURRENT_YEAR, the default value of CURRENT_YEAR (0) has taken.

like image 95
Prince John Wesley Avatar answered Feb 07 '26 21:02

Prince John Wesley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!