KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am trying to swap two strings in Java. I never really understood "strings are immutable". I understand it in theory, but I never came across it in practice. Also, since String is an object in Java and not a primitive type, I don't understand why the following code prints the same result twice, instead of interchanging the words! public static void main(String[] args) { String s1 = "Hello"; String s2 = "World"; System.out.println(s1 + " " + s2); Swap(s1, s2); System.out.println(s1 + " " + s2); } public static void Swap(String s1, String s2) { String temp = s1; s1 = s2; s2 = temp; } I want it to print Hello World World Hello But it is printing Hello World Hello World I thought s1 and s2 are references and hence the references should be swapped and the new ones should point to the other one respectively. Where am I going wrong?
Tags (comma-separated)
Save Edits
Cancel