I am having problems understanding the way non-static variables are handled. I chose to work with an array so that it is easy to retrieve its memory address.
Consider the following code:
public class tryClass
{
int[] v = {0}; // vector v is non-static (and NOT local to any method)
tryClass obj;
public void met ()
{
obj = new tryClass();
obj.v[0] = 30;
v[0]=3;
}
public static void main (String[] args)
{
tryClass obj = new tryClass(); // is this the SAME object as in met() ?
int[] v = new int[1];
obj.v[0] = 40;
obj.met();
}
}
In order to know at each step how vector v
is handled I filled the code with some println
instructions and my ouput is as follows:
In main(), BEFORE running met()
obj.v[0] = 40
obj.v = [I@78456a0c
INSIDE method met()
obj.v[0] = 30
v[0] = 3
obj.v = [I@15357784
v = [I@78456a0c
In main(), AFTER running met()
obj.v[0] = 3
obj.v = [I@78456a0c
I am very puzzled by many things, the first of which is why the reference of obj.v
when called in static method main()
is the same as that of v
inside non-static method met()
. Besides, what exactly is v
when called with no object (in a non-static context, of course)?
I am new to Java and I really have an infinity of questions, I hope an answer can solve them altogether... Thanks in advance for your help.
For the sake of completeness, the full code is
public class tryClass
{
int[] v = {0};
tryClass obj;
public void met ()
{
obj = new tryClass();
obj.v[0] = 30;
v[0]=3;
System.out.println("\nINSIDE method met()");
System.out.println("\tobj.v[0] = "+obj.v[0]);
System.out.println("\tv[0] = "+v[0]);
System.out.println("\tobj.v = "+obj.v);
System.out.println("\tv = "+v);
}
public static void main (String[] args)
{
tryClass obj = new tryClass();
int[] v = new int[1];
obj.v[0] = 40;
System.out.println("In main(), BEFORE running met()");
System.out.println("\tobj.v[0] = "+obj.v[0]);
System.out.println("\tobj.v = "+obj.v);
obj.met();
System.out.println("\nIn main(), AFTER running met()");
System.out.println("\tobj.v[0] = "+obj.v[0]);
System.out.println("\tobj.v = "+obj.v);
}
}