This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
if everything in java is pass by value and when i passed s1 as argument then the reference of s1 gets copied as s1 stores the reference of string.
As i am doing s1=s1+" "+s1 then it should have changed the original string but it is not....
I think your concept about pass-by-value is incorrect. Pass-by-value has nothing to do with reference. So when you are passing "s1" and "s2" their value gets passed to newly created variables "s1" and "s2" which you have written in the method definition. So "s1" and "s2" which you are passing and "s1" and "s2" in method definition are total 4 different variables.
Jatin sachdev wrote:As i am doing s1=s1+" "+s1 then it should have changed the original string but it is not....
Why should it have changed the original String? Strings are immutable and cannot be changed. What you're doing in that method is creating new Strings that you assign to the local parameter variables s1 and s2. Afterwards, these two no longer refer to the original Strings but to the new Strings. The original Strings, with references in the original s1 and s2 local variables of the main method, remain as they were.
If you use StringBuilder instead of String, this allows you to modify the actual object instead of only the reference. It will then work as you expected:
Here in the main method s1 and s2 are just like keys to the String Builder objects(Say locks). Now passing by value means you make duplicate keys to open and close those locks. now you have 2 keys for each stringbuilder object. making s1 = null and s2 = null in the getString(StringBuilder...objects) method is like losing the duplicate keys but you still have another pair of keys to work with the locks.
Strings are immutable. Their state cannot be modified.