Java TechnologyJava Tutorial Java Program to remove all white spaces from a string by Online Tutorials Library July 22, 2022 81 How do you remove all white spaces from a string in java? File: RemoveAllSpace .java public class RemoveAllSpace { public static void main(String[] args) { String str = “IndiaIs My Country”; //1st way String noSpaceStr = str.replaceAll(“\s”, “”); // using built in method System.out.println(noSpaceStr); //2nd way char[] strArray = str.toCharArray(); StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < strArray.length; i++) { if ((strArray[i] != ‘ ‘) && (strArray[i] != ‘t’)) { stringBuffer.append(strArray[i]); } } String noSpaceStr2 = stringBuffer.toString(); System.out.println(noSpaceStr2); } } Output: IndiaIsMyCountry IndiaIsMyCountry Next TopicJava String FAQs charAt()examplejavamethodsignaturestring Share 0 FacebookTwitterPinterestEmail previous post Java program to print the following pattern on the console 2 next post Java Subtract Days from Current Date You may also like Java SHA Java Interpreter Java Email Validation Java String charAt() method Java String toLowerCase() method Java Collections replaceAll() Method with Examples