0

I want to make a method where parameters might be empty or filled. How to do that (what to use?)

public static void Main() {
    someMethod("John");
    someMethod(10);
}

static void someMethod(String name, int age) {
    System.out.println(name, age);
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
Clickonme
  • 1
  • 1

2 Answers2

1

You have to provide method overloads, that means the same method with different parameters:

static void someMethod(String name, int age) {
    System.out.println(name + ": " + age);
}

static void someMethod(String name) {
    System.out.println(name);
}

static void someMethod(int age) {
    System.out.println(age);
}

Then you can do this:

public static void main(String[] args) {
    String john = "John";
    int ten = 10;

    someMethod(john, ten);
    someMethod(john);
    someMethod(ten);
}

By the way, the line System.out.println(name, age); will not compile...

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • 1
    Thank I'll try that out! About sout part - yeah I got what your mean, just wanted to show the idea what I want to – Clickonme Oct 30 '19 at 08:36
0

One way, instead of using primitive(int) use Integer or Long, etc. You can pass these params as null for which you don't want to pass the value and check if it's non-null then only print. Other way is that you will have to pass same type of variable with multiple numbers like

static void someMethod(String... var) {
     for(String x : var){
         System.out.println(x);
     }
}

or you can also pass a map containing key-value and just iterate over it and print it. So there can be multiple ways to solve this.