Passing parameter null to a method

Asked

Viewed 2,748 times

2

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

In C# I know it is possible using ? in kind.

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

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

  • It works the same way, but if you assign the value of "example" to something inside the function will throw you an exception.

  • @Jorgeb. Answer the question.

2 answers

2


If you have used the primitive types (int, boolean, long, char, etc.) in the parameter, so you cannot pass null for 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) which is not a primitive type, so you can pass null directly smoothly.

  • Thank you, it’s all right.

2

I understand that you are talking to do this for primitive types. All Java classes accept nulls as in C#. In Java only primitive types do not accept null, as is usually the case with ValueTypes of the C#.

C# found a solution encapsulating these types in a struct calling for Nullable. It contains the data you are working on and a * flag* indicating whether it is null or not, after all types by value cannot have exceptional values, so extra information is required. And the syntax of Tipo? which is ultimately translated into Nullable<Tipo> when compiling.

There are two solutions for Java:

  1. 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
     }
    

I put in the Github for future reference.

  1. It is possible to simulate this by creating a class that contains a flag indicating the condition of null and the value itself. It is a form very similar to what I gave in that reply (evidently it would not have the primitive type and not a list). That is, you are reproducing what the Nullable do C# faz. But it does not have the Tipo? that C# has. Not such a good solution because Java does not have structs (value types) user-defined, but solves.

There is still the option to use the annotation @Nullable but I believe you don’t do exactly what you expect.

I did not cite the example of DateTime because unlike C# in Java this type is by reference, so it accepts null naturally.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.