White Spaces Removal Program

Using Java

 Remove White Spaces From String In Java Using Built-In Methods?

we use replaceAll() method of String class to remove all white spaces (including tab also) from a string. This is one of the easiest method to remove spaces from string in java. replaceAll() method takes two parameters. One is the string to be replaced and another one is the string to be replaced with. We pass the string “\\s+” to be replaced with an empty string “”

import java.util.Scanner;
 
public class RemoveWhiteSpaces 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
         
        System.out.println("Enter input string to be cleaned from white spaces...!");
         
        String inputString = sc.nextLine();
         
        String stringWithoutSpaces = inputString.replaceAll("\\s+", "");
         
        System.out.println("Input String : "+inputString);
        System.out.println("Input String Without Spaces : "+stringWithoutSpaces);
         
        sc.close();
    }
}

Remove White Spaces From String Without Using Built-In Methods?

 first we convert the given input string to char array and then we traverse this array to find white spaces. We concatenate the characters which are not the white spaces to String object.

import java.util.Scanner;
 
public class RemoveWhiteSpaces 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
         
        System.out.println("Enter input string to be cleaned from white spaces...!");
         
        String inputString = sc.nextLine();
         
        char[] charArray = inputString.toCharArray();
         
        String stringWithoutSpaces = "";
         
        for (int i = 0; i < charArray.length; i++) 
        {
            if ( (charArray[i] != ' ') && (charArray[i] != '\t') )
            {
                stringWithoutSpaces = stringWithoutSpaces + charArray[i];
            }
        }
         
        System.out.println("Input String : "+inputString);
         
        System.out.println("Input String Without Spaces : "+stringWithoutSpaces);
         
        sc.close();
    }
}

annotation @JsonInclude of Jackson library which helps in eliminating default, null, empty, etc values. For this post, we will focus on default values. Suppose we have an Employee POJO as below:- It may not be mandatory to pass values to all fields in a payload. For example, a “gender” field may be optional and you …

Continue reading @JsonInclude Annotation – Ignore Default Values In Payload