Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
Now Reading
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
In Java programming, manipulating strings efficiently is a crucial skill. One common task is removing whitespace from strings, eliminating unnecessary space to optimize text processing.
In this article, we will explore various techniques to remove whitespace from string in java, while also discussing alternative approaches in other programming languages such as Java Script, Python, C++, and C#. We will cover the built-in methods in Java, such as trim(), strip(), stripLeading(), stripTrailing(), and replaceAll(), along with custom implementations.
So, let's dive into the world of whitespace removal in Java!
Whitespace refers to any non-visible characters within a string, including spaces, tabs, and line breaks. Removing these whitespace characters can significantly improve the efficiency of string operations and enhance memory usage.
In the following sections, we will explore different methods to achieve this optimization in Java, focusing on simplicity and effectiveness.
In Java, there are multiple approaches to remove whitespace from a string. Let's explore each method in detail:
The trim() method is a built-in function in Java that removes leading and trailing whitespace from a string. It trims spaces from both ends of the string, leaving the internal whitespace intact. For example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // Output: "Hello, World!"
}
}
Output:
Hello, World!
In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, World! ". This string contains leading and trailing whitespace.
To remove the leading and trailing whitespace from the string, we use the trim() method. The trim() method is a built-in function in Java's String class that eliminates leading and trailing whitespace characters.
We then assign the trimmed string to the variable trimmedStr. Finally, we print the value of trimmedStr to the console using System.out.println(), which will output "Hello, World!".
When you run this Java program, you will see the output "Hello, World!", demonstrating the removal of whitespace from the original string.
Introduced in Java 11, the strip() method removes leading and trailing whitespace from a string, similar to trim(). However, strip() is more powerful as it can handle Unicode whitespace characters as well. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String strippedStr = str.strip();
System.out.println(strippedStr); // Output: "Hello, World!"
}
}
Output:
Hello, World!
This is because the strip() method removes the leading and trailing whitespace from the string " Hello, World! ", resulting in the trimmed string "Hello, World!". The System.out.println() statement prints this trimmed string to the console, displaying "Hello, World!" as the output.
The stripLeading() method, introduced in Java 11, removes only the leading whitespace from a string, leaving trailing whitespace intact. It also handles Unicode whitespace characters. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String strippedStr = str.stripLeading();
System.out.println(strippedStr); // Output: "Hello, World! "
}
}
Output:
Hello, World!
In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, World! ". This string contains leading and trailing whitespace.
To remove only the leading whitespace from the string, we use the stripLeading() method. The stripLeading() method is a built-in function introduced in Java 11 that trims the whitespace from the beginning of the string while leaving the trailing whitespace intact.
We then assign the stripped string to the variable strippedStr. Finally, we print the value of strippedStr to the console using System.out.println(), which will output "Hello, World! ".
The stripTrailing() method, introduced in Java 11, removes only the trailing whitespace from a string, leaving the leading whitespace intact. It handles Unicode whitespace characters as well. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String strippedStr = str.stripTrailing();
System.out.println(strippedStr); // Output: " Hello, World!"
}
}
Output:
Hello, World!
In the given code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, World! ". This string contains leading and trailing whitespace.
To remove only the trailing whitespace from the string, we use the stripTrailing() method. The stripTrailing() method is a built-in function introduced in Java 11 that trims the whitespace from the end of the string while leaving the leading whitespace intact.
We then assign the stripped string to the variable strippedStr. Finally, we print the value of strippedStr to the console using System.out.println(), which will output " Hello, World!".
The replaceAll() method with regular expressions lets you remove all whitespace characters from a string, including spaces, tabs, and line breaks. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, \nWorld! ";
String noWhitespaceStr = str.replaceAll("\\s", "");
System.out.println(noWhitespaceStr); // Output: "Hello,World!"
}
}
Output:
In the given code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, \nWorld! ". This string contains various whitespace characters, including spaces and a newline character.
To remove all whitespace characters from the string, we use the replaceAll() method along with the regular expression pattern "\\s". The "\\s" pattern matches any whitespace character, including spaces, tabs, and newline characters. We replace all occurrences of whitespace with an empty string "".
We then assign the resulting string to the variable noWhitespaceStr. Finally, we print the value of noWhitespaceStr to the console using System.out.println(), which will output "Hello,World!".
Now let's explore two additional methods to remove all whitespace characters from a string in Java:
By combining multiple string class functions, we can remove all whitespace characters from a string. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, \nWorld! ";
String noWhitespaceStr = str.replace(" ", "").replace("\t", "").replace("\n", "");
System.out.println(noWhitespaceStr); // Output: "Hello,World!"
}
}
Output:
In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, \nWorld! ". This string contains various whitespace characters, including spaces, tabs, and a newline character.
We use the replace() method multiple times to remove all whitespace characters from the string. We chain the replace() method calls to individually remove spaces, tabs, and newline characters. In each replace() call, we specify the whitespace character to be replaced with an empty string "".
We then assign the resulting string to the variable noWhitespaceStr. Finally, we print the value of noWhitespaceStr to the console using System.out.println(), which will output "Hello,World!".
The Character class in Java provides handy functions to determine if a character is whitespace. By iterating through the characters of a string, we can filter out the whitespace characters. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, \nWorld! ";
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
String noWhitespaceStr = sb.toString();
System.out.println(noWhitespaceStr); // Output: "Hello,World!"
}
}
Output:
In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, \nWorld! ". This string contains various whitespace characters, including spaces, tabs, and a newline character.
To remove all whitespace characters from the string, we use a StringBuilder to build the resulting string without whitespace. We iterate through each character of the input string using a for loop and check if the character is not a whitespace character using the Character.isWhitespace() method. We append it to the StringBuilder if it's not a whitespace character.
After iterating through all the characters, we convert the StringBuilder to a string using the toString() method and assign it to the variable noWhitespaceStr. Finally, we print the value of noWhitespaceStr to the console using System.out.println(), which will output "Hello,World!".
You can use a combination of string manipulation techniques to remove whitespace from a string in Java without using the replace() method. Here's an example approach:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String noWhitespaceStr = removeWhitespace(str);
System.out.println(noWhitespaceStr); // Output: "Hello,World!"
}
public static String removeWhitespace(String str) {
char[] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : chars) {
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
return sb.toString();
}
}
Output:
Hello, World!
To remove whitespace from a string in Java without using the replace() method, you can iterate through each character of the string and append non-whitespace characters to a StringBuilder. Finally, convert the StringBuilder to a string. This approach avoids direct replacement and produces a new string without whitespace.
To remove whitespace from the beginning and end of a string in Java, you can use the Java trim. The trim() method is a built-in function that eliminates leading and trailing whitespace characters. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // Output: "Hello, World!"
}
}
In the above code, the string " Hello, World! " contains whitespace characters at the beginning and end.
By applying the trim() method to the string, we remove those leading and trailing whitespace characters. The resulting string, "Hello, World!", is then printed to the console.
Removing whitespace from strings is a common requirement in Java programming. In this article, we explored various methods to achieve efficient string manipulation by removing whitespace. We covered built-in functions like trim(), strip(), stripLeading(), stripTrailing(), and replaceAll(), along with custom implementations using string class functions and the Character class. By utilizing these techniques, you can optimize your code for improved performance and memory usage. So, the next time you encounter whitespace removal in Java, choose the appropriate method based on your specific needs and achieve efficient string manipulation.
1. How does the trim() method in Java remove whitespace from a string?
The trim() method removes leading and trailing whitespace characters from a string, including spaces, tabs, and newline characters. It returns a new string with the whitespace removed.
2. How can I remove only the leading whitespace from a string in Java?
To remove only the leading whitespace from a string, use the stripLeading() method introduced in Java 11. It trims the whitespace from the beginning of the string while leaving the trailing whitespace intact.
3. How can I remove only trailing whitespace from a string in Java?
To remove only trailing whitespace from a string, use the stripTrailing() method introduced in Java 11. It trims the whitespace from the end of the string while preserving the leading whitespace.
4. How does the trim() method differ from the replaceAll() method for removing whitespace in Java?
The trim() method removes leading and trailing whitespace characters, while the replaceAll() method replaces all occurrences of a specified pattern with a replacement string. The trim() method is specifically designed for removing whitespace from the beginning and end of a string, while replaceAll() provides more flexibility for replacing specific patterns throughout the string.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...