Java - Write code to trim All Whitespace from a string

Requirements

Write code to trim All Whitespace from a string

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        System.out.println(trimAllWhitespace(str));
    }/*from   ww  w. j av  a  2  s.c o m*/

    public static String trimAllWhitespace(String str) {
        if (!hasLength(str)) {
            return str;
        }
        StringBuffer buf = new StringBuffer(str);
        int index = 0;
        while (buf.length() > index) {
            if (Character.isWhitespace(buf.charAt(index))) {
                buf.deleteCharAt(index);
            } else {
                index++;
            }
        }
        return buf.toString();
    }

    public static boolean hasLength(String str) {
        return (str != null && str.length() > 0);
    }
}