Question

How do I test for an uninitialized byte in Java?

This doesn't work:

byte b;

if (b != null) {
   // Do something
}
Was it helpful?

Solution

There is no such thing as an "uninitialized byte", as the compiler will not allow you to write code that uses an uninitialized value (note: fields that are not explicitly assigned a value are automatically initialized to 0/false/null).

You have a few options.

You could use a wrapper type, which can be null, e.g.:

Byte b = null;

if (b != null) {
    ...
}

You could use a special value, but you have to be sure it does not overlap with meaningful values:

byte b = -1;

if (b != -1) {
    ...
}

You could do a variant of the above, but with a larger type (this is how, e.g., InputStream.read() indicates EOF), so that the "magic" value can't be in the valid range:

int b = -1;

if (b != -1) {
    // then b is in [0, 255] (unsigned byte in this example)
    ...
}

You could store a second flag indicating initialization state:

boolean bInitialized = false; 
byte b = 0; // arbitrary

if (bInitialized) {
    ... 
}

You could also rework your application logic to avoid having to do this test in the first place which, to be honest, is the solution I recommend if possible.

OTHER TIPS

The Java Language specification says the following about the initial value of variables

Every variable in a program must have a value before its value is used:

[...]

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16).

Therefore you cannot use the value of a variable until such a value is given to it.

Also, in your example, b could never be null since it is of a primitive type and that snippet would not compile for that reason as well.

As suggested in the comments, you could use a reference type and set it to null to indicate a special case.

The initialization state of local variables is known at compile time. As far as I'm aware, there's no language feature to query that state.* Furthermore, since the compiler won't allow you to read a local variable until it has been initialized, you won't have any luck doing it at runtime either.

*I guess you could kind of query it by trying to read from it and seeing if the compiler allows it. lol

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top