-1
class Test {
    int a = 100;
    System.out.println(a); 
}
class Demo {
    public static void main(String args[]) {
        Test t = new Test();
    }
}

I'm new to programming. I found this code when I'm practicing. I don't understand why I'm getting this error.

Here is the error I'm getting.

Demo.java:3: error: <identifier> expected
 System.out.println(a);
                   ^
Demo.java:3: error: <identifier> expected
 System.out.println(a);
                     ^
2 errors
Compilation failed.

Can you guys explain why I'm getting this error?

Dhanuka
  • 2,826
  • 5
  • 27
  • 38

2 Answers2

1

You can't call a method directly from the java class body.

Create a constructor in your Test class, and put the print in it :

class Test {
    int a = 100;

    public Test() {
        System.out.println(a); 
    }
}

Note that if for some reason you really want a statement to be executed when the class is loaded without using a constructor, you can define a static block, here an example :

class Test {
    static int a = 100;

    static {
        System.out.println(a); 
    }

}

However, this is just for reference and really not needed in your case.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • Yes, it's because the code needs to be in a method or constructor. But note that adding code with side effects (like printing things to the screen) to constructors is not a good practice. – user253751 Feb 08 '15 at 04:18
  • @DhanukaLakshan I am not one of the people who downvoted your question. – user253751 Feb 08 '15 at 04:28
0

From Declaring Classes in the Java tutorial:

In general, class declarations can include these components, in order:

  1. Modifiers such as public, private, and a number of others that you will encounter later.

  2. The class name, with the initial letter capitalized by convention.

  3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.

  4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.

  5. The class body, surrounded by braces, {}.

You can't make any function calls outside of a method declaration.

Community
  • 1
  • 1
user2752467
  • 864
  • 5
  • 16