简体   繁体   中英

Static variable in Java not initializing

So I am having trouble with the following code.

public class bw {
    public static int checked[][];
    public static BufferedImage input;

    public static void floodfill(int j, int i, int color, int spotColor, int th) throws Exception {
       input.setRGB(j, i, color);
    }

    public static void main(String args[]) throws Exception {
        BufferedImage input = ImageIO.read(new File("C:\\Users\\Aditya\\Desktop\\Lena.png"));       
        checked = new int[input.getHeight()][input.getWidth()];
        floodfill(250, 310, 0, input.getRGB(250,310), 35);
    }
}

Have taken out most of the irrelevant part from the code. The checked variable which is static is working fine. But the input variable which I have intialized in the main function is still null. It gived me null pointer exception from floodfill.

You have a local variable with the same name, inside main method as a local variable and as a static attribute . Therefore your static attribute is not get initialized instead of the local variable getting initialized

Try this

public class bw{
    public static int checked[][];
    public static BufferedImage input;

    public static void floodfill(int j, int i, int color, int spotColor, int th) throws Exception{
        input.setRGB(j, i, color);

    }
    public static void main(String args[]) throws Exception{
        input = ImageIO.read(new File("C:\\Users\\Aditya\\Desktop\\Lena.png"));       
        checked = new int[input.getHeight()][input.getWidth()];
        floodfill(250, 310, 0, input.getRGB(250,310), 35);

    }
}

You have declared variable input twice, so the input variable inside main method is initialized and the other(the static attribute) is not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM