class Effect
{
public static void main(String [] args)
{
Effect e=new Effect();
e.method();
}
void method()
{
long [] a1 = {3,4,5};
long [] a2 = doArray(a1);
//expected output
System.out.println("After Calling doArray "+a1[1] +" "+ a2[1]);
String s1 = "Hello";
String s2 = doString(s1);
//expected output s1=HelloJava s2=World like earlier arrays
System.out.println("After Calling doString "+s1 + " " + s2);
}
long [] doArray(long [] a3)
{
a3[1] = 7;
System.out.println("In doArray "+ a3[0]+" "+a3[1]+" "+a3[2]);
return a3;
}
String doString(String s1)
{
s1 = s1 + "Java";
System.out.println("In doString "+ s1);
return "World";
}
}
OUTPUT
In doArray 3 7 5
After Calling doArray 7 7
In doString HelloJava
After Calling doString Hello World
My Expected OUTPUT :
After Calling doString HelloJava World
please give some explanation?
In java String objects are immutable.
The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.
Documentation
Code clarification -
String doString(String s1) {
s1 = s1 + "Java";
...
}
Here s1+"java" will create a new object into the String pool. and reference s1 from method fucntion will still refer the old String object.
You need to understand that there's a difference between an object and a reference (ie, pointer). An object is real (as close as anything is "real" in a program) "thing". A reference is simply the address of the thing.
If, in a phone book, I change the address of your house from 123 1st Ave to 456 2nd St, that doesn't change your house. It will still (presumably) be located at 123 1st Ave. But if someone follows the address in the phone book they will end up at a different house.
And if you move from one house to the other you don't (usually) take the house, you load the furniture into a truck (lorry) and haul it to the other house. Then, if you don't change the phone book, someone looking for you will end up at the wrong (old) house.
(This has nothing to do with the fact that a String is immutable, BTW. The same is true of an array of long. But what you're doing in the above code with the array is moving in new furniture, not changing the address. There is only ever one array.)
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