import java.util.Arrays;
public class Test {
public static void main(String... args) {
String[] strings = new String[] { "foo", "bar" };
changeReference(strings);
System.out.println(Arrays.toString(strings)); // still [foo, bar]
changeValue(strings);
System.out.println(Arrays.toString(strings)); // [foo, foo]
}
public static void changeReference(String[] strings) {
strings = new String[] { "foo", "foo" };
}
public static void changeValue(String[] strings) {
strings[1] = "foo";
}
}
Can anyone explain these questions?
What is Strings[]. Is it a String Object or String Object containing array of Objects.
What does the changeReference() and changeValue() functions do and return?
Does Java support Pass by Reference?
strings is an array of Strings. Arrays are objects for our purposes here, which means they are a reference type.
changeReference does nothing useful. It receives a reference to strings, but it receives that reference by value. Reassigning strings within the function has no effect on the strings being passed in -- it just replaces the local copy of the reference, with a reference to a new array. changeValue, on the other hand, modifies the array object referred to by strings. Since it's a reference type, the variable refers to the same object.
No, "pass by reference" is not supported. Java can pass references around, but it passes them by value. Summary being, you can change the object being passed in, but you can't replace the object in such a way that the caller will see it.
What is Strings[]. Is it a String Object or String Object containing array of Objects.
It’s neither. It’s an object (well, actually it’s a type) that references an array of strings.
What does the chanfeReference and changeValue function do and return?
Please try it yourself to see the effect.
Does Java support Pass by Reference?
No. Java is always pass by value.
What is String[]. Is it a String
Object or String Object containing
array of Objects.
String[] is an array of String (and String is an Object).
What does the changeReference and
changeValue function do and return?
In changeReference() java changes the reference of strings to an new string array. In changeValue(), java changes the value of the first element of strings array.
Does Java support Pass by Reference?
Java supports Pass by Value. As stated on JavaWorld:
Java does manipulate objects by
reference, and all object variables
are references. However, Java doesn't
pass method arguments by reference; it
passes them by value.
String[] is an array of String objects
changeReference changes the refence to the array strings to a new refence to a new array which, in this case, contains the same thing, but the reference in the memory is in another place.
Pass by Reference is not supported in Java
Related
I started with java a couple of weeks ago. Before that i had multiple years working with c/c++ on embedded targets and with c# with UI Stuff on Win PCs.
I got this very simple example:
public class StreamProcessing {
public static void main(String[] args) {
Stream stream = new Stream(); //after this line: Stream string empty
StreamFiller.fillStream(stream); //after this line: Stream string not empty any more
StreamPrinter.printStream(stream);
}
}
I'd expect that whatever StreamFiller.fillStream() does, the argument is copied. However it looks like fillStream is modifying the actual stream object itself.
The Stream class basically contains a string
public class Stream {
private String content = "";
int index = 0;
public char readChar() {
if (index < content.length()) {
return content.charAt(index++);
} else {
return 0;
}
}
public void writeString(String str) {
content += str;
}
}
The Streamfiller should modify it's stream copy but not the original reference
public class StreamFiller {
public static void fillStream( Stream stream ) {
stream.writeString( "This is a" );
stream.writeString( " stream." );
}
}
Please correct me if I'm wrong, but since the actual text of the string class is allocated on the heap, both the StreamProcessing () Stream object and the (supposed copied) local object of fillStream() point to the same address on the heap (yeah i now it's not an actual memory address like in c/c++ but some unique object identifier)
So is my assumption correct? Non trivial objects (aka objects allocated on the heap) are passed by reference?
thx for your help :)
The Java language does not let you make heap / stack distinction in your code the way C and C++ do.
Instead, it divides all data types in to two groups:
Primitive types:
These are simple built in numerical types such as int, double or boolean (not a numerical type in Java).
Note that String is not such a type!
Object types:
If it is a class, it is an object type. This goes for built in types such as String and for user defined types such as your Stream class.
For these types, all you ever see is a reference, whether you are looking at a local variable, class member, instance member, or function parameter.
Lets look at a simple example:
public class A {
public int a;
public static void main(String [] args) {
A var1 = new A();
A var2 = var1;
var1.a = 42;
System.out.println("var2.a = " + var2.a);
}
}
If you compile and run this example it will print 42.
In C++ the line A var2 = var1; would have invoked a copy constructor and created a new object but in Java there is no such thing. If you want a copy, you need to invoke clone method explicitly.
What is held in var1 and copied to var2 is just a reference.
So both vars "point" to the same object.
And again - it does not matter if the class is trivial or not. Even if a class is completely empty, you will still only be given and work with a reference to any object of this class.
As for the primitive types mentioned earlier, Java has wrapper classes such as Integer and Boolean for them.
You might want to read about "boxing" and "unboxing".
One more thing to note is that some types are immutable - that is, they do not provide a way to change their data once created.
String in Java is an immutable type, but it is also a bit different from any other type.
It has special privileges.
While Java does not support operator overloading like C++ does, for String type the language does provide a special + operator that preforms string concatenation.
How ever, since String objects are immutable, any concatenation operation will create a brand new String object, even one like this:
String a = "Hello";
a = a + " world!";
This creates a new string "Hello world" and stores the reference to it in a, leaving the reference to old "Hello" string to be garbage collected at some future point.
Even though in Java everything is passed by value, there is a difference between how primitive data types (such as int, char and boolean) and how reference data types are passed to a method.
When passing the value of a primitive data type, this value can only be changed in the scope of the particular method. When passing the value of a reference data type, the reference will remain the same but the value will change globally (or in whatever scope the object was initialised).
See also this for more information: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
List<String> list = new ArrayList<String>();
String string = null;
string = "123";
list.add(string);
string = "456";
list.add(string);
for (String s : list)
{
System.out.println(s);
}
This program outputs:
123
456
which is pretty natural.
However, I'm thinking in another way. "string" is the reference(pointer) to the actual String object. When executing add(), it just stores the reference. When "string" refers to another String object, why the list still keeps the original one? Does it make a copy before add()?
The "value" of a String variable is a reference to the (immutable) object that is the string.
So there is no copy of the String but a copy of the reference. Having this reference doesn't allow you to change the original variable (you have no link to it) and doesn't allow you to change the string as it is immutable.
What you have here, inside the array contained by the arrayList after the two calls to add, is two different references. They could point to the same string but changing one reference doesn't change the other one. If you wanted to change the first reference in this case to point to the same string as the second one, the simplest would have been to do list.set(0, list.get(1));
When "string" refers to another String object, why the list still keeps the original one?
What you've added to the list is the reference to the string. Later, when you do
string = "456";
you're not changing the existing string, you're assigning a reference to a different string to the string variable. The original string is unchanged (in fact, strings in Java are immutable).
because the variable 'string' is nothing but a pointer to a address in the memory. when you add 'string' in list the memory address of the 'string' is entered in the list. when you again assign a value , it justs change the address in the memory where the new variable is pointing
*strong text*what is reference copying technique?
The reference copying technique is much more difficult to use for mutable objects, because if any user of a reference to a mutable object changes it, all other users of that reference will see the change
Another thing I tested sample code below for pass-by-value & pass-by-reference.The primitive values are pass-by-value and object reference are pass-by-reference.In the sample example,I tested types a string contant,String object,String buffer,int,ArrayList.
String s="foo";
String sample1=new String("dog");
StringBuffer sb=new StringBuffer();
sb.append("abc");
ArrayList l=new ArrayList();
l.add("ssss");
l.add("bbbb");
l.add("ssbbbss");
l.add("bbbb");
l.add("bbbb");
int k=14,listsize=0;
listsize=l.size();
TesingPrimitivRefernce.generateString(s);
TesingPrimitivRefernce.generateString(sample1);
TesingPrimitivRefernce.generateStringBuilder(sb);
TesingPrimitivRefernce.generateInt(k);
TesingPrimitivRefernce.generateNewList(l);
System.out.println("String============"+s+" String Buffer========"+sb+" String object "+sample1);
System.out.println("int Primitive Values==="+k);
System.out.println("Orignal List Size"+listsize+" After called method List Size=========="+l.size());
public static void generateString(String s){
s=s.concat("d");
}
public static void generateStringBuilder(StringBuffer s){
s=s.append("d");
}
public static void generateInt(int s){
s=10;
}
public static void generateNewList(ArrayList list){
list.remove("bbbb");
}
My doubt is why String object is not changed (**i.e.,variable sample1) after calling *TesingPrimitivRefernce.generateString(sample1).but in the arraylist i removed the value "bbb" and automatically decrase size.Here I passed String object reference.So why it is not changed?*
I don't know who told you that "primitive values are pass-by-value and object reference are pass-by-reference". This is wrong.
In Java, everything is pass-by-value.
Now, objects are not manipulated directly but through references. Multiple references can point to the same object but these references are copied like any other arguments.
References in Java are passed by value. So if you reassign the first argument in TesingPrimitivRefernce.generateString to something else, it is the copy of the sample1 reference that is changed (you weren't trying to modify the argument using some... modifiers, were you? :)).
So, before the modification:
sample1 -> dog
s -> dog
After the modification:
sample1 -> dog
s -> dogdd (and this String object is lost once the method exits).
In the ArrayList case, you were modifying the underlying list, so the originally referenced object was modified.
Strings are constant; their values cannot be changed after they are created. At the moment you pass a string to a method a copy of this string is created. All further changes in this method modify this copy, not the string itself.
I have come across two scenarios.
One in which an array is passed as argument to a method and if it is updated in the called method, it is reflecting in the calling method as well.
But in the second scenario, a String Object is passed as argument. The object is updated in the called method, but it doesn't reflect in the calling method.
I want to understand what is the difference between two, even though in both cases, value (of reference) is passed as argument. Please see below snippets.
Scenario 1:
class Test {
public static void main(String[] args){
int a[] = {3,4,5};
changeValue(a);
System.out.println("Value at Index 1 is "+a[1]);
}
public static void changeValue(int b[]){
b[1] = 9;
}
}
Output:
Value at Index 1 is 9
Here, reference (Memory Address) related to array a is passed to changeValue. Hence, b is just pointing to same address as a does.
Hence, whether I say b[1] or a[1], it is referring to same memory address.
Scenario 2:
public class Test {
public static void main(String[] args){
String value = "abc";
changeValue(value);
System.out.println(value);
}
public static void changeValue(String a){
a = "xyz";
}
}
Output:
abc
If I apply the same logic here, String Object VALUE's reference (Memory Address) is being passed to changeValue, which is recieved by a.
Hence, now a should be referring to the same memory location as VALUE does. Therefore, when a="xyz" is executed, it should replace "abc" with "xyz".
Can someone please point out where my understanding goes wrong? Thanks in advance!!
Java passes all its arguments by value. This means that a copy of the pointer to the String is made, and then passed to the method. The method then makes the pointer point at another object, but the original pointer still points to the same String.
This is not the same thing:
in the first example, you pass an array reference as an argument, therefore you correctly expect it to be changed by manipulating the reference directly;
in the second example however, you pass an object reference, sure -- but you change the reference itself in the method. Changes to a are not reflected when the method returns.
Consider any object:
public void changeObj(Object o)
{
o = new Whatever();
}
a new object is created, but it won't change o in the caller. The same happens here.
You're doing different things; with the string you set the parameter value, with the array you set something belonging to the reference.
For an equivalent array example you'd need to try setting the array reference to a new array:
public static void changeValue(int[] b) {
b = new int[] { 42, 60 };
}
The original array won't be changed.
The difference here is simple, and it is not actually about immutability of strings, as some other answers (now edited or deleted) might have originally implied. In one version (with the string), you have reassigned the reference, and in other version (with the array), you haven't.
array[0] = foo; // sets an element, no reassignment to variable
array = new int[] { 1,2,3 }; // assigns new array
obj = "hey"; // assigns new value
When you reassign the variable, you are not going to observe that change outside of the method. When you change elements of an array without reassigning the array variable, you will observe those changes. When you call a setter on an object without reassigning the actual variable of the object, you will observe those changes. When you overwrite the variable (new array, assigning new value, creating new object, etc.) those changes will go unobserved.
Arguments are passed (or copied) by value. The variable inside the method has the same value as the variable on the outside at the beginning. The variables are not linked, and they are not aliases for one another. They just happen to contain the same value. Once you reassign the value to one of them, that is no longer true! The variable on the outside is not affected by the variable on the inside, or even another local variable. Consider
Foo foo = new Foo();
Foo other = foo;
foo.setBar(1);
int bar = other.getBar(); // gets 1
foo = new Foo();
foo.setBar(42);
int bar2 = other.getBar(); // still gets 1
foo and other only referenced the same object for a time. Once foo was assigned a new object, the variables no longer had anything in common. The same is true for your reassignments to the parameter variable inside your method.
Thank you all for answers and updates..
I understood the difference between scenario 1 and 2 as below..
In scenario 1, the array reference is passed. The called method just updates one of the elements pointed by the reference.
While in scenario 2, the reference is passed, but when the called method assigns "xyz" to the reference variable (pointer), it actually creates a new String Object and its reference is assgined to a local reference variable 'a' (Pointer now points a different objct).
The code in called method is as good as
a = new String("xyz");
Hence, the object in called method and calling method are absolutely different and indepenedent and have no relation with each other.
The same could have happened with scenario 1, if instead of doing
b[1] = 9;
I would have used
b = new int[] {8,9,10};
I understood, Mutability fundamentals would have come in action, if I might have done like below..
String a="abc";
a="xyz";
In this case, object "abc" was being pointed by 'a'. When 'a' is assigned the duty to point to a new object "xyz", a new object "xyz" is created, which is not replacing the existing object "abc". i.e. "abc" is still existing but has no reference variable to keep itself accessible anymore. This non-replacement property is because of Immutability of String.
private static void changeString(String s) {
s = new String("new string");
}
public static void main(String[] args) {
String s = new String("old string");
changeString(s);
System.out.println(s); // expect "new string"
}
How could I make the output of "new string" happen with s as the only argument to method changeString?
thanks.
In Java arguments are passed by value, object arguments pass a reference to the object, this means that you can change the reference of the argument, but that does not change the object you passed the reference to. You have two possibilities, return the new object (preferred) or pass reference to a container that can receive the new reference (collection, array, etc.) For example:
private static String changeStringAndReturn(String s) {
return new String("new string");
}
private static void changeStringInArray(String[] s) {
if (null != s && 0 < s.length) {
s[0] = new String("new string");
}
}
References in Java are passed by value, so even if you modify the reference inside the function, changes won't be reflected back to the calling function because what you modify inside the function is just a copy of the original reference not the original reference itself.
But you can return the new string from your changeString method instead of trying to modify the reference there(inside the function) itself.
Only if you make the function
private static void changeString(String[] s) {
s[0] = new String("new string");
}
String are immutable, and Java has no concept of a 'pointer-to-a-reference' as a first class datatype. If you don't like the above, you can make a little class containing a single String field.
You can, of course, return the new string from your changeString method instead of trying to change it in place.
Alternately, you can create an object that wraps or contains a string, and pass that in. The ChangeString method would change the string that was internal to your object, and the main method would still be holding a reference to that object.
Otherwise, you can't do this. String is immutable, and java always passes objects as a value that is a pointer to a particular object. Change where you're pointing, and you aren't referencing the same object anymore.
Strings are immutable in Java and parameters are passed by value so you can't change them (there is not equivalent to ref in C#). You can pass in a StringBuilder and change it's contents just as easily.
A: You can't, in Java object references are pass by value.
If you really need to, you can create a wrapper like this and use it the way you expected:
private static void changeString( _<String> str) {
str.s("new string");
}
public static void main(String[] args) {
_<String> s = new _<String>("old string");
changeString(s);
System.out.println(s); // prints "new string"
}
I know this is old, but, just for posterity, most of this is mostly wrong.
In Java, non-primitives are passed by reference. Primitives (boxed and unboxed) are passed by value.
To directly answer OP, you're getting a reference to the actual String you passed. However, as #bmarguilies correctly pointed out - Strings are immutable in Java. Any assignment to a String creates a copy, then assigns the newly-assembled copy to the reference.
This is not possible in Java as everything in Java is passed by value. In this case where the argument is an object reference it is the value of the reference that is passed into the method, not the reference itself.
Java does not allow out parameters like C#, so you will not be able to achieve this as such.
Its ugly but you could change the String to global static:
private static String s;
private static void changeString(String t) {
if(s.equals(t))
s = new String("new string");
}
public static void main(String[] args) {
s = new String("old string");
changeString(s);
System.out.println(s); // expect "new string"
}