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
Ok, so i have to create a recursive method for counting the nodes in a tree, and i did this (variable names are in portuguese, sorry):
public int contaNos(Arvbin r) {
Integer cardinalidade = 0;
contaNosPrivado(r, cardinalidade);
return cardinalidade;
}
private void contaNosPrivado(Arvbin r, Integer cardinalidade) {
if (r==null) {
return;
}
cardinalidade=cardinalidade+1;
contaNosPrivado(r.esq, cardinalidade);
contaNosPrivado(r.dir, cardinalidade);
return;
}
Arvbin is the binary tree, esq and dir are the left and right references to the tree's branches.
I thought this would work, but for some reason when i try to run it, it returns 0. I've usen a little bit of debugging and i think the issue is that when the methods finish and come back to the original non-recursive one, the cardinalidade variable is set to 0. I'm not sure if it's because autoboxing is messing with my Integer and turning it into an int, and then when i call the method it passes a copy of the value instead of the reference to the existing object, and i don't know how to fix it. If anyone could help, i'd greatly appreciate it
The problem is that wrapper classes are immutable in Java. cardinalidade is just a parameter of contaNosPrivado here and, unfortunately, cannot act as an argument like other object type parameters can, i.e. this local reference cannot change inner fields of the object that initial reference refers. Any change to it affects it only the way it affects any primitive local variable.
What exactly happens inside your contaNosPrivado:
On invocation, it is indeed supplied a reference to an Integer object. This reference is assigned to a local variable named
cardinalidade.
In this line:
cardinalidade=cardinalidade+1;
this object is first unboxed to a primitive int variable, this variable is incremented afterwards, and
finally the result is reboxed into a new Integer object which is
then assigned to cardinalidade. There is no way to 'increment'
original object, even if you use the increment operator:
cardinalidade++;
Any further processing applies to the newly created Integer object and doesn't affect the reference passed to contaNosPrivado.
To achieve your goals, use something like this instead:
static int contaNosPrivado(Arvbin r) {
if (r == null)
return 1;
else
return contaNosPrivado(r.esc) + contaNosPrivado(r.dir);
}
As #John McClane has pointed out, you can't pass an Integer argument by reference, only by value.
But there's also no need for a private helper method, you can just simplify it all to a single method:
public int countLeaves( BinaryTreeNode n )
{
return n == null? 0 : ( countLeaves( n.rightLeaf ) + countLeaves( n.leftLeaf ) );
}
Or (excuse my poor Portugese):
public int contaNos( Arvbin r )
{
return r == null? 0 : ( contaNos( r.esq ) + contaNos( r.dir ) );
}
I have an Integer value of variable as below:
Integer programNumber= ........
I took the program number as Integer type. However in my other class, I want to check whether this variable, programNumber, equals variable which is the type of int.
To sum up, I want to convert the variable of the of Integer to int primitive value.
I used programno.intValue() but it doesn't work.
Thanks in advance.
I have a two class, BasvuruKisi and Program. the code snippet is below:
BasvuruKisi bsvkisi = (BasvuruKisi) (this.getHibernateTemplate().find("from BasvuruKisi bsv where bsv.basvuruNo=?", basvuruNumaralari.get(i))).get(0);
if (bsvkisi != null) {
int yetkiVarmi = 0;
Integer programno= bsvkisi.getProgramId();
List array =
this.getHibernateTemplate().find("from Program p where p.id=?", programno.intValue());
but
this.getHibernateTemplate().find("from Program p where p.id=?", programno.intValue());
this one doesn't work. return firstly, no table or view is available despite available and then returns null pointer exception.
thanks
The variable name in the initialization block says programNumber, but the variable in the method call is programno. Which is it?
Using the wrong variable name shouldn't give you a null pointer exception, unless you have another variable named programno defined somewhere.
Whatever the variable name is, make sure you initialize it before you get the intValue.
Validate programNumber is null or not?
If the value is null, it throws Exception.
Integer programNumber= null;
System.out.println(programNumber.intValue());
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.
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.
Is it null for Object type?
class C {
int i;
String s;
public C() {}
}
Will s be always null?
What about simple types as int? What will that be? Zero or an arbitrary value?
What about local variables in methods?
public void meth() {
int i;
}
What is the unitialized value of i?
Relying on such default values, however, is generally considered bad
programming style.
Ok, what do you suggest we do?
class A {
String s = "";
int i = 0;
}
OR:
class A {
String s;
int i;
public A() {
// default constructor
s = "";
i = 0;
}
}
Which is better and why?
From suns java tutorial
It's not always necessary to assign a
value when a field is declared. Fields
that are declared but not initialized
will be set to a reasonable default by
the compiler. Generally speaking, this
default will be zero or null,
depending on the data type. Relying on
such default values, however, is
generally considered bad programming
style.
The following chart summarizes the
default values for the above data
types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
String (or any object) null
Local variables are slightly
different; the compiler never assigns
a default value to an uninitialized
local variable. If you cannot
initialize your local variable where
it is declared, make sure to assign it
a value before you attempt to use it.
Accessing an uninitialized local
variable will result in a compile-time
error.
For member variables:
The default value for String is null. The default value for primitives is 0 (or 0.0 for floating point values).
For local variables:
You must explicitly initialise a local variable before using it.
As to the second part of your question:
You can always say String s = ""; in the member variable definition, or s = ""; in the constructor. Then you know it will have a non-null value. (Also, in your setter you'd need to ensure that someone doesn't try and set it back to null.)
Fields: Objects default to null; ints, longs and shorts to 0; Strings to null; booleans to false. It's all here.
The compiler will force you to initialise variables declared in methods, local variables, yourself.
Primitive fields are initialized to 0 / false. Objects are initialized to null . But frankly, you could have tried that one..
As for the setter-method question: The whole point of setters is that they can check if the object passed conforms to the requirements of the class. e.g.
public void setS(String s) {
if (s == null)
throw new IllegalArgumentException("S must not be null");
this.s = s;
}
Or, with Google Collections/Google Guava:
public void setS(String s) {
this.s = Preconditions.checkNotNull(s, "S must not be null");
}
Of course, you can define arbitrary constraints, e.g.:
/**
* Sets the foo. Legal foo strings must have a length of exactly 3 characters.
*/
public void setFoo(String foo) {
if (foo == null)
throw new IllegalArgumentException("Foo must not be null");
if (foo.length() != 3)
throw new IllegalArgumentException("Foo must have exactly 3 characters");
...
Of course in such a case you should always state the correct range of values for your properties in the JavaDoc of the setter and/or of the class.
JLS 4.12.5. Initial Values of Variables
Each class variable, instance variable, or array component is
initialized with a default value when it is created (§15.9, §15.10.2):
For type byte, the default value is zero, that is, the value of
(byte)0.
For type short, the default value is zero, that is, the value of
(short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is,
'\u0000'.
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null.