This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
I am a beginner in Java, recently faced such an interview question on Java String concept:
public class Test1 {
public static void changeStr(String str){
str="welcome";
}
public static void main(String[] args) {
String str="1234";
changeStr(str);
System.out.println(str);
}
}
I think the output should be "welcome", however, I tested it in Eclipse, it showed "1234", isn't Java string is a reference, so the Java string "str" references gets changed to "welcome" in method changeStr?
Pardon me for the beginner question!
The object's reference is passed to the method and assigned to the parameter, which is a kind of local variable.
Assigning a different object reference to the parameter does nothing to the variable outside the method that held a reference to the original object.
Also String is immutable, so there's no way to change its value (for example a setValue() method).
The line str = "welcome"; doesn't change the value of any String - Strings can never change their values. What it does is it makes one reference point to a different String. But the reference that it reassigns is the one that's local to changeStr, not the one that is declared in main.
String is a reference, but the key is that String str inside changeStr is a different reference than str in main. Add that to the fact that strings are immutable in Java (meaning that when you change a String, the reference points to a different location in memory) and that explains why main will print 1234
Consider the following example:
public static void main(final String[] args) throws Exception {
final StringHolder holder = new StringHolder("old value");
System.out.println(holder);
reassignHolder(holder);
System.out.println(holder);
changeVal(holder);
System.out.println(holder);
}
static void reassignHolder(StringHolder holder) {
holder = new StringHolder("new value");
}
static void changeVal(StringHolder holder) {
holder.setVal("new value");
}
static class StringHolder {
private String val;
public StringHolder(String val) {
this.val = val;
}
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
#Override
public String toString() {
return "StringHolder{" + "val=" + val + '}';
}
}
In Java references are passed by value and (almost) everything is an object reference.
Here we have a mutable object that holds a String - a StringHolder.
When we call reassignHolder what we actually do is copy our object reference and pass it to the method. When the method reassigns the reference nothing happens to our original reference as we are passing a copy.
When we call reassignHolder we also pass a copy of our reference, but the method uses this reference to call a method on our object to change its val variable. This will have an effect.
So the output is:
StringHolder{val=old value}
StringHolder{val=old value}
StringHolder{val=new value}
As String is immutable, you can only carry out the first example rather than the second.
The logic here is that the str value that is passed is passed as a copy of reference of str. This implies that any change in str will not be reflected in the original str.
This situation is similar to pass by value (but of references!)
However in your code if you change the code to str = new String("welcome"); It will change the original str string by making it reference a new copy that was created.
Hope this clears things for you.
Related
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
Please explain me why am i getting an output
1234567 7654321
I want to know what exactly is happening here.
public static void main(String[] args) {
Date date = new Date(1234567);
m1(date);
System.out.print(date.getTime() + " ");
m2(date);
System.out.println(date.getTime());
}
public static void m1(Date date) {
date = new Date(7654321);
}
public static void m2(Date date) {
date.setTime(7654321);
}
What you do in m1 is make the variable date point at a new object. But this variable exists only inside the scope of the method m1. The date variable inside your main method is a different one.
This is your code just with renamed variables
public static void main(String[] args) {
Date var1 = new Date(1234567);
m1(var1);
System.out.print(var1.getTime() + " ");
m2(var1);
System.out.println(var1.getTime());
}
public static void m1(Date parameter) {
parameter = new Date(7654321);
}
public static void m2(Date parameter) {
parameter.setTime(7654321);
}
As you can see your method m1 only changes the value of parameter, not of the original var1. This method doesn't access the object which the variable parameter is pointing at but instead makes the variable point at a new object which has nothing to do with the object which was passed from var1.
m2 is not creating a new object. It is accessing the object which the variable parameter points at and calls the setTime(...) function to change attributes of the object. Since the object of parameter and var1 is still the same here, var1 later references the object which has been modified and the changes are "visible" to you.
It is a common miss assumption of young oop developers that objects and variables are one and the same. Objects are instances of classes created into the ram of your computer. Variables are just simply referencing those objects (accessing them through their memory address) and reading/writing from their memory. The same object can be referenced by multiple variables tho
// here both variables are pointing at the same object
Date var1 = new Date();
Date var2 = var1;
// this change is done to one object, referenced by both variables
var1.setTime(180128);
// Since both point at the same object, the output is exactly the same
System.out.println(var1);
System.out.println(var2);
// now we point var2 at a different object, the same one as var3
Date var3 = new Date();
var2 = var3;
// Var1 will still be the same as before. But var2 will match var3
System.out.println(var1);
System.out.println(var2);
System.out.println(var3);
So you see variables are not the same thing as objects. And a parameter of a method is also just another variable which points at the object that was passed to the method when it was called. Changing the object it is pointing at does not do any changes to the object it originally was pointing at.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
OK, here is the thing. I have multiple pointers to an object and I want to remove both of them. I have simplified it, below, so don't bother asking why on earth I would try the thing below :)
String first = "ASSIGNED";
String second = test;
second = null;
System.out.println(first);
In the example above, the output still results in "ASSIGNED". However, I want first to be no longer assigned. In the example above, it is easy, by setting it to null, but in my real example, this is not possible (first being passed into a method, where I want to remove the assingment).
EDIT:
So, I guess the question is, if it is possible to remove all pointers to a given object.
Apparently it was a bit vague what I was asking, so let's try to give a better example:
String first = "Assigned";
doSomethingAndRemove(first);
public void Remove(String string) {
//Do something
//...and remove
string = null;
}
The thing is that first still is referencing to "Assigned"... But from what I read in the answers so far, there is no way around this?
No, it is not possible to remove all "pointers" to a given object, for one because Java doesn't have pointers, they are called references.
Neither Java nor the JVM knows all references to a given object. This is why the garbage collector has to scan everything to find unused objects.
You have to clear references, and you cannot clear a reference variable that was used to pass a parameter from within the called method, because Java is pass-by-value, meaning the reference (not the object) is copied.
Example:
public static void main(String[] args) {
String var1 = "Hello";
doSomething(var1); // The value of var1 is copied to param1
}
private static void doSomething(String param1) {
param1 = null; // Only clears the param1 reference
var1 = null; // Cannot do this, because doSomething() does not have access to var1
}
Only code in method main can change the reference value of var1.
Update
If you want method doSomething to be able to update var1 to a different value, incl. null, then a common practice is to simply return the updated value.
public static void main(String[] args) {
String var1 = "Hello";
var1 = doSomething(var1);
}
private static void doSomething(String param1) {
// do something with param1
return "Goodbye";
}
This of course only works if you didn't already have a different kind of return value, and only works for a single value.
Output (and In/Out) parameters can be simulated in Java using the holder pattern, e.g. see Output Parameters in Java
C# can do it using ref, but Java cannot. The following is the last resort in Java if you must do it.
public class Nullify
{
public static void main(String[] args) {
String[] first = { "ASSIGNED" };
System.out.println("first[0] = " + first[0]);
nullify(first);
System.out.println("first[0] = " + first[0]);
}
private static void nullify(String[] array) {
array[0] = null;
}
}
String s=ASSIGNED;
String s2=s;
String s2=null; // means just remove the link s2 is pointing to
System.out.println(s); // print ASSIGNED
seen the picture.
if you want to remove you have to assign null to all individual objects.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
Beginner java question, but I cannot understand how call-by-Value ( or Reference ) is working in the example below -
How come the String value is not modified after it exits the method while my custom String Object is. ? Same with other classes like Date..
public class StringMadness {
public static void main(String[] args) {
String s = "Native String";
CustomStringObject cs = new CustomStringObject();
System.out.println("Custom String Before: " + cs.str);
hello(cs);
System.out.println("Custom String After: " + cs.str);
System.out.println("Native String Before: " + s);
hello(s);
System.out.println("Native String After: " + s);
}
private static void hello(String t) {
t = "hello " + t;
}
private static void hello(CustomStringObject o) {
o.str = "hello " + o.str;
}
}
class CustomStringObject {
String str = "Custom String";
}
Compare these two methods:
private static void hello(String t) {
t = "hello " + t;
}
private static void hello(CustomStringObject o) {
o.str = "hello " + o.str;
}
In the first case, you're assigning a new value to t. That will have no effect on the calling code - you're just changing the value of a parameter, and all arguments are passed by value in Java.
In the second case, you're assigning a new value to o.str. That's changing the value of a field within the object that the value of o refers to. The caller will see that change, because the caller still has a reference to that object.
In short: Java always uses pass by value, but you need to remember that for classes, the value of a variable (or indeed any other expression) is a reference, not an object. You don't need to use parameter passing to see this:
Foo foo1 = new Foo();
Foo foo2 = foo1;
foo1.someField = "changed";
System.out.println(foo2.someField) // "changed"
The second line here copies the value of foo1 into foo2 - the two variables refer to the same object, so it doesn't matter which variable you use to access it.
There's an important difference between the two methods: using hello(String) you're trying to change the reference to the String, and with hello(CustomObject), given a reference, you're using the reference to change a member of the object.
hello(String) takes a reference to a String. In the function you're trying to change which object that reference points to, but you're only changing the pass-by-value copy of the reference. So your changes aren't reflected outside the method.
hello(CustomObject) is given a copy of a reference to an object, which you can then use to change the actual object. Think of this as changing the contents of the object. So your changes are reflected in the caller.
Given a reference to an object, you can change the object using it's exposed methods/fields
Because for the String you are just changing the local parameter reference.
t will point to new object and scoped to method only, so changes not visible outside.
Second case, the value you are changing will be updated to object,so those changes are visible after method call.
Doesn't work because String is an immutable object
static void f(String s)
{
s = "x";
}
public static void main(String[] args) {
String s = null;
f(s);
}
Why the value of s after calling f(s) is null instead of "x"?
Because s is a reference. You pass a copy of that reference to the method, and then modify that copy inside the method. The original doesn't change.
When passing an Object variable to a function in java, it is passed by reference. If you assign a new value to the object in the function, then you overwrite the passed in reference without modifying the value seen by any calling code which still holds the original reference.
However, if you do the following then the value will be updated:
public class StringRef
{
public String someString;
}
static void f(StringRef s)
{
s.someString = "x";
}
public static void main(String[] args)
{
StringRef ref = new StringRef;
ref.someString = s;
f(ref);
// someString will be "x" here.
}
Within the function f() the value will be "x". Outside of this function the value of s will be null. Reference data types (such as objects) are passed by value see here (read the section "Passing Reference Data Type Arguments")
Given that s is of type String, which is a reference type (not a primitive):
s = "x";
does not mean "transform the thing that s refers to into the value "x"". (In a language where null is a possibility, it can't really do that anyway, because there is no actual "thing that s refers to" to transform.)
It actually means "cause s to stop referring to the thing it currently refers to, and start referring to the value "x"".
The name s in f() is local to f(), so once the function returns, that name is irrelevant; the name s in main() is a different name, and is still a null reference.
The only thing that the parameter passing accomplishes is to cause s in f() to start out as null.
This explanation would actually go somewhat more smoothly if you hadn't used null :(
Actually you are not changing the value you are creating new one, it is totally different, If you change an attribute of the abject in the method then i will be changed in your references. But you are creating new object.
In the following code
public class Test {
public static void main(String[] args){
int [] arr = new int[]{1,2};
String b=new String("abc");
f(b,arr);
System.out.println(b);
System.out.println(arr[0]);
}
public static void f(String b, int[] arr){
b+="de";
b=null;
arr[0] = 5;
}
}
Why the reference variable of the string doesn't behave like the reference variable of the array?.
I know string are immutable so operations on them creates new string but how about references to strings and how the reference b still refer to the old value although it was changed to refer to something else in f() method.
Object references in Java are passed by value. Assigning just changes the value, it does not alter the original object reference.
In your example arr[0] is changed, but try arr=null and you will see it has no effect after the method has returned.
Method call is called by value in Java, well there is long debate about this , But I think that we should consider in terms of implementation language of Java which is C/C++. Object references just pointers to objects, and primitives are the values.. Whenever a method is called, actual arguments are copied to formal parameters. Therefore, if you change pointer to reference another object , original pointer is not affected by this change, but if you change object itself, calling party can also see the changes, because both party are referring the same object..
Well, in your example, you are changing string reference to null in called method, but you are changing object referred by array reference.. These two operations are not the same, therefore they do have different consequences.. for example, if you change the code as below, they would be semantically same operation..
arr = null;
You cnanot change the argument for any method, however you can do the following.
public static void main(String... args) throws IOException {
String[] strings = {"Hello "};
addWorld(strings);
System.out.println("Using an array "+Arrays.toString(strings));
StringBuilder text = new StringBuilder("Hello ");
addWorld(text);
System.out.println("Using a StringBuilder '" + text+"'");
}
private static void addWorld(String[] strings) {
for(int i=0;i<strings.length;i++)
strings[i] += "World!";
strings = null; // doesn't do anything.
}
private static void addWorld(StringBuilder text) {
text.append("World !!");
text = null; // doesn't do anything.
}
prints
Using an array [Hello World!]
Using a StringBuilder 'Hello World !!'