简体   繁体   中英

Simpler way to print to the console in Java?

When I was in high school, I used to do this hacky way of printing to the console in which I would define a method called say() that would allow me to not have to type System.out.println() every time I wanted to print something. It is a really simple method and looks like this:

public static void say(Object o){

System.out.println(o);

}

The only downside I can really think of is the inability to print objects that can't be converted to strings, but that problem also occurs with System.out.println(). I also know that method calls take up space on the stack, but since this isn't a recursive method, I really don't think it can have the potential to blow up the stack. If anyone has any insight on whether or not doing this is okay, please let me know!

Thanks!

Every time you print an object System.out.println(obj) or add it to a string "value is "+obj the obj.toString() method will be called and you will have a user-friendly message when you overrided this method with some internal useful information. Otherwise, you will have a message with the object package, class name, and object memory id.

Call System.out.println(obj) is really too much to only print a value in the console, I personally like to make a static import and use out.println(obj) . It is not the best option but is good enough.

Example:

 import static java.lang.System.out;

 public class PrintExample {

public static void main(String[] args) {
    MyObject obj = new MyObject(10);
    out.println(obj);
    MyObject2 obj2 = new MyObject2(10);
    out.println(obj2);
}

static class MyObject {

    final int value;

    MyObject(final int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "The value is " + value;
    }
}

static class MyObject2 {

    final int value;

    MyObject2(final int value) {
        this.value = value;
    }

}
}

Output:

The value is 10
com.cflex.mp.api.log.PrintExample$MyObject2@60285225

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM