Jump to content

Beginners quest in learning java

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
joules32

joules32

    Newbie

  • Members
  • Pip
  • 2 posts
Hi folks,
I'm very new to java and learning via some old library programming books. I'm about 1/4 into these texts and have a very simple question. In the programming examples in the beginning, they output string using the "System.out.print()" . Then later they moved to using "StdOut.print()". Seems like its 2 ways of doing the same thing. Question is how do you know which to use and when? Ok, you may destroy me now...

#2
G_Morgan

G_Morgan

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 537 posts
There is no StdOut class in the JRE. I suspect your tutorial binds System.out to a StdOut variable so that it can call print without typing out the System.out bit. This is poor practice and it should use a static import instead.

Anyway check for a line that looks something like

PrintStream StdOut = System.out;

If that exists it means they have bound the System.out stream to a local variable. If that is the case then they are both equivalent and frankly it is unneeded. I'd use a static import.

import static System.out;

Then you can call 'out.print()'.

#3
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
Why is that a bad practice?

I didn't know you could do that.

Is is better to do the static import or just type System.out.println()?

#4
G_Morgan

G_Morgan

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 537 posts

chili5 said:

Why is that a bad practice?

I didn't know you could do that.

Is is better to do the static import or just type System.out.println()?

Because it's basically rebinding the API into your class. It creates additional code in your class that does nothing. Also what used to happen is people would create a giant class with all their favourite functions bound into it and would always inherit from it while writing their classes. A static import means you don't have a single gigantic base class or a mess of extra variables only used for simplifying function calls.

I'd call the long version unless you do so often. The static import system is only to stop the two issues mentioned above.

#5
joules32

joules32

    Newbie

  • Members
  • Pip
  • 2 posts
ahh, i see. Thanks so much for your reply and clarifying this.

#6
G_Morgan

G_Morgan

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 537 posts
It's also worth noting this isn't just aesthetics. When we talk about accessing everything through a shared base class it amount to a massive amount of indirection. With Java already suffering from too many layers of indirection it doesn't make sense to add more.