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 ?
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){}
.
You can use
if (person == null || String.valueOf(person.getId() == null))
in addition to regular approach
person.getId() == 0
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...
A primitive int
cannot be null. If you need null, use Integer
instead.
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.
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;
Source: Stackoverflow.com