Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Java, non main class cant call certain functions?

Why is it that outside the main class, i cannot call System.out.prinln() without putting it inside a method.

A simple but detailed explanation would be appreciated!

1 Answer

Paolo Bass
Paolo Bass
3,921 Points

Hi behar,

When you mention 'main class', I assume that you are talking about this:

public static void main(String[] args){}.

This is not a class. It is a method (or function if you rather), as indicated by the 'void' rather than a 'class'. You can only call code from inside of a method, and System.out.println() is a call to a method called println(). This is the case with ALL methods, not just the println() method.

The reasoning for this is that, outside of a method, no code will run. Think of methods as a sort of chain reaction. All methods can only be called from inside of another method, and the chain starts from the 'main method'. Therefore, calling any method in a location that is outside of another method will result in it never running, as it can never be reached from the main method (which is the starting point of the program), and the computer doesn't know when to call it.

Certainly, you can create and initialise variables from outside of methods, however this code only ever runs once, when the program first starts. It doesn't need timing specificity. It therefore doesn't need to be called in a certain order and it never has to be called again, hence the reason why it does not need to be located inside of a method.

Of course, you can create and initialise variables from inside methods, and doing so will indicate that those variables are needed during specific points in the 'method chain'.

I hope this helped.