To remove all the white spaces from a string in Java, you can use the replaceAll() method with the regular expression "\\s" which matches all whitespace characters including space, tab, and newline.
Here's an example:
public class RemoveSpacesFromString { public static void main(String[] args) { String originalString = "This is a string with spaces"; String stringWithoutSpaces = originalString.replaceAll("\\s", ""); System.out.println("Original string: " + originalString); System.out.println("String without spaces: " + stringWithoutSpaces); } }
In the above example, the originalString variable contains the string "This is a string with spaces". The replaceAll() method is called on this string with the regular expression "\\s" as the first argument and an empty string "" as the second argument. The method replaces all whitespace characters with an empty string, effectively removing all spaces. The resulting string is stored in the stringWithoutSpaces variable and printed to the console.
Finally, we print both the original string and the string without spaces to the console using the println() method. The output of running this code would be:
Original string: This is a string with spaces String without spaces: Thisisastringwithspaces