开发者

How to test if a variable is set?

开发者 https://www.devze.com 2023-04-12 06:41 出处:网络
In PHP, there is a isset fun开发者_如何学JAVAction. What about Java? I think I can use == null with objects, but what about value types like intJava\'s compiler won\'t let you define variables and use

In PHP, there is a isset fun开发者_如何学JAVAction. What about Java? I think I can use == null with objects, but what about value types like int


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.

EDIT

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.


In Java it is a compiler error to use a variable without being set.

Class and instance variables are initialized with what is considered a default "null" value, depending on the data type.

So a isset like function does not make sense.


You can't check if the variable is set. You can:

  1. Initialize the variable that makes sense as an initial value -- such 0 for a counter, the maximal integer value if you're calculating a minimum, etc.
  2. Initialize the variable to a value that you aren't going to use, for example -1 if you're going to use unsigned integer values and an empty string for a string.
  3. Introduce a boolean flag that indicates whether you have started doing something.


Default for int will be 0 and for string will be "".


You could try to use an Object instead of a primitive value, i.e.


Integer x = null;
...
public Integer getX(){
   if(x == null) {
      x = new Integer(10);
   }
   return x;
}


Create your functions for that control because each object has own rules about "isset() result" ;

Examples :

    public static final boolean isEmpty(String x) {
        return (x == null || x.trim().equals(""));
    }
    public static final boolean isEmpty(Integer x) {
        return (x == null || x == 0);
    }
    public static final boolean isEmpty(Long x) {
        return (x == null || x == 0);
    }
    public static final boolean isEmpty(Collection<?> x) {
        return (x == null || x.size() == 0);
    }
    public static final boolean isEmpty(Map<?,?> x) {
        return (x == null || x.size() == 0);
    }
    public static final boolean isEmpty(Object[] x) {
        return (x == null || x.length == 0);
    }


The most common use case of wanting to have an undefined value is when retrieving information from a data source. In any given SQL query, you are likely to have records that have integers whose values is 0, but which can also be empty/null fields. The same goes for strings, where an empty string '' is not the same as an undefined or null string.

It appears that using the object reference versions of native types is the only solution here, which is unfortunate since it's messy. The alternative would be to store a boolean for every single data field that has to be checked and maintained by hand, which is even worse.


The integer variable declared in java ,cannot undergo the condition for "undefined" or "null".But by the use of the wrapper class we can make use of it i.e: Integer a = null;

public class Solution {
    public static void main(String[] args) {
        Integer max = null; //works perfectly
        int max1 == null; //throws and incompatible error 
        if (max == null)
            System.out.println("null");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号