Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Problem with java program

Name: Anonymous 2009-03-28 20:51

public class Test {

    /**
     * @param args
     */
    String szHello="hello world!";
    public static void main(String[] args) {
        System.out.println(szHello);

    }

}

I get an error when I try to compile: Cannot make a static reference to the non-static field szHello  Test.java  test/src  line.
What does this mean?

Name: Anonymous 2009-03-28 20:58

szHello is a member of the class Test, i.e.: a field that each instance of type "Test" has unique to itself.

The main method in a java program is not a member of that class, but just an indicator of the entry point into the program.

What you are trying to do with this program is print out from a static method the contents of a field. Basically, You either need to instantiate an object of type "Test" and then print out its szHello field, or make szHello a static variable so it can be referenced without needing to belong to a specific instance of a class.

i.e.:
public class Test {
    String szHello="hello world!";
    public static void main(String[] args) {
        Test instanceOfTest = new Test();
        System.out.println(instanceOfTest.szHello);
    }
}


or

public class Test {
    static String szHello="hello world!";
    public static void main(String[] args) {
        System.out.println(Test.szHello);
    }
}


Note how in the second example, the name of the class is used to access the szHello variable? This is because szHello is static now, so it belongs to the class as opposed to any particular instance of that class.

Name: Anonymous 2009-03-28 21:01

szHello is an instance variable and you can only access it inside of instance methods

you cant access inside a static method

Name: Anonymous 2009-03-28 21:24

Some people, when confronted with Java, think “I know, I'll use Hungarian notation.” Now they have two problems.

Name: Anonymous 2009-03-29 0:26

>>4
Especially when the sz prefix is usually used to indicate a size_t, not a string. (Now he has three problems).

Name: Anonymous 2009-03-29 2:53

>>5
Actually, sz is used to represent a null terminated string. Unfortunately for OP, strings in java use a length field to delimit the end of a string as opposed to null terminators.

Name: Anonymous 2009-03-29 4:04

>>1-
Back to /pr/, please.

Name: Anonymous 2009-03-30 13:48


public class Test {
  public static void main(finalString[] args) {
    System.out.println("Hello World!");
  }
}

Name: ​​​​​​​​​​ 2010-10-22 20:01

Name: Anonymous 2011-02-03 0:48

Name: Anonymous 2011-02-04 16:38

Don't change these.
Name: Email:
Entire Thread Thread List