Search code examples
javaobjectmethodsstaticinstance

How to edit instance variable from inside a method? non-static variable sum cannot be referenced from a static context


public class Sum{

    int sum = 0;

    public static void sum_do(String array[]){
        int tmpi = 0;
        for (int i=0; i<array.length; ++i){
            tmpi = Integer.parseInt(array[i]);
            sum += tmpi;
        }
    }
}

I'd like to modify sum variable, but I am unable to do that.

./Sum.java:9: error: non-static variable sum cannot be referenced from a static context
                        sum += tmpi;
                        ^
1 error

I'm really new to Java, so this is probably some very easy stuff


Solution

  • you try to reach a non-static var in a static context, try:

    static int sum = 0;