Different Cases When Integer and int can be used interchangeably
suggest changeCase 1: While using in the place of method arguments.
If a method parameter is a wrapper type, a primitive of that type can be passed and is boxed. If the parameter is primitive, a wrapper can be passed and is unboxed. Unboxing null throws NullPointerException.
Example:
int i;
Integer j;
void ex_method(Integer i)//Is a valid statement
void ex_method1(int j)//Is a valid statement
Case 2: While passing return values:
A method declared to return a primitive may return a wrapper, which is unboxed. A method declared to return a wrapper may return a primitive, which is boxed.
Example:
int i;
Integer j;
int ex_method()
{...
return j;}//Is a valid statement
Integer ex_method1()
{...
return i;//Is a valid statement
}
Case 3: While performing operations.
Whenever performing operations on numbers the primitive type variable and object of respective wrapper class can be used interchangeably.
int i=5;
Integer j=new Integer(7);
int k=i+j;//Is a valid statement
Integer m=i+j;//Is also a valid statement
Pitfall: Unboxing a null wrapper throws NullPointerException. A field of wrapper type starts as null.
public class Test {
Integer i;
int j;
public void met() {
j = i; // NullPointerException: i is null
System.out.println(j);
System.out.println(i);
}
public static void main(String[] args) {
Test t = new Test();
t.met();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents