Andrew Andrew - 3 months ago 24
Java Question

Getting error cannot resolve symbol 'println'

I just started to learn Java and i faced with this error;

Cannot resolve symbol 'println'

I'm using Intellij IDEA 14.1.6

package Java_String;

public class NewString {
private String str = "Hello World";
System.out.println(str);

}


Working method:

public class NewString {
public static void main(String[] args) {
String name = "Hello World";
System.out.println(name);
}

}


Can you please explain why it's not working without main method.

Answer

In java you can't write syntax into a class. You need to write the code into a method like the main(String args[]) method.

For you it would work using following:

package Java_String;

public class NewString {
    private static String str;

    public static void main(String s[]) {
        str = "Hello World";
        System.out.println(str);
    }
}

The method main(String[]) in java gets called when a program starts, so this will execute when your application starts.