r/javahelp • • Sep 17 '26

Uninitialized variables are null or zero?

Inside public static void main(String[] args) and static void namehere() {}.

Int X;

would be "Uninitialized" and give errors when compiling.

Outside main and any other method, right after public class xxx.

public static int x;

holds no value whatsoever, yet the program doesn't complains about it when compiling, when printing it gives 0 as an int rather than null or NaN.


I am expecting:

Strings: "Null", Null or "".

Int: Null, None, NaN.

booleans give false by default.


What's different in this language?


Edit:

public static int X;

public static boolean Check;



static void Method A() {

X = 1

}



static void Method B() {
    
    boolean ThisLoop = true;
    
    String AverageText = "Average";
    
    int Number;
    
    if (Check == false) {
    
       Number = X;
      
    }

    int Average;
    
    while (ThisLoop == true) {

             try {
                
             Average = Integer.parseInt(JOptionPane.showInputDialog("Input " + AverageText + 

             Integer.toString(Number)));
             
             if (Average >= 0 || Average <= 0) { 
                 
             Number = Number++;
             
             InputNumber = Average;
                 
             ThisLoop = false;
             
             }
                
             }
             
            catch (NumberFormatException e) {
        
            JOptionPane.showMessageDialog(null, "Not a number", "Alert: Stupidity detected", 

            JOptionPane.ERROR_MESSAGE);
        
            ThisLoop = true;
            
           
            }
             
}                            

}

According to Java, we already know booleans with no value are by default false.

I am initializing Number before the If.

Check is public and also is false.

It goes into the If and sets Number to X (Which is public)

Initializes Average.

Sets Average to [Option dialog] "Input" + AverageText + Converts Number into a String.

Java is telling me that Number is not initialize inside the Integer.toString()

If Average is 1000 to 0 or to -1000 then it sums Number + 1.

Java isn't telling me Number = Number++; are not initialized.

7 Upvotes

16 comments sorted by

View all comments

1

u/HyperspaceFrontier Sep 18 '26

- `Int` is an object, can be null and is null when uninitialized.

- `int` is a primitive value that occupies 4 bytes of memory and is always initialized to `0` if not assigned; it cannot be null.

The difference between capital `I` and lowercase `i` is at the start, and it works the same exact way for byte, short, long, char and boolean. This is a very fundamental Java concept.