This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
If the Employee reference is made null in the changedetails(), variable id value is retained and NullPointerException is not thrown (Code 1) may be because we just pass a copy of object's reference, but in Code 2 why the 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);
}
}
In both cases Reference 'e' in changedetails() and 'emp' in main() both point to same object.
In code (1)
In changedetails() when you make e=null; ONLY e STOPS POINTING TO OBJECT. BUT emp CONTINUES TO POINT TO OBJECT. So in main() when you do emp.id value prints and no NullPointerException
In code (2)
In changedetails() when you make e.id=9 remember Both References are pointing to same object i.e.
'e' in changedetails() and 'emp' in main() point to same object ....
So e.id=9 means change made on same object hence when you do emp.id in main() value is 9
In java references to objects are passed by value.
So,
public static void main(String args[])
{
Employee emp = new Employee("Vishal",7);
changedetails(emp); / /object Employee ahs only one reference - "emp"
System.out.println(emp.id);
}
public void changedetails(Employee emp1){ // here both emp1 and emp of main() point to the same Employee object.
emp1.setId(100); // now since emp1 also points to same Employee object, the data will be changed.
emp1 = null;// now emp1 points to null. So, only emp is pointing to E,ployee
}
--------
A -->| Object |<-- B
--------
A.id = 10; // Property of object modified
B.id = 10; // Property of object modified here also
B = null ; // B is set to null
--------
A -->| Object | B (reference is null)
--------
Here when you set B to null, A is not modified it will continue to point the Object in heap.
And that is why it will not throw NullPointerException if you will access id from reference A. All you are confused is between reference of Object and Object in memory.
In your case, A is emp and B is e.
You can find some good explanation in this question.
The argument you pass into the method changedetails() is a variable of its own, different from the variable emp in your main() method. They both refer to the same eployee so. Hence if you refer to the employee and change its state, the change is visible in both methods, changedetails() and main(). But if you assign null to the argument variable of the method changedetails() this is a local change visible only in that method.
Sidenote: it is considered bad practice to change the value of method arguments. And after leaving the method changedetails(), the method arguments are gone, because they live on the stack and not on the heap.
Related
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 2 years ago.
Please see my code below. I have a functional interface IFace with a method. I'm creating an implementation using Method reference from a class instance of Test. Can anyone tell me how the interface still refers to the instance method even if the reference is nullified? or reference is changed...?
public class Test {
private int intVar;
public Test() {
intVar = 123;
}
public Test(int intVar) {
this.intVar = intVar;
}
public void myInstanceMethod() {
System.out.println("Hello from instance: " + intVar);
}
public static void main(String[] args) {
Test t = new Test();
IFace i = t::myInstanceMethod;
i.method(); // Hello from instance: 123
t = null; // Nullifying the reference
i.method(); // Hello from instance: 123
// Why still executing the method if reference is nullified?????
t = new Test(456);
i.method(); // Hello from instance: 123
// Why not Hello from instance: 456 ??????
}
static interface IFace {
void method();
}
}
In a sense, the question is similar to asking why printing b does not output null in the following program:
String a = "abc";
String b = a;
a = null;
System.out.println(b);
When IFace i = t::myInstanceMethod; finishes running, i has captured a reference to the object that t points to at this time. That reference is independent from the variable t. Look at it like i, the method reference, has its own variable pointing to the same object.
The memory is not freed when you nullified the reference. It's freed when ALL references are gone. By passing method reference you created new reference to object itself, so the ref count is 2 at that point, i.e. the i holds reference to t underneath
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
In Java, object reference is used for call by reference and variables are used for call by value.
Here’s an example:
class Foo{
int x;
int y;
}
public class CallByRef {
public static void main(String[] args) {
Foo foo = new Foo();
foo.x=5;
foo.y=10;
System.out.println(foo.x+", "+foo.y);
getFoo(foo);
System.out.println(foo.x+", "+foo.y);
}
static void getFoo(Foo f){
f.x=2;
f=new Foo();
f.x=10;
}
}
Output:
5, 10
2, 10
Why this is happend?
x should be 10 as I modified its value with f.x=10
Is it correct that f=new Foo() will create new object in heap and not point to prevoise reference?
In method getFoo, variable f is a local variable.
When you call getFoo(foo) from main, this variable indeed refers to foo.
But once you set f = new Foo(), it refers to a different object.
Therefore, at that point, changing f.x does not affect foo.x.
Here is a basic description what happens in your case as an example
// Creating a new object of Foo
// The variable foo now stores a VALUE!!! to the memory where the
// Instance of foo is stored
Foo foo = new Foo();
// accesing the instance of Foo over the value to the reference in the memory
// and set x to 5
foo.x = 5
// accesing the instance of Foo over the value to the reference in the memory
// and set y to 5
foo.x = 10
// Print out x and y of the instance of Foo where the value of the reference to memeory points to
System.out.println(foo.x+", "+foo.y);
now to what get Foo does
// The instance f of Foo holds the value to the reference in the memory
// Lets call it 1234567 as example
static void getFoo(Foo f){
// The object in the memory 1234567 is going to have x changed
f.x=2;
// The VALUE of the reference is changed, lets say it now refers to the memory 123456789 where a new instance of Foo is stored now
f=new Foo();
// The object in the memory 123456789 is going to have x changed
f.x=10;
}
Lets go back to your last output and what it does print now
// So in your getFoo() Call your first action was to change the value of x
// on the object with the value to the reference which you gave as a parameter
// hence it prints 2
// The new instance of the Object Foo that is stored somewhere else in the memory should be garbage collected soon, since no variable actually holds the VALUE to the reference anymore
System.out.println(foo.x+", "+foo.y);
The most import part to understand is, that the references to the object in a variable or parameter are actually stored as values to the memory. Due to this your getFoo() method simply changes the value of the reference to the instance of the object, but can never change the reference itself
I think first case is clear for you, ie the value 5,10.
After that by calling getFoo() method and passing the same object foo is passing as argument. And in getFoo() method the instance variable value of the same object(foo) is changed to 2. But after that it s creating new object using new keywork and assigning another value.
ie.
foo => x=2(new value) and y=10(not changed, so it takes old value)
f => x=10 and y=0(not assigned)
And you are printing foo's values.
Hence the result 2,10
In the following code why output is 0 42 42 rather than 0 0 42.
In Java object is not passed by reference so why value of t.x was modified to 42?
class Two
{
byte x;
}
class PassO
{
public static void main(String [] args)
{
PassO p = new PassO();
p.start();
}
void start()
{
Two t = new Two();
System.out.print(t.x + " ");
Two t2 = fix(t);
System.out.println(t.x + " " + t2.x);
}
Two fix(Two tt)
{
tt.x = 42;
return tt;
}
}
Because what's being passed around in Java is the value of the pointer to the object. Thus when you do tt.x=42, you are changing the original t.x to have a value of 42. And when you return tt you are actually returning the same pointer, so infact t and t2 point to the same instance of the object.
In Java object is not passed by reference so why value of t is
modified to 42?
The value of t is not modified to 42. t.x is modified to 42.
Java is always pass-by-value. The difficult thing to understand is
that Java passes objects as references and those references are passed
by value.
Yes it is passed by value. The value is the reference. t is a pointer to a new Two(). You pass the value that t is referring too and point to it with tt.
Your method fix is not really testing passed by value adherence. If you were really testing for passed by value adherence the method should be something like below:
Two fix(Two tt)
{
// Create a brand new instance of Two
Two newTwo = new Two();
newTwo.x = 42;
// Assign the new reference to the passed in value.
tt = newTwo;
return tt;
}
In your original fix method you are just mutating the passed in object.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
So as far as I know, in java you can't access objects directly, you only have the pointer to it. So for example I have this code:
public class App {
public App() {
Thing t = null;
doStuff(t);
System.out.println(t);
}
public void doStuff(Thing a) {
a = new Thing();
}
public static void main(String[] args) {
new App();
}
}
class Thing { }
And the output is null. Why? I've passed the pointer to a method which gave it a new Thing instance to point to. Is it because it's a new pointer? Also how can I resolve it without returning anything from doStuff()?
You have references not pointers, and a method cannot update the callers reference without an assignment in the caller - so this
public App() {
Thing t = null;
doStuff(t);
System.out.println(t);
}
public void doStuff(Thing a) {
a = new Thing();
}
Would work if you did,
public App() {
Thing t = null;
t = doStuff(t);
System.out.println(t);
}
public Thing doStuff(Thing a) {
a = new Thing();
return a;
}
This is because Java works by pass by value of Object references and not pass by reference of an Object ,even if the reference is an Object,it still gets passed by the value of reference.So you always work with new references
Refer:http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
Declaring a Variable to Refer to an Object
Previously, you learned that to declare a variable, you write:
type name; This notifies the compiler that you will use name to refer
to data whose type is type. With a primitive variable, this
declaration also reserves the proper amount of memory for the
variable.
You can also declare a reference variable on its own line. For
example:
Point originOne; If you declare originOne like this, its value will be
undetermined until an object is actually created and assigned to it.
Simply declaring a reference variable does not create an object. For
that, you need to use the new operator, as described in the next
section. You must assign an object to originOne before you use it in
your code. Otherwise, you will get a compiler error.
A variable in this state, which currently references no object, can be
illustrated as follows (the variable name, originOne, plus a reference
pointing to nothing):
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static fields on a null reference in Java
I am new to Java. I know if any object point to and if we try to perform any operation on that object, a Nullpointer exception is thrown by JVM. But in my case there is no Nullpointer exception please help me ?. Below is my code
public class Employee
{
public static String empName = "John"
public static void main(String args[])
{
Employee emp = new Employee();
emp = null;
System.out.println(emp.empName);
}
}
It prints John as output even emp object is pointion to null. But I am expecting a nullpointer exception.
because field is static.
In your case emp.empName equals to Employee.empName
Since you are accessing a static variable, so you will not get NPE if your reference is referencing null. This is because static fields are bound to class rather than any instance.
So, for static variable: -
Employee emp = null;
emp.empName; // This is evaluated as `Employee.empName;`
So, only the reference type is used. Regardless of whether that reference is pointing to null, or any subclass object.
As empName is static the call would be Employee.empName in the byte code, Thus no NPE:
original Code: System.out.println(emp.empName);
Byte code: GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
GETSTATIC oops/Employee.empName : Ljava/lang/String;