saltandwater saltandwater - 5 months ago 10
Java Question

Does a non-static variable in a non-static method correspond to that of the object?

Please see below, where I have created an object for the class, and used the method nonstaticMethod to change the value of a non-static integer variable. I'm able to do this without the use of 'this' keyword?

Is nonstaticVariable inside nonstaticMethod same as this.nonstaticVariable ?

package lastcommon;

public class Check {

int nonstaticVariable = 100;

public static void main(String[] args) {
Check obCheck = new Check();

obCheck.nonstaticMethod();
}

void nonstaticMethod()
{
nonstaticVariable = 200;
System.out.println(nonstaticVariable);
}
}

Answer

Yes. nonstaticVariable = 200; is short for this.nonstaticVariable = 200; you can see this by printing it after the method call like,

public static void main(String[] args) {
    Check obCheck = new Check();
    obCheck.nonstaticMethod();

    System.out.println(obCheck.nonstaticVariable);
}
Comments