Can an int be null in Java? - java

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.

Related

Integer vs int types, which is better? [duplicate]

This question already has answers here:
Which one to use, int or Integer
(11 answers)
When to use wrapper class and primitive type
(11 answers)
Closed 9 years ago.
Why does Java have these Integer, Character types and classes
while they are also adapting C's int, char etc
Sometimes when people are creating arrays, they tend to
use Integer[] i = {......}
rather than int[] i = {....};
what is the difference then?
Integer is an object, while int is a primitive. Whenever we pass an int into a function, we pass it as-is.
Integer wraps an int. In its case it is immutable so editing it via reference isn't going to work, but it can be put into generics. This can be set to null while int does not have a possibility of anything beyond 0 or a special value you interpret as a null condition, such as -1 or Integer.MAX_VALUE.
For instance, ArrayList<int> is completely invalid while ArrayList<Integer> must be used with ints being wrapped.
With autoboxing, however, we can immediately add an int to an ArrayList without manually wrapping it, and if we need a primitive when we get() the entry, it'll automatically unwrap it transparently.
In the end if you're doing calculations with a limited number of distinct variables or a fixed array, you should generally use int. When dealing with sets, lists, or maps, you should declare the collection as FooCollection<Integer> then add( an int directly allowing for autoboxing.
Integer, Character and others like this are Objects while int, char and others like this are primitives.
The biggest difference is that an Object can be null while a primitive value can't.
It's recommended to use primitive values where you can because they use less memory.
The only difference we can tell generally is Wrapper is objective representation of primitive.
Wrapper classes are used to represent primitive values when an Object is required.
In java,
Integer is a wrapper class i.e. it is an object while int is a primitive.
Integer default value is null while for int it is 0
There is a concept of autoboxing and auto-unboxing for these two types.
An integer can be converted to an int and vice versa
Followign program demonstrates this
public class TestClass {
int num;
Integer number;
public static void main(String[] args) {
TestClass testClass = new TestClass();
System.out.println(testClass.num);
System.out.println(testClass.number);
testClass.autoBoxInt(testClass.num);
}
public void autoBoxInt(Integer number){
System.out.println(number);
}
}
The output is
0
null
0
The statement System.out.println(testCkass,num) prints int default value i.e. 0. System.out.println(testClass.number) prints Integer default value i.e. null. When you pass testClass.num to a method with parameter Integer, int is automatically converted into and Integer object. so the method prints out 0.
The java collections framework uses autoboxing to convert primitives into Wrapper classes because they cannot take primitive values. They help fast retrieval and storing of objects into collections using hashing and hashcodes. Following example demonstrates this
Set<Integer> numbers = new HashSet<Integer>();
numbers.add(new Integer(10));
numbers.add(new Integer(4));
numbers.add(6);
numbers.add(-9);
numbers.add(new Integer(65));
System.out.println(numbers);
This prints out the set
[4, 65, 6, -9, 10]
To know what hashing is and how hashcodes are used, you can look these links
http://www.thejavageek.com/2013/06/27/what-are-hashcodes/
http://www.thejavageek.com/2013/06/26/what-is-the-significance-of-equals-method-in-java/

Difference between int and Integer

What is the difference between int and Integer. Yes, one is primitive and another one is wrapper, what is the situation to use them correctly.
Also what is the difference between :
int i=0;
++i
and
i++
part 1
One example .. you can use Integer as the key of HashMap but you can't use int. Because an Object is needed.
So where you need an int value as an object there you need to use Integer class.
part 2
++i is pre increment
i++ is post increment
for example
i = 0;
System.out.println(i++) //will print 0 then the i will be 1.
and
i = 0;
System.out.println(++i) // here i wil be incremented first then print 1.
Integer is a wrapper class for int which is a primitive data type. Integer is used when int can't suffice. For example: In generics, the type of the generic class, method or variable cannot accept a primitive data type. In that case Integer comes to rescue.
List<int> list; //Doesn't compiles
List<Integer> list; // Compiles
Moreover Integer comes with a plethora of static methods, like toBinaryString, toHexString, numberOfLeadingZeros, etc. which can come in very handy.
As already explained above
An Integer is an object, whereas an int is a primitive. So you can have a null reference to an Integer and a Set or List of them. You can not do that with an int
I find this null reference very useful, when i have to store int values in database. I can store a null value when I use Integer. But cannot do so when I use int.
An Integer is an object, whereas an int is a primitive. So you can have a null reference to an Integer and a Set or List of them. You can not do that with an int.
A basic explanation is an int is a primitive data type and literally is only a value stored in memory. An Integer is a Java object that wraps an int in a Class with lots of nice/helpful methods that can be called to work with that backing int hidden inside. This is the same with most of the primitive data types, such as boolean and Boolean, char and Character, etc. This is refereed to as Boxing a primitive. Unboxing being the opposite, taking an Object and extracting the backing primative.
Here's an example of how one may use Integer to convert a String into an int (boxed to an Integer)
String someString = "10";
Integer intObj = Integer.parseInt(someString);
System.out.println(intObj.toString());
You'll find that some of the data types have more helpful methods than others. Check the JavaDoc's for each of the types you are interested in, there are a lot of goodies in there!

Assigning a null value to an int

If the following code is possible:
Integer a = null;
int b = a;
Does it mean that a function returning a possible null value for an integer is a bad practice?
Edit 1:
There are several different opinions in these answers. I am not enough confident to choose one or another.
That code will give a NullPointerException when you run it. It's basically equivalent to:
Integer a = null;
int b = a.intValue();
... which makes it clearer that it will indeed fail.
You're not really assigning a null value to an int - you're trying and failing.
It's fine to use null as a value for an Integer; indeed often Integer is used instead of int precisely as a "nullable equivalent`.
It is not possible. You will get NullPointerException
That will throw a NullPointerException.
The reason for this is that you're relying on auto-unboxing of the Integer value to an int primitive type. Java does this by internally calling .intValue() on the Object, which is null.
As to either it's a good practice or not... I would advise against doing so, unless the code is only used by you and you're extremely well behaved, making sure that you only assign the return value of such method to Integer values, not int.
If your code ends up in a lib used by others, it's not safe, and I would rather explicitly throw an Exception, well documented, and allow for defensive coding on the caller's part.
Funny thing with Java tenerary operator ?: (using 8u151 on OSX)
If you do
Integer x = map == null ? 0 : map.get ( key );
which seems fine and compact and all, then you get an npe!!! if
map.get ( key )
is a null. So I had to split that and it worked fine.
Of course you cannot assign null to an int. But returning a null in some situations makes sense. Null can mean that the value is not set. A typical example is a DB column.
The code is possible, but throws a NullPointerException at runtime, because of unboxing. Regarding
Does it mean that a function returning a possible null value for an
integer is a bad practice?
yes, it is. It's useless and dangerous (as you can see) to return an Integer when a int is enough, because objects can be null, while primitives can't. Integer should be used only when needed, like in a parameterized type - List<Integer>
From Java 8, we can use Optional:
// example: if an Integer object is null, an int value could receive 0, for example:
Integer value = getSomeInteger (...); // (0, null, or some other numeric value)
int inteiro = Optional.ofNullable(value).orElse(0);
That would work indeed.
Integer a = null;
Integer b = a;
But I would rather use a int value out of range (-1 if your numbers are all positive) to return in case of an error.
It's a bout Java auto-boxing.
Integer a = null;
int b = a;
this code assign a to b,actually the compiler will do this:int b=a.intValue(), so this line will throw NullPointerException;
the code :
Integer a = 1;
will actually do this: Integer a = Integer.valueOf(1);
You can use javap to see the compiled virtual machine instructions。
You can write simple test:
public class Test {
public static void main(String[] args){
Integer a = null;
int b = a;
System.out.println(b);
}
}
And the output is a NullPointerException on int b = a;
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

How to check if an int is a null

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

Can't check if int is null

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;
}

Categories

Resources