Java out.println() how is this possible?

前端 未结 9 1421
难免孤独
难免孤独 2020-12-08 13:42

I\'ve seen some code such as:

out.println(\"print something\");

I tried import java.lang.System;

but it\'s not working

相关标签:
9条回答
  • 2020-12-08 13:49

    @sfussenegger's answer explains how to make this work. But I'd say don't do it!

    Experienced Java programmers use, and expect to see

            System.out.println(...);
    

    and not

            out.println(...);
    

    A static import of System.out or System.err is (IMO) bad style because:

    • it breaks the accepted idiom, and
    • it makes it harder to track down unwanted trace prints that were added during testing and not removed.

    If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.

    0 讨论(0)
  • 2020-12-08 13:51

    simply import :

    import static java.lang.System.*;
    
    0 讨论(0)
  • 2020-12-08 13:52

    You will have to create an object out first. More about this here:

        // write to stdout
        out = System.out;
        out.println("Test 1");
        out.close();
    
    0 讨论(0)
  • 2020-12-08 13:52

    you can see this also in sockets ...

    PrintWriter out = new PrintWriter(socket.getOutputStream());
    
    out.println("hello");
    
    0 讨论(0)
  • 2020-12-08 13:53

    Well, you would typically use

    System.out.println("print something");
    

    which doesn't require any imports. However, since out is a static field inside of System, you could write use a static import like this:

    import static java.lang.System.*;
    
    class Test {
        public static void main(String[] args) {
            out.println("print something");
        }
    }
    

    Take a look at this link. Typically you would only do this if you are using a lot of static methods from a particular class, like I use it all the time for junit asserts, and easymock.

    0 讨论(0)
  • 2020-12-08 13:57
    PrintStream out = System.out;
    out.println( "hello" );
    
    0 讨论(0)
提交回复
热议问题