r/javahelp • • Aug 31 '22

Unsolved Java Static

Why cannot we use System.out.println(), outside <main()> or any static function ?

0 Upvotes

7 comments sorted by

View all comments

9

u/8igg7e5 Aug 31 '22

You can invoke System.out.println() anywhere that you can use a non value returning statement, including in non-static methods, constructors appropriately typed lambda bodies or method references.

Can you explain why you think this is not the case?

1

u/kichiDsimp Sep 04 '22

If I use it withour curly braces, then it gives error If I use it with curly braces but not writing nothing before the braces, it does not give error but it does not also print

1

u/8igg7e5 Sep 04 '22

Okay. So what you're referring to is not System.out.println() specific. You're not allowed any statements directly in the class body (or outside of one).

By using the braces you're creating an 'instance initialisation block' - in which you can place statements, including instance expressions (since 'this' is defined).

This class shows some of the places you can and cannot use a statement.

// Can't be here... everything has to be insides a type (class/interface/enum/record)
// System.out.println(); 

class Foo {
    // Can't be here... Only declarations (fields, methods and blocks) are allowed here.
    // System.out.println(); 

    static {
        // Inside a static initialisation block
        System.out.println();
    }

    {
        // Inside an instance initialisation block
        System.out.println();
    }

    // This is using System.out.println() as a 'method reference' (used here in field initialisation)
    Runnable methodReference = System.out::println;

    // Inside a expression-form lambda - though of type void (used here in field initialisation)
    Runnable expressionLambda = () -> System.out.println();

    // Inside a statement-form lambda (used here in field initialisation)
    Runnable statementLambda = () -> {
        System.out.println();
    };

    Foo() {
        // Inside a constructor is fine
        System.out.println();
    }

    void someMethod() {
        // Inside a method is fine
        System.out.println();
    }

    // You can't invoke this with 'm(System.out.println())' - you can never use a void-type expression where a value is expected
    // `Void` is actually a meta-type that can't be instantiated...so this method is uncallable (outside of some significant rule-breaking).
    void m(Void v) {
    }
}