java - Passing object reference to a method -
this question has answer here:
if employee reference made null in changedetails(), variable id value retained , nullpointerexception not thrown (code 1) may because pass copy of object's reference, in code 2 why variables value has changed
code 1:
public class javapassing { public static void changedetails(employee e) { e=null; } public static void main(string args[]) { employee emp = new employee("vishal",7); changedetails(emp); system.out.println(emp.id); } }
code 2:
public class javapassing { public static void changedetails(employee e) { e.id=9; } public static void main(string args[]) { employee emp = new employee("vishal",7); changedetails(emp); system.out.println(emp.id); } }
-------- -->| object |<-- b -------- a.id = 10; // property of object modified b.id = 10; // property of object modified here b = null ; // b set null -------- -->| object | b (reference null) --------
here when set b
null
, a
not modified continue point object
in heap.
and why not throw nullpointerexception
if access id
reference a
. confused between reference of object , object in memory.
in case, a
emp
, b
e
.
Comments
Post a Comment