1

I am in a stage of transition from C# to Java.

I remember in C# we can call a nullable method with or without passing arguments. for example in C#

C#

    public void method (int? x){
logic goes here
}

I can call the above method like this without passing any parameters in c#

method();

how to do it in Java?? In Java, it's forcing me to call the method by passing an argument, if there is no argument it's forcing me to at least pass a null. my problem here is I want to edit an existing method, but this method was called at many places, so I need to edit in many places which is frustrating.

Java

    public void method (Integer x){
logic goes here
}

method(null);
  • 1
    Your C# example is wrong. You can't call `public void method (int? x)` with no parameters unless you provide a default value for `x` in the call signature (`public void method (int? x = null)`). – Flydog57 Sep 20 '19 at 16:23

2 Answers2

4

If you don't want to edit existing uses of a method, you can add a new method that calls the existing one:

public void method() {
    method(null);
}
jalynn2
  • 6,397
  • 2
  • 16
  • 15
2

You complete C# example would look like this:

public void method (int? x = null){ }

which would mean using default value null for method parameter x. Java does not support default parameter values.

What you can do (and you sometimes do) instead is:

public void method (Integer x){ }

public void method(){
  method(null);
}

Though in my opinion this is not the best design, as passing null is implicit and no parameters in the method() would suggest there are actually not parameters needed.

madreflection
  • 4,744
  • 3
  • 19
  • 29
syntagma
  • 23,346
  • 16
  • 78
  • 134