How we must compare an int wrapper, Integer, to zero value? We can use Integer when the int value can be null (int does not allows null):
Integer x;
both options throw java.lang.NullPointerException:
0 == x; or x == 0;
So, simple, how we can compare Integers that can or not, be null?
x is a field in your class, so when you create it without making it to reference to any Integer object (Integer x = new Integer(7) for example), the compiler gives it a null for you (the default values for Object references). It seems like you have hence: Integer x = null;
So to compare it just use the equals() method that is implemented by Integer wrapper class.
new Integer(0).equals(x)
Related
This question already has answers here:
Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?
(8 answers)
Closed 7 years ago.
public class MainClass
{
public static void main(String[] args)
{
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2);
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i3 == i4);
}
}
i1,i2,i3,i4 are not objects I guess they are only reference variables. So how they work differently from class variables?
Answer I heard is
true
false
But how? Why is it different for 127 and 128?
Since Java 5, wrapper class caching was introduced. The following is an examination of the cache created by an inner class, IntegerCache, located in the Integer cache. For example, the following code will create a cache:
Integer myNumber = 10
or
Integer myNumber = Integer.valueOf(10);
256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array. This caching functionality can be seen by looking at the inner class, IntegerCache, which is found in Integer:
So when creating an object using Integer.valueOf or directly assigning a value to an Integer within the range of -128 to 127 the same object will be returned. Therefore, consider the following example:
Integer i = 100;
Integer p = 100;
if (i == p)
System.out.println("i and p are the same.");
if (i != p)
System.out.println("i and p are different.");
if(i.equals(p))
System.out.println("i and p contain the same value.");
The output is:
i and p are the same.
i and p contain the same value.
It is important to note that object i and p only equate to true because they are the same object, the comparison is not based on the value, it is based on object equality. If Integer i and p are outside the range of -128 or 127 the cache is not used, therefore new objects are created. When doing a comparison for value always use the “.equals” method. It is also important to note that instantiating an Integer does not create this caching.
Remember that “==” is always used for object equality, it has not been overloaded for comparing unboxed values
Also see Integer wrapper objects share the same instances only within the value 127?
Integer is an object and hence the == check if the variables refer to the exact same instance. Equality of objects can be checked using the myObject.equals(otherObject)
int is the primitive type of Integer and in that case the == would return true if both the ints have the same value
update: please note that in some case, as for String for example, two variables can share the same reference depending from the code and the compiler but still it is not something you should base your code logic on.
I have written following code
class Test {
public static void main(String... args) throws Exception{
Set<Integer> s = new HashSet();
Integer i1 = new Integer(1);
s.add(i1);
Integer i2 = new Integer(2);
s.add(i2);
i1 = 5;
s.remove(i1);
System.out.println("size= "+s.size());
}
}
Output: 2
I have added two integers(i1 and i2) in set and i1 is modified.
When s.remove(i1) is there, output is 2
when I comment out s.remove(i1) still output is 2.
Why this is so.How it is working in background.
Thnaks in advance!
Integer objects are immutable objects and hence any change to them will create a new object. So when you change
i1 = 5;
the original i1 which was stored in set is not changed. As i1 now holds the reference of a different object, which is not present in Set so calling
s.remove(i1);
will have no effect i.e. it does not remove anything and the size of the set remains 2. To confirm whether remove has removed anything or not, you can use boolean return value of remove method. It will return true if the value is removed. So try this:
if(s.remove(i1)) {
System.out.println("i1 removed");
} else {
System.out.println("i1 NOT removed");
}
This line
i1 = 5;
is actually compiled to
i1 = Integer.valueOf(5);
So after execution, i1 is holding another (new) reference, with a value that is not in the HashSet, so nothing is removed.
Java primitives types can only have VALUES.
While Java boxed types have VALUE and IDENTITY.
Two Java boxed types can have same VALUE but different IDENTITY.
Java boxed types are IMMUTABLE; any change in their VALUE will also change the IDENTITY.
If IDENTITY of an object is changed; Java collections cant work effectively.
Statement: i1 = 5; => is actually i1 = Integer.ValueOf(5) => which meant new VALUE of i1.
Collections store only IDENTITY but not VALUE.
Removal by non existing IDENTITY (i1 = 5) from collection, will result nothing.
Source ..... Effective Java by Joshua Bloch
Collections (Set is a collection) in java works with the 'equals()' method, not with the '=' reference operator. That is, when you set 'i1=5', and then 's.remove(i1)', the remove method will compare with all elements.
a) Beginning with the first: is 5 equal to 1?. No, so don't remove that element.
b) The second: is 5 equal to 2?. No, so don't remove that element.
Adding duplicate works the same, on an empty set:
i1=1;
i2=1;
s.add(i1);
s.add(i2)
This will result on a set with only 1 element, because 'i1.equals(i2)' is true, and doesn't matter that 'i1=i2' is NOT true.
It is very important to distinguish between objects and reference variables. A reference expression, including a reference variable, is either null or a pointer to some object.
The HashSet contains its own pointers to the objects in the set it represents. Working through the code:
Set<Integer> s = new HashSet();
// s is a pointer to a new, empty, HashSet.
Integer i1 = new Integer(1);
// i2 is a pointer to an Integer object with value 1
s.add(i1);
// The set contains one Integer object, value 1
Integer i2 = new Integer(2);
s.add(i2);
// The set contains two Integer objects, values 1 and 2
i1 = 5;
// i1 is a pointer to an Integer object with value 5
s.remove(i1);
// The set does not contain any object that is equal
// to an Integer with value 5 so it is unchanged
Becase after you do "i1 = 5;", i1 starts pointing to another address. And it is no more the same Integer than is stored in your HashSet.
I have an object called Person.
it has several attributes in it;
int id;
String name;
i set a person object like Person p = new Person(1,"Joe");.
1.) I need to check if the object is not null; Is the following expression correct;
if (person == null){
}
Or
if(person.equals(null))
2.) I need to know if the ID contains an Int.
if(person.getId()==null){}
But, java doesn't allow it. How can i do this check ?
An int is not null, it may be 0 if not initialized.
If you want an integer to be able to be null, you need to use Integer instead of int.
Integer id;
String name;
public Integer getId() { return id; }
Besides, the statement if(person.equals(null)) can't be true because if person is null, then a NullPointerException will be thrown. So the correct expression is if (person == null)
primitives dont have null value. default have for an int is 0.
if(person.getId()==0){}
Default values for primitives in java:
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
Objects have null as default value.
String (or any object)--->null
1.) I need to check if the object is not null; Is the following expression correct;
if (person == null){
}
the above piece of code checks if person is null. you need to do
if (person != null){ // checks if person is not null
}
and
if(person.equals(null))
The above code would throw NullPointerException when person is null.
A primitive int cannot be null. If you need null, use Integer instead.
1.) I need to check if the object is not null; Is the following expression correct;
if (person == null){
}
YES. This is how you check if object is null.
2.) I need to know if the ID contains an Int.
if(person.getId()==null){}
NO Since id is defined as primitive int, it will be default initialized with 0 and it will never be null. There is no need to check primitive types, if they are null. They will never be null. If you want, you can compare against the default value 0 as if(person.getId()==0){}.
Compiler won't let you assing value of int to null. It won't run.
So we could say it is already partly solved for you.
You have to access to your class atributes.
To access to it atributes, you have to do:
person.id
person.name
where
person
is an instance of your class Person.
This can be done if the attibutes can be accessed, if not, you must use setters and getters...
In Java there isn't Null values for primitive Data types.
If you need to check Null use Integer Class instead of primitive type. You don't need to worry about data type difference. Java converts int primitive type data to Integer.
When concerning about the memory Integer takes more memory than int. But the difference of memory allocation, nothing to be considered.
In this case you must use Inter instead of int
Try below snippet and see example for more info,
Integer id;
String name;
//Refer this example
Integer val = 0;
`
if (val != null){
System.out.println("value is not null");
}
`
Also you can assign Null as below,
val = null;
You can use
if (person == null || String.valueOf(person.getId() == null))
in addition to regular approach
person.getId() == 0
What is the difference between them?
l is an arraylist of Integer type.
version 1:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i);
}
return a;
version 2:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i).intValue();
}
return a;
l.get(i); will return Integer and then calling intValue(); on it will return the integer as type int.
Converting an int to Integer is called boxing.
Converting an Integer to int is called unboxing
And so on for conversion between other primitive types and their corresponding Wrapper classes.
Since java 5, it will automatically do the required conversions for you(autoboxing), so there is no difference in your examples if you are working with Java 5 or later. The only thing you have to look after is if an Integer is null, and you directly assign it to int then it will throw NullPointerException.
Prior to java 5, the programmer himself had to do boxing/unboxing.
As you noticed, intValue is not of much use when you already know you have an Integer. However, this method is not declared in Integer, but in the general Number class. In a situation where all you know is that you have some Number, you'll realize the utility of that method.
The Object returned by l.get(i) is an instance of the Integer class.
intValue() is a instance method of the Integer class that returns a primitive int.
See Java reference doc...
http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#intValue()
Java support two types of structures first are primitives, second are Objects.
Method that you are asking, is used to retrieve value from Object to primitive.
All java types that represent number extend class Number. This methods are in someway deprecated if you use same primitive and object type since [autoboxing] was implemented in Java 1.5.
int - primitive
Integer - object
Before Java 1.5 we was force to write
int i = integer.intValue();
since Java 1.5 we can write
int i = integer;
Those methods are also used when we need to change our type from Integer to long
long l = integer.longValue();
Consider this example:
Integer i = new Integer(10);
Integer j = new Integer(10);
if (!(i == j)) {
System.out.println("Surprise, doesn't match!");
}
if (i.intValue() == j.intValue()) {
System.out.println("Cool, matches now!");
}
which prints
Surprise, doesn't match!
Cool, matches now!
That proves that intValue() is of great relevance. More so because Java does not allow to store primitive types directly into the containers, and very often we need to compare the values stored in them. For example:
oneStack.peek() == anotherStack.peek()
doesn't work the way we usually expects it to work, while the below statement does the job, much like a workaround:
oneStack.peek().intValue() == anotherStack.peek().intValue()
get(i) will return Integer object and will get its value when you call intValue().In first case, automatically auto-unboxing happens.
They are exactly the same. As other posters have mentioned, you can put either the Integer object or the int primitive into the array. In the first case, the compiler will automatically convert the Integer object into a primitive. This is called auto-boxing.
It's just a convenience method for getting primitive value from object of Number: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Number.html
Consider the code:
Integer integerValue = Integer.valueOf(123);
float floatValue = integerValue.floatValue();
The last line is a convenient method to do:
float floatValue = (float)(int)integerValue;
Since any numeric type in Java can be explicitly cast to any other primitive numeric type, Number class implements all these conversions. As usual, some of them don't make much sense:
Integer integerValue = Integer.valueOf(123);
int intValue = integerValue.intValue();
int intValue2 = (int)integerValue;
int intValue3 = integerValue;
I'm trying to use a dictionary. Whenever I want to check if an element is present in the dictionary, I do this:
int value = results.get("aKeyThatMayOrMayNotBePresent");
if (value != null)
// ...
But then the compiler says I can't compare an int to a <nulltype>. What's the correct way to check for null in this case?
You're comparing a primitive value (int) to null. Since primitives cannot be null, you should use a corresponding object, such as Integer in this case. So, you should write
Integer value = results.get("aKeyThatMayOrMayNotBePresent");
Your null check is too late.
int value = results.get("aKeyThatMayOrMayNotBePresent");
This line already converts the reference to a primitive int. It will throw a NullPointerException if the return value of get is null.
The correct way would be to use Integer instead of int.
Integer value = results.get("aKeyThatMayOrMayNotBePresent");
This way value wont be a primitive type and your null check is valid.
int is a primitive type; you can compare a java.lang.Integer to null.
You should use Map instead of Dictionary, Dictionary is obsolete.
With Map you can use containsKey() instead, which in my opinion is more readable:
if (results.containsKey(key))
{
int value = results.get(key);
[...]
}
In my experience this is not slower than your approach, despite the apparent double access to the map. If this is executed often enough for performance to matter then it is optimized away.
Get the Object and check if that is null.
Object valueObj = results.get("...");
if ( valueObj != null )
{
Integer value = (Integer)valueObj;
}