In PHP, there is a isset
function. What about Java? I think I can use == null
with objects, but what about value types like int
To check if a variable is set in Bash Scripting, use-v var or-z ${var} as an expression with if command. This checking of whether a variable is already set or not, is helpful when you have multiple script files, and the functionality of a script file depends on the variables set in the previously run scripts, etc.
To confirm whether a variable is set or not in Bash Scripting, we can use -v var or -z ${var} options as an expression with the combination of 'if' conditional command.
Java's compiler won't let you define variables and use them before they were assigned a value, so the problem doesn't exist in the same form as it exists in php.
If in your case the compiler didn't stop you already (because this is eg an instance variable) the best solution is probably to initialize the variable to some "special" value as suggested by Guest11239193. Like this:
int x = 0; // because by convention 0 is a reasonable default here
Of course, what a "safe, reasonable" initialization value is depends on the application.
Afterwards, you could
if (x == 0) { // only allow setting if x has its initial value x = somenewvalue; }
Or you could access x via a setter that inhibits changing more than once (probably overkill for most cases):
private int x; private boolean x_was_touched = false; public void setX (int newXvalue) { if (!x_was_touched) { x = newXvalue; x_was_touched = true; } } public int getX() { return x; }
You could also use an Integer
, int's object brother, which could be initialized to null
Integer x = null;
However, the fact that you think you need that knowledge may hide a deeper logic flaw in your program, so I'd suggest you explore the reason why you want to know if a primitive value (primitive as opposed to objects, int
vs Integer
) wasn't touched.
A non-existing variable doesn't exist in Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With