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
By using StringBufferReader and StringBuilder this can be solved. At 1st get the values from the user then split them and store them in array. Run the for loop in the reverse order so that the last string will be appended and displayed 1st the first will displayed last.
input:hello world
output:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Solution {
public static void main(String[] args) {
try {
int s,i,j;
StringBuilder str = new StringBuilder();
String st,t;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
t = br.readLine();
s = Integer.parseInt(t);
for (i = 0; i < s; i++) {
st=br.readLine();
String st1[]=st.split("\\s+");
// System.out.println("l="+st1.length);
for (j = st1.length - 1; j >= 0; j--) {
str.append(st1[j] + " ");
}
System.out.println(str);
str.setLength(0);
}
} catch (Exception e) {
System.out.println(e);
}
}
}