In Java, how would I do the following:
Foo bar = new Foo();
Foo a = bar;
Foo b = bar;
bar = null;//will only set bar to null. want to set value of bar to null rather than the reference to null.
Is it possible to set the variables bar
, a
and b
(all are a reference to bar
) to null only with access to bar? If so, could somebody please explain how to do so.
To set all values in an object to null , pass the object to the Object. keys() method to get an array of the object's keys and use the forEach() method to iterate over the array, setting each value to null . After the last iteration, the object will contain only null values.
A reference isn't supposed to be null. The variable must be initialized to a non-null value. The variable can never be assigned the value null . The compiler issues a warning when code assigns a maybe-null expression to a variable that shouldn't be null.
In order to set object values to null, you need to get all the keys from the object and need to set null. You can use for loop or forEach() loop.
Javascript. The null can not be assigned to undefined type variables: Javascript.
No, it is not possible in Java.
I a little explain what happened in your code.
Here Foo bar = new Foo();
you created object of Foo
and put reference to the variable bar
.
Here Foo a = bar;
and Foo b = bar;
you put the reference to the variables a
and b
. So you have now one object and three variables pointing to him.
Here bar = null;
you clear the bar
variable. So you have two variables (a
and b
) pointing to the object and one variable (bar
) without reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With