Immutability of Strings in Java

后端 未结 26 2335
不思量自难忘°
不思量自难忘° 2020-11-21 06:33

Consider the following example.

String str = new String();

str  = \"Hello\";
System.out.println(str);  //Prints Hello

str = \"Help!\";
System.out.println(s         


        
26条回答
  •  温柔的废话
    2020-11-21 07:28

    Because String is immutable so changes will not occur if you will not assign the returned value of function to the string.so in your question assign value of swap function  returned value to s.

    s=swap(s, n1, n2) ;then the value of string s will change.

    I was also getting the unchanged value when i was writing the program to get some permutations string(Although it is not giving all the permutations but this is for example to answer your question)

    Here is a example.

    > import java.io.*;  public class MyString { public static void
    > main(String []args)throws IOException {  BufferedReader br=new
    > BufferedReader(new InputStreamReader(System.in));  String
    > s=br.readLine().trim(); int n=0;int k=0;  while(n!=s.length()) {
    > while(k n++; } }  public static void swap(String s,int n1,int n2) { char temp;
    > temp=s.charAt(n1); StringBuilder sb=new StringBuilder(s);
    > sb.setCharAt(n1,s.charAt(n2)); sb.setCharAt(n2,temp); s=sb.toString();
    > } }
    

    but i was not getting the permuted values of the string from above code.So I assigned the returned value of the swap function to the string and got changed values of string. after assigning the returned value i got the permuted values of string.

    /import java.util.*; import java.io.*; public class MyString { public static void main(String []args)throws IOException{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
    String s=br.readLine().trim(); int n=0;int k=0; 
    while(n!=s.length()){ while(k

提交回复
热议问题