A better way to convert Integer (may be null) to int in Java?
Avoiding an exception is always better.
int i = integer != null ? integer.intValue() : -1;
Conversion from null to int possible?
Let's look at the line:
return y == null ? null : y.intValue();
In a ? :
statement, both sides of the :
must have the same type. In this case, Java is going to make it have the type Integer
. An Integer
can be null
, so the left side is ok. The expression y.intValue()
is of type int
, but Java is going to auto-box this to Integer
(note, you could just as well have written y
which would have saved you this autobox).
Now, the result has to be unboxed again to int
, because the return type of the method is int
. If you unbox an Integer
that is null
, you get a NullPointerException
.
Note: Paragraph 15.25 of the Java Language Specification explains the exact rules for type conversions with regard to the ? :
conditional operator.
Assigning a null value to an int
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`.
Convert a nullable integer value in Java (Short, Long etc.)
Plain simple "casting" and the "ternary conditional operator" would be the minimal and fastest solution.
Short shortVal = null;
Long longVal = shortVal == null ? null : (long) shortVal;
Since you don't seem to know about casting, here's an example that does not work - and how to fix it. Mind that the problem of null is completely ignored here - this is just a quirky aspect of casting that you might want to know, that's all.
Double doubleVal = 1d;
Float floatVal = (float) doubleVal; // Inconvertible types!
Working version:
Double doubleVal = 1d;
Float floatVal = (float) (double) doubleVal;
Can an int be null in Java?
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>
How to convert null to int without casting to integer?
The fundamental issue here is that you are declaring, up front, three arrays without knowing how many values they will need to hold. Sure, you know a maximum number of values they'll hold (10), but you don't know the minimum. This then affects your calls to Arrays.toString
.
Using a List
would be the preferred method, but if you haven't covered casting in your class then I'm guessing that lists have also not been covered yet. Why not just have your server return a String
instead? (I'm purposely leaving out StringBuilders here for simplicity, again as I doubt they've been covered).
Main:
import java.util.Scanner;
public class Main {
public static void main (String[] args){
Scanner input = new Scanner(System.in);
int [] array = new int[10];
System.out.print("Insert the 10 values of your array.");
for(int i=0; i<array.length; i++){
array[i] = input.nextInt();
}
System.out.println("The even numbers in the array are...");
System.out.println(Server.getEven(array));
System.out.println("The odd numbers in the array are...");
System.out.println(Server.getOdd(array));
System.out.println("The negative numbers in the array are...");
System.out.println(Server.getNeg(array));
input.close();
}
}
Server
public class Server {
public static String getEven(int[] array){
String result = "";
for(int i=0; i<array.length; i++){
if(array[i]%2 ==0){
if(result.length() != 0)
{
result = result + ", ";
}
result = result + array[i];
}
}
return result;
}
public static String getOdd(int[] array){
String result = "";
for(int i=0; i<array.length; i++){
if(array[i]%2 !=0){
if(result.length() != 0)
{
result = result + ", ";
}
result = result + array[i];
}
}
return result;
}
public static String getNeg(int[] array){
String result = "";
for(int i=0; i<array.length; i++){
if(array[i]<0){
if(result.length() != 0)
{
result = result + ", ";
}
result = result + array[i];
}
}
return result;
}
}
Cast a Null String into Integer
You cannot cast from String to Integer. However, if you are trying to convert string into integer and if you have to provide an implementation for handling null
Strings, take a look at this code snippet:
String str = "...";
// suppose str becomes null after some operation(s).
int number = 0;
try
{
if(str != null)
number = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
number = 0;
}
How to set to int value null? Java Android
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.
Related Topics
Error While Running Allure Command Line Generate Command
Regular Expression to Validate Username
Error: Could Not Find or Load Main Class in Intellij Ide
Find Maximum Score or the Maximum Average Score of Candidate Scores Given in Two Dim Array
How to Specify the Required Java Version in a Gradle Build
Multiple Scanner Inputs (Java)
How to Disable Spring Security for Particular Url
How to Upload a Document to Sharepoint With Java
Using an Empty Keystore Password Used to Be Possible
Passing Data into HTML from Java Via Spring
How to Return Different Results When Calling the Same Mocked Method
How to Find Max Date in List<Object>
Object Cannot Be Converted to Integer Error
Java.Io.Filenotfoundexception: the System Cannot Find the File Specified
Select the Letters After - in a String
Method Does Not Override Method from Its Superclass . Android Fragment