Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does System.out.println have to be inside a method?

Tags:

java

class Employee {    
    int DOB;
    int eid;
    String name;
    double salary;
    System.out.println("Employee class");
}

If I write the System.out.println inside a method,it seems to work. But not when written directly inside a class. Why is a method necessary?

like image 382
user2261650 Avatar asked Dec 01 '22 21:12

user2261650


1 Answers

It's the same as any other code that gets executed - it has to be inside a method! (Yes, ish, for the purists, I'm also including constructors and static / instance initialiser blocks.) Think about it - if it wasn't inside a method or other related code block as you propose, then when would that code get executed? It wouldn't make much sense. You can't execute a class per-se, you can only execute a specific method / constructor / etc. contained within that class.

The only things allowed outside method and constructor declarations are declarations of fields. Since System.out.println() is not a field declaration, it's not allowed.

like image 112
Michael Berry Avatar answered Dec 09 '22 13:12

Michael Berry