Swap two strings in Java, by passing them to a utility function, but without returning objects or using wrapper classes

前端 未结 9 2244
既然无缘
既然无缘 2020-12-16 20:31

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

9条回答
  •  不思量自难忘°
    2020-12-16 21:07

    Java Strings are implemented with references, so you need to swap their references.

    String s1 = "Hello";
    String s2 = "World";
    AtomicReference String1 = new AtomicReference(s1);
    AtomicReference String2 = new AtomicReference(s2);
    String1.set(String2.getAndSet(String1.get()));
    System.out.println(String1 + " " + String2);
    

    It will give you this output:

    World Hello
    

提交回复
热议问题