Checking Integer Wrapper against NULL as well as primitive value 0
Replace or
by and
:
if( statusId != null && statusId != 0 )
It will work because only if statusId
is not null
:
statusId != null
you will try to unbox statusId
to int
:
statusId != 0
And in the case of statusId
is null
, the short-circuiting &&
operator will prevent to throw a NullPointerException
as statusId != 0
will not be evaluated.
How can I tell if a Java integer is null?
parseInt()
is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers
, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
Beware if you do decide to use parseInt()
! parseInt()
doesn't support good internationalization, so you have to jump through even more hoops:
try {
NumberFormat nf = NumberFormat.getIntegerInstance(locale);
nf.setParseIntegerOnly(true);
nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.
// Start parsing from the beginning.
ParsePosition p = new ParsePosition(0);
int val = format.parse(str, p).intValue();
if (p.getIndex() != str.length()) {
// There's some stuff after all the digits are done being processed.
}
// Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
// Something blew up in the parsing.
}
Check if the value is null and assign it 0
You can use ternary operator to check a condition and set the value like 0
String num1 = editTextnum1.getText().toString();
num1 = num1.isEmpty() ? "0" : num1;
Integer variable is zero when is it null in database
You have to handle that case yourself. The ResultSet
documentation clearly states (emphasis mine):
getInt int getInt(int columnIndex)
Retrieves the value of the designated column in the current row of this ResultSet object as an int in the
Java programming language.Parameters:
* columnIndex - the first column is 1, the second is 2, ...Returns:
the column value; if the value
is SQL NULL, the value returned is 0
You have to call wasNull()
after reading a column value and set your field to null
if that was the case. So something like the following:
Integer projectId = rs.getInt("PROJECT_ID");
if (rs.wasNull()) projectId = null;
return new Project (rs.getInt("ID"), projectId), ...);
For sanity reasons it's probably nicer if you move that code into a new method:
/**
* Retrieves the value from the designated column as an {@link Integer}
* object.
*
* @param rs
* The ResultSet to read from.
* @param columnName
* The column name to read.
* @return {@code null} if the column value was SQL NULL; its value as an
* integer otherwise.
*/
public static Integer getInteger(ResultSet rs, String columnName) {
int v = rs.getInt(columnName);
return rs.wasNull() ? null : v;
}
Check if a Integer is empty
Class Integer
is just an wrapper on top of primitive int
type. So it can either be null
or store a valid integer value. There is no obvious "empty" definition for it.
If you just compare Integer
against empty String
, you''ll get false
as a result. Always. See Integer.equals(Object o)
implementation:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
First of all, you can get a NumberFormatException
during parsing integer in the line:
Integer varsta = Integer.parseInt(request.getParameter("varsta"));
And you are getting it, since For input string: ""
looks like a NumberFormatExpection
message.
In your example you should either check whether the "varsta"
attribute value is a number (assume it's a string) and then parse it, or parse it as is and catch NumberFormatException
that Integer.parseInt()
throws on incorrect argument.
First solution:
Integer varsta = null;
String varstaStr = request.getParameter("varsta"); // read string 'varsta' field
if (varstaStr != null && varstaStr.matches("\\d+")) { // null-check and regex check to make sure the string contains only digits
varsta = Integer.parseInt(varstaStr);
}
Second solution:
Integer varsta = null;
String varstaStr = request.getParameter("varsta"); // read string 'varsta' field
try {
varsta = Integer.parseInt(varsta);
} catch (NumberFormatException e) {
// handle error
}
After this, you have one more problem in the line:
if(varsta == null && "".equals(varsta)){
The varsta
reference has type Integer
here, so "".equals(varsta)
will always return false
:
(varsta == null && "".equals(varsta)) = [assume varsta is null] =
((null) == null && "".equals(null)) = (true && false) = false
Replace
if(varsta == null && "".equals(varsta)){
with
if(varsta == null){
This should help you.
P.S. If you use Java of version 7 or higher, consider use try-with-resources to manage Connection
and PreparedStatement
.
Compare nullable Integer to 0
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 Topics
How to Check If an Int Is a Null
Java Spring Boot Test: How to Exclude Java Configuration Class from Test Context
Find Difference Between Two Strings
Java Spring: Best Way to Convert a File to a Multipartfile
Parameter 0 of Constructor in Required a Bean of Type 'Java.Lang.String' That Could Not Be Found
Rounding to the Nearest Hundered-Thousandths
How to Prevent Duplicate Results in Hibernate
How to Check If a Record Exists Using Jpa
How to Split a String Between Letters and Digits (Or Between Digits and Letters)
What Happens When Base and Derived Classes Each Have Variables With the Same Name
Resttemplate: How to Send Url and Query Parameters Together
Cannot Construct Instance of 'Java.Time.Localdate' - Spring Boot, Elasticseach, Jackson
Java 8 Lambda Create List of Strings from List of Objects
How to Remove the Decimal Part If It Is Only 0
How to Download a Pdf File in Chrome Using Selenium Webdriver
Spring Boot - Exception Encountered During Context Initialization. How to Know the Reason of Error
Can Not Deserialize Instance of Java.Util.Arraylist Out of Start_Object Token