-5

I was wondering if there was a difference between these two e.g.

System.out.println("Hello World");

and

println("Hello World");

I know they print the same thing, but is there anything different? (I'm new to java, so I don't know so far)

In other words, does the "System.out" change anything?

Randy Huang
  • 113
  • 1
  • 3
  • 11

2 Answers2

3

Yes, there is a difference, because they are not calling the same method.

Assuming the second statement actually compile, it means that the println("Hello World") call is for a method that is either:

  • defined in your class
  • inherited from a super class
  • a default method inherited from an interface (Java 8+)
  • statically imported1

Now, the local/inherited/imported println(String s) method could just have been implemented to call System.out.println(s), which would make it behave the same as the direct call to System.out.println(s), but that's different.


1) Since you cannot statically import java.lang.System.out.println() (it is not a static method), it would have to be statically imported from some other class.

Andreas
  • 154,647
  • 11
  • 152
  • 247
2

You might have a local method called println or a static import. So:

private void println(String str) {
    //
}

or

import static java.lang.System.out;

but then it'd have to be:

out.println("bla bla");

If you are using an IDE, try to open its declaration (F3 in Eclipse) and see where it takes you.

Eugene S
  • 6,709
  • 8
  • 57
  • 91
  • Sorry, i mean the function println() – Randy Huang Jun 17 '16 at 01:18
  • 1
    @RandyHuang those are methods, java prefers to call them method. – Bálint Jun 17 '16 at 01:39
  • If you static import `System.out`, you'd have to write `out.println()`, so that's obviously not what's going on. As for the local method, in order for `println("Hello World")` to work, the method would have to take a `String` parameter. – Andreas Jun 17 '16 at 01:54
  • @Andreas 1)No, I won't. 2)Added a string as parameter. – Eugene S Jun 17 '16 at 01:59
  • `import static java.lang.System.out` only means that you can reference `out` without qualification. It does *not* add `println()` to the namespace. Compile error: *The method println(String) is undefined* – Andreas Jun 17 '16 at 02:01