Calculus5000
Calculus5000

Reputation: 427

How to create uninitialised static final variables in Java

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();
    }
}

Upvotes: 5

Views: 724

Answers (4)

Mordechai
Mordechai

Reputation: 16234

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;  
}

Upvotes: 2

KDP
KDP

Reputation: 1481

You can do this but you need to exit the static block by throwing an exception

  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();
     throw new RuntimeException("Could not init class.", e);    
 }

}

Upvotes: 0

Ashycre
Ashycre

Reputation: 57

You can't. final variables can only be assigned values during initialization, hence why you're receiving compiler error (the variables will stay null). It's used to ensure consistency.

You can either drop the final keyword or make HEIGHT and WIDTH local variables.

currentImage = new Image("res/images/asteroid_blue.png");
final int width= currentImage.getWidth();
final int height = currentImage.getHeight();

Upvotes: -2

swinkler
swinkler

Reputation: 1701

  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.

Upvotes: 3

Related Questions