Search code examples
javastaticsingletonfinal

Can I set a final variable in Java with a result of a divison?


I want to have a global-scale variable, so some graphical objects can always have the same size in relation to the window. My idea:

public static final double GLOBALSCALE = SCREENWIDTH / 1920;

But my variable is zero at that point. It happens in the datafield of a Singleton-Patterned-Class.. did I understand anything wrong?


Solution

  • You made a mistake by dividing an int to an int and expect a double as it's outcome. You need to devide by a double:

    public static final double GLOBALSCALE = SCREENWIDTH / 1920.0;
    

    Notice the difference, 1920.0 is a double while 1920 is an int. If one of the two is a double java will not do integer division but double instead.

    Or cast the division to a double like so:

    public static final double GLOBALSCALE = SCREENWIDTH / (double)1920;