Voidable types in Java equivalent to those in C #, possible?

5

The main purpose of this question is to contribute content to Stack Overflow in Spanish

In C # we can convert data types (that do not accept the null value) to be nullable; assigning null to this type of data, produces a syntax error since C # performs the verification while it is being written.

That is, if we had something like float flotante = null; it would generate the error: float es un tipo que no acepta valores null

Although if you put the question sign in front of the type, then e becomes nullable and supports null values.

It would be something like:

bool? booleano = null;
int? entero = null;
float? flotante = null;
decimal? decim = null;

Now, is there any equivalent in Java?

    
asked by Héctor Manuel Martinez Durán 04.05.2018 в 02:43
source

3 answers

5

No.

In Java, null values are not accepted in primitive data types, but in objects. So if, for example, you want to assign null to a boolean, you can not boolean boleano = null;

Instead, you can use for example the class Boolean encuadrada (the object java.lang.Boolean which is an ordinary class / object / or instead of a primitive type).

You can use:

Boolean b = null;

And then also set true or false by a simple assignment:

Boolean b = true; o Boolean b = false;

This is called Primitive wrapper class or primary wrapper class, which are classes to which values can be assigned of primary types, but that being objects, they also accept null;

Here are some types of these classes:

I hope it will serve you, and also future readers. Good luck.

    
answered by 04.05.2018 / 02:43
source
0

By default, Java does not support implicit conversion to Nullable of primary types like C #, but it can be applied to objects that perform similar primary type handling functions.

Objects such as Integer , Character , or Boolean , Float , Long , Short handle these values keeping their object type which in turn supports null value.

    
answered by 04.05.2018 в 05:39
-1

No, the same concept does not exist in Java. The most similar to the nullables types of C # is the class java.util.Optional<T>

    
answered by 04.05.2018 в 03:47