Search code examples
javaargumentsparameter-passingvoidtypeof

Passing System.out.println(); as an argument in a method


I want to pass System.out.println(); as an argument but the compiler won't allow me to return a void type as an argument. here is what I want it for.

public class Array {

    public static void main(String args[]) {
        a(data());
    }

    static void a(e) {
        System.out.println(e);
    }

    static void data() {
        ...
    }
}

So What is want a(data()); to look like after it is compiled is something like this.

a(data()) = System.out.println(data(){...});

Eventually I want to shorthand System.out.println().


Solution

  • What you are doing here is not passing System.out.println() as an argument; you are trying to pass an argument to System.out.println()

    Try changing the return type of data() to String, or int, or anything other than void, and return something of that type from it.

    Also change the parameter type of e in the function definition of a() to match the return type of data().

    After you make these changes, calling a(data()); will actually print something out.

    Example:

    public static void main(String args[]) {
        a(data());
    }
    
    // shorthand for System.out.println
    static void a(String e) {
        System.out.println(e);
    }
    
    // a method that returns some data
    static String data() {
        // replace this with whatever actual data you want to return
        return "This is some data...";
    }