How to swap two string variables in Java without using a third variable

后端 未结 18 771
梦谈多话
梦谈多话 2021-02-02 12:30

How do I swap two string variables in Java without using a third variable, i.e. the temp variable?

String a = \"one\"
String b = \"two\"
String temp = null;
temp         


        
18条回答
  •  说谎
    说谎 (楼主)
    2021-02-02 13:16

    String a = "one";//creates "one" object on heap
    String b = "two";// creates "two" object on heap
    System.out.printf("a is %s , b is %s%n",a,b);
    a = "two";// will not create new "two" object & now a is pointing to "two" object
    b = "one";// will not create new "one" object & now b is pointing to "one" object
    System.out.printf("a is %s , b is %s%n",a,b);
    

提交回复
热议问题