Passing null parameter to a method

2

It is possible to pass / receive null parameters in Java.

In C # I know it's possible using ? in type.

public DateTime Teste(DateTime? exemplo){...}

In this case the example I know can come null , in Java is this possible in any way?

    
asked by anonymous 05.11.2014 / 18:34

2 answers

2

If you have the primitive types ( int , boolean , long , char , etc.) in the parameter, then you can not pass null to a function:

public java.util.Date Teste(boolean valor) { ... }
public void Test2() {
    Test(null); // erro de compilação
}

If you want to use a "nullable" type, you must use the class corresponding to the primitive type of the parameter:

public java.util.Date Teste(Boolean valor) { ... }
public void Test2() {
    Test(null); // funciona
    Test(false); // funciona também
}
Note that in your example, the class corresponding to DateTime in Java is java.util.Date (among other options) that is not a primitive type, so you can pass null directly without any problems.

    
05.11.2014 / 19:06
2

I understand you're talking about doing this for primitive types. All Java classes accept nulls as in C #. In Java only the primitive types do not accept null, as usually occurs with the ValueTypes of C #.

C # has fixed a solution by encapsulating these types into a struct named Nullable . In it is the data you are working with and a * flag * indicating whether it is null or not, after all types by value can not have exceptional values, so extra information is needed. And the syntax of Tipo? was created which in the background is translated to Nullable<Tipo> when compiling.

There are two solutions for Java:

  • Use Integer . It is a class, it can have a null reference. Something like this:

    Integer inteiro = MetodoQualquer();
    if (inteiro  == null) {
        // faz algo
    } else {
        // faz outra coisa
    }
    
  • You can simulate this by creating a class that contains a flag indicating the condition of null and the value itself. It's a very similar form to what I gave in that answer (obviously it would not have the primitive type, not a list). That is, you are reproducing what C # Nullable does. But it does not have the Tipo? syntactic sugar that C # has. It is not a good solution because Java does not have user defined%% types), but resolves.

  • There is still an option to use the structs annotation but I believe it does not do exactly what you expect.

    I did not mention the example of @Nullable because unlike C # in Java this type is by reference, so it accepts DateTime of course.

        
    05.11.2014 / 19:07