简体   繁体   中英

If you pass an exception into Java's `System.out.println`, what happens?

In java, we normally pass strings as input to System.out.println
What happens if you try to input something weird, such as an instance of the Exception class?

class Main {
    public static void main(String[] args]) {
        System.out.println("printing a string is perfectly normal");
        Exception e = new Exception();
        System.out.println(e);
    }
}      

What datatypes are allowed as input to System.out.println ?
What happens if you attempt to print an instance of a class which System.out.println is not overloaded for?

It calls the overloaded method with the Object parameter, which looks like this:

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
          print(s);
          newLine();
    }
}

This essentially prints "null" if the object is null and will print the result of calling .toString on the object otherwise.

What datatypes are allowed as input to System.out.println?

Anything.

What happens if you attempt to print an instance of a class which System.out.println is not overloaded for?

There is an overload for Object, and its documentation says what happens: for the argument x , a call to String.valueOf(x) is made, and the result is printed.

And if you read the documentation for that , it says that x.toString() will be called for non-null x .

In short, all objects have an accessible toString() method, and that is what determines what is printed.

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