Write a program to remove unwanted empty spaces in a string

import java.util.*;public class RS{ 

public static void main(String[] args){
String a = " hello world is beautiful ";
char[] b = a.toCharArray();
int s = 0, e = b.length -1;
// Remove the beginning and trailing spaces of the sentence
while(s<e && ( b[s] == ' ' || b[e] == ' ')){
if(b[s] == ' '){
s++;
}
if(b[e] == ' '){
e--;
}
}
StringBuffer sb = new StringBuffer();
boolean spaceMet = false;
// Append only non space elements and next first space
for(int i = s; i <= e; i++){
if (b[i] != ' '){
sb.append(b[i]);
spaceMet = false;
} else if (!spaceMet){
sb.append(b[i]);
spaceMet = true;
}
}
System.out.println(sb.toString());
}
}

Output

p4@prince:~/Projects/java/i_samples/test$ java RS
[ , h, e, l, l, o, , w, o, r, l, d, , , , i, s, , b, e, a, u, t, i, f, u, l, ]
hello world is beautiful
p4@prince:~/Projects/java/i_samples/test$