Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create uninitialised static final variables in Java

Tags:

java

variables

The code below produces the compiler error Variable HEIGHT might not have been initialized (same goes for WIDTH).

How can I declare an uninitialized static final variable like what I'm trying to do below?

public static final int HEIGHT, WIDTH;
static{
    try {
        currentImage = new Image("res/images/asteroid_blue.png");
        WIDTH = currentImage.getWidth();
        HEIGHT = currentImage.getHeight();
    }catch (SlickException e){
        e.printStackTrace();
    }
}
like image 468
Calculus5000 Avatar asked Oct 19 '22 08:10

Calculus5000


2 Answers

  static {
    Image currentImage = null;
    try {
      currentImage = new Image("res/images/asteroid_blue.png");
    } catch (Exception e) {
      // catch exception - do other stuff
    } finally {
      if (currentImage != null) {
        WIDTH = currentImage.getWidth();
        HEIGHT = currentImage.getHeight();
      } else {
        // initialise default values
        WIDTH = 0;
        HEIGHT = 0;
      }
    }
  }

Whatever happens (try/catch), you have to assign values to the static variables - therefor, finally should be used.

like image 88
swinkler Avatar answered Oct 21 '22 23:10

swinkler


The right way would be to set the values to null (in case its an object), but since it's final you'll have to do this roundabout:

public static final int HEIGHT, WIDTH;
static{
    int w = 0, h = 0;
    try {
        currentImage = new Image("res/images/asteroid_blue.png");
        w = currentImage.getWidth();
        h = currentImage.getHeight();
    }catch (SlickException e){
        e.printStackTrace();
    }

    WIDTH = w;
    HEIGHT = h;  
}
like image 28
Mordechai Avatar answered Oct 22 '22 00:10

Mordechai