質問

Though this has been discussed in detail in various forums including SO and I have read most of the replies of the experts, But below is the problem is confusing me.

I have few integer variables and my requirement is to check null before executing few statements. So first I have declared as int (I don't have knowledge on int and Integer).

int a,b,c;
if(a == null) {
    //code here
}

But complier is not allowing me to declare like this.

After searching in google, experts advised me to use Integer instead of int and when I changed like the code below

Integer a,b,c;
if(a == null) {
   //code here
}

This is fine with the compiler as Integer is defined as Object in java and int is not.

Now my code has become some declarations with int and some with Integer.

Can anyone suggest if declaring Integer will give the same result as int also can I change all my declarations to Integer.

Thanks for your time.

役に立ちましたか?

解決

int a,b,c;
if (a == null) {
    //code here
}

This code doesn't make sense, because primitive int types cannot be null. Even if you considered auto-boxing, int a is guaranteed to have a value before being boxed.

Integer a,b,c;
if (a == null) {
   //code here
}

This code makes sense, because Object Integer types can be null (no value).

As far as the functionality, the Object vs built-in types actually do make a bit of a difference (due to their different natures).

Integer a,b,c;
if (a == b) {
  // a and b refer to the same instance.
  // for small integers where a and b are constructed with the same values,
  // the JVM uses a factory and this will mostly work
  //
  // for large integers where a and b are constructed with the same values,
  // you could get a == b to fail
}

while

int a,b,c;
if (a == b) {
  // for all integers were a and b contain the same value,
  // this will always work
}

他のヒント

int is the primitive type, and is not a nullable value (it can't ever be null). Integer is a class object, which can be null if it has not yet been instantiated. Using an Integer vs. an int won't really affect anything in terms of functionality, and your code would behave the same if you changed "int" to "Integer" everywhere.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top