How to set to int value null? Java Android [duplicate] - java

This question already has answers here:
What is the difference between an int and an Integer in Java and C#?
(26 answers)
Closed 9 years ago.
which is the best way to set already defined int to null?
private int xy(){
int x = 5;
x = null; //-this is ERROR
return x;
}
so i choose this
private int xy(){
Integer x = 5;
x = null; //-this is OK
return (int)x;
}
Then i need something like :
if(xy() == null){
// do something
}
And my second question can i safely cast Integer to int?
Thanks for any response.

You can't. int is a primitive value type - there's no such concept as a null value for int.
You can use null with Integer because that's a class instead of a primitive value.
It's not really clear what your method is trying to achieve, but you simply can't represent null as an int.

In this case, I would avoid using null all together.
Just use -1 as your null
If you need -1 to be an acceptable (not null) value, then use a float instead. Since all your real answers are going to be integers, make your null 0.1
Or, find a value that the x will never be, like Integer.MAX_VALUE or something.

Only objects can be null. Primitives (like int) can't.
can i safely cast Integer to int?
You don't need a cast, you can rely on auto-unboxing. However it may throw a NullPointerException:
Integer i = 5;
int j = i; //ok
Integer k = null;
int n = k; //Exception

Your method compiles, but will throw NullPointerException when trying to unbox the Integer...
The choice between Integer and int depends on what you are trying to achieve. Do you really need an extra state indicating "no value"? If this is a legitimate state, use Integer. Otherwise use int.

Related

Delete value for previously assigned int field [duplicate]

Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
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 . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.

What is the use of intValue() when you can directly assign Integer value to primitive int? [duplicate]

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;

why "==" operator does not work [duplicate]

This question already has answers here:
Compare two objects with .equals() and == operator
(16 answers)
Closed 7 years ago.
the targetPixValList is a list contains Double objects and it contains also similar values in successive position in the list, and when i tried to compare two Double values using Code_1, the cnt returns zero.
and when i used code_2, the cnt returns value.
and the type of the list is
why "==" operator does not work with Double?
Code_1:
int cnt = 0;
for (int i = 0; i < cs.targetPixValList.size()-1; i++) {
if (cs.targetPixValList.get(i) == cs.targetPixValList.get(i+1))
++cnt;
}
Code_2:
int cnt = 0;
for (int i = 0; i < cs.targetPixValList.size()-1; i++) {
if (cs.targetPixValList.get(i).equals(cs.targetPixValList.get(i+1)))
++cnt;
}
Double is a class wrapper for primitive double. When comparing instances of Double (or object references) use equals method rather than ==.
Also, for your case, the comparison of Double by using equals could also give wrong results due to float point comparison (done behind the scenes). If you're working with sensitive floating points values, I recommend using BigDecimal instead of Double and use BigDecimal#compareTo rather than equals because BigDecimal#equals does not take into account the scale, while BigDecimal#compareTo does.
You use .equals(otherObject) when comparing objects. You're comparing Double which is an object. If you were using double instead, a primitive, you could use == to compare values.
Alternatively, get the double value from Double object:
if (yourDoubleObject.doubleValue() == otherDoubleObject.doubleValue()) {
// Do some things
}
== operator gives correct results in primitive types like int, long, double. If you use the operator with objects it will compare the references by default.
Using equals method may give the correct result dependingof the object. You should override equals method to receive logically check if the objects are equals.
For Double object, ,it also checks the referance equivalence of the objects. You should use Double#doubleValue method to check value equivalence.
Here is the code;
for (int i = 0; i < cs.targetPixValList.size()-1; i++) {
if (cs.targetPixValList.get(i).doubleValue() == cs.targetPixValList.get(i+1).doubleValue())
++cnt;
}
See also :
How to override equals and hashcode

Java declaration confusion for datatypes

I have a doubt about null assigning to variable in Java. In my program I have assigned null to String variable as String str_variable = null;. For the learning purpose i assigned null integer variable as int int_variable = null; It shows error Add cast with Integer. So that rewrite the above int declaration as Integer int_variable = null;. This does not shows errors. I do not know the reason of these two kind of declaration.
Please the difference between to me.
String str_variable = null;
int int_variable = null; // error.
Integer int_variable1 = null; // no error.
String and Integer are both classes, in a way they are not native data types that is why it is always okay for you to set null as an initial value, however for int you must always initialize it with a number, one good way to find out their appropriate initialization value is to create variables outside your main(), example String var1; int var2; then use System.out.println(var1); System.out.println(var2); within the main()
to see what was placed as an initial value when you run the program.
int is a primitive, Integer is a class.
See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
int is a primitive type, Integer is a wrapper class type extending Object class. Non-referencing objects can be null but primitives cannot. That's why you get an error message saying you need casting.
You can use a line like int num = (Integer) null;, this is how casting is done, however you will get NullPointerException when you try to use num anywhere in your code since a non-referencing(null) Integer object doesn't hold / wrap a primitive value.

How to compare Integer correctly in Java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Integer wrapper class and == operator - where is behavior specified?
I known Java integer use cache in -127~128.
If
Integer i = 1;
Integer j = 1;
Integer m = 128;
Integer n = 128;
i == j // true
m == n // false
But I met a strange phenomenon.First,look at following snippet.
List<CustomerNotice> customerNotice = findByExample(example); // use Hibernate findByExample method
for(CustomerNotice n : customerNotice){
if(n.getConfirmStatus() == NoticeConfirmStatus.UNCONFIRMED.getValue()){
// do sth
}
}
public enum NoticeConfirmStatus{
UNCONFIRMED(1), //
CONFIRMED(2), //
FAILED_TO_CONFIRM(3); //
private final Integer value;
private NoticeConfirmStatus(Integer value) {
this.value = value;
}
public Integer getValue() {
return this.value;
}
}
public class CustomerNotice {
#Column(name = "CONFIRM_STATUS")
private Integer confirmStatus;
public Integer getConfirmStatus() {
return this.confirmStatus;
}
public void setConfirmStatus(Integer confirmStatus) {
this.confirmStatus = confirmStatus;
}
}
Although the if expression is not recommended, I think it will be return true,because n.getConfirmStatus()==1, but the result is false.I'm very confusing.
In addition, theList<CustomerNotice> customerNotice acquired by Hibernate findByExample method. Is there some Autoboxing or new operation when retrieve the resultset?
Thank you.
SHORT: (answers question)
If you want to compare Integers as the objects, you should use .equals:
i.equals(j);
m.equals(n);
With this, they should both return true. But if you really want to use ==, you need to get the primitive int value:
i.intValue() == j.intValue();
m.intValue() == j.intValue();
LONG: (explains answer)
The basis of this is that Objects are always stored separately in memory (except for some special cases like m=n), and to be compared properly, they need to be broken down into primitive types that can be compared successfully using ==.
Every Object has a .equals() method, which is inherited from Object as its superclass. However, it must be overridden to do a proper comparison. Integer overrides this method to compare to Integer objects successfully, while using == checks to see if both objects point to the same space in memory, and because two instances of an Object cannot point to the same space in memory, this will always return false.
However, as your code points out, there are some special cases that work, like these:
Your code uses a Integer i = 1, which is considered a "standard instance" and is able to be compared using ==.
If you set one Object equal to another using =, Java tells both objects to point to the same location in memory, which means that == will return true.
There are many others, but those are the two that come to mind and seem relevant.
You'll drive yourself crazy and waste a lot of time trying to figure out specific cases where this works or does not work. It depends on the implementation of code which isn't always visible to you.
The bottom line: never, ever, use == to compare Integer instances, period. As you have seen, it works sometimes, under some circumstances, and fails miserably the rest of the time. If you have a method that returns an Integer, then assign the value to an int, and then you can use == to compare that int to another int.

Categories