memory - Are non-static fields static until they're changed in Java? -
let's consider following code:
public class testing { static int = 47; public static void main(string[] args) { testing t1 = new testing(); testing t2 = new testing(); system.out.println(t1.i == t2.i);
i'm creating static field belonging testing class , field shared among 2 instances of class t1
, t2
well. test if reference same value in memory , indeed, do, result true. , that's clear me.
however, if delete static keyword declaration of int i
, unexpected happen.
public class testing { int = 47; public static void main(string[] args) { testing t1 = new testing(); testing t2 = new testing(); system.out.println(t1.i == t2.i);
i expect 2 instances t1
, t2
both have 47 value of field fields in different memory addresses. surprisingly, when test t1.i == t2.i
true in case - why? field int = 47;
not static anymore expect in different memory addresses every instance of class equality yields true.
an int
primitive type, not reference type. condition t1.i == t2.i
not test reference equality -- there no reference in first place here. compares values , in case, both have value 47
.
if had member field not primitive, result different, example:
public class testing { integer = new integer(47); public static void main(string[] args) { testing t1 = new testing(); testing t2 = new testing(); system.out.println(t1.i == t2.i); // false } }
in case, each instance has different reference integer
object created using new
keyword invokes constructor, , condition t1.i == t2.i
compares these 2 references.
Comments
Post a Comment