In the code below, I tried to compare char at i with the char at i+1. My understanding is that by using charAt(): I can take the character from the string and treat it as integer and be able to compare two characters. This part of the code works, but I think I am missing something in the code, hence it is not printing the desired result. Unless this way of sorting characters in a String is not valid.
public class stringAlphabetical {
public static void main(String[] args){
String word="watch";
boolean swapped;
char temp = ' ';
do{
swapped = false;
for(int i=0;i<word.length()-1;i++){
char a = word.charAt(i);
char b = word.charAt(i+1);
if(word.charAt(i)>word.charAt(i+1)){ // if (a>b) {
temp = a;
a = b;
b = temp;
}
}
}while (swapped==true);
System.out.println(word);
}
}