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.