How to write nullable int in java?
Asked Answered
D

4

84

I want to convert a web form to a model in Java.

In C# I can write this:

<input name="id" value="" type="text"/>


public class Test
{
    public int? Id{get;set;}
}

The id can be null.

But in Java when using struts2 it throws an exception:

Method "setId" failed

So how to write this case in Java?

Descendant answered 14/1, 2013 at 15:16 Comment(2)
use Integer instead of int.Hellas
Possible dupes: https://mcmap.net/q/246378/-how-to-present-the-nullable-primitive-type-int-in-java/1015495 https://mcmap.net/q/247412/-creating-nullables-types-in-java/1015495Ramiroramjet
A
169

Instead of using int you can use Integer (Integer javadoc) because it is a nullable Java class.

Adaxial answered 14/1, 2013 at 15:18 Comment(2)
thanks~ 'int' is same as 'Integer' in C#,so I didn't know this solution.Descendant
@Descendant don't forget to mark this post as an answer once the 15 mins have past.Carlist
S
53

You can use an Integer, which is a reference type (class)in Java and therefore nullable.

Int32 (or int) is a struct (value type) in C#. In contrast, Integer in Java is a class which wraps an int. Instances of reference types can be null, which makes Integer an legit option.

Nullable<T> in .NET gives you similar options because it enables you to treat a value type like a nullable type. However, it's still different from Java's Integer since it's implemented as a struct (value type) which can be compared to null, but cannot actually hold a genuine null reference.

Saintmihiel answered 14/1, 2013 at 15:18 Comment(1)
this is a more thorough answer than the accepted oneObjectivism
L
9

In Java, just use Integer instead of int. This is essentially a nullable int. I'm not too familiar with Struts, but using Integer should allow you to omit the value.

Leghorn answered 14/1, 2013 at 15:18 Comment(0)
C
1

Optional<Integer> - The purpose of the class is to provide a type-level solution for representing optional values instead of null references.

OptionalInt - A container object which may or may not contain a int value. If a value is present, isPresent() will return true and getAsInt() will return the value.

Clare answered 12/2, 2023 at 8:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.