- Java String trim() Method
- Syntax of trim() in Java
- Parameters of trim() in Java
- Return Value of trim() in Java
- Example for trim() in Java
- How Does the trim() Method Work in Java?
- trim() vs replaceAll()
- Example 1: Java String trim()
- Example 2: Remove All Whitespace Characters
- Conclusion
- Java String trim() method with examples
- The What If scenarios
- 15.30. Java – Метод trim()
- Синтаксис
- Параметры
- Возвращаемое значение
- Пример
- Оглавление
Java String trim() Method
The trim() in Java is used to eliminate all leading and trailing whitespaces in a string. It is defined under the String class of Java.lang package.
Syntax of trim() in Java
Following is the syntax of trim in Java:
Parameters of trim() in Java
The trim() in Java does not accept any parameter.
Return Value of trim() in Java
Return Type: String
The trim() method in Java returns a new string which is the copy of the original string with leading and trailing spaces removed from it.
Example for trim() in Java
Suppose we are given the string: » Java » with whitespaces present at the beginning and at the end. To remove spaces, we can use the trim() method; the code given below illustrates this.
How Does the trim() Method Work in Java?
The Unicode value for space character is ‘\u0020’ . When the code is being processed in Java, the trim in Java checks whether the Unicode value ‘\u0020’ is present before and after the given string. If the Unicode value ‘\u0020’ is present, then the trim in Java eliminates the spaces and returns a new string.
- The trim() in Java returns a new String object with no leading and trailing spaces.
- The original string is not modified by this method.
- The trim() in Java does not remove the spaces present in the middle of the string.
trim() vs replaceAll()
The trim() method only removes leading and trailing whitespaces, whereas the replaceAll() method removes all the whitespaces present in the string(including leading and trailing).
Now let’s understand the difference between the two with the help of examples.
Example 1: Java String trim()
Explanation of the Example:
In the above example, we are given a string » This is an example » . The given string has 1 leading space and 4 trailing spaces. Now, upon compiling the code, the trim in Java would encounter 1 ‘\u0020’ characters at the beginning and 4 ‘\u0020’ characters at the end. Thus it would eliminate all these characters and return a new string that would output «This is an example» .
Example 2: Remove All Whitespace Characters
In the above sections, we have learned how to remove leading and trailing spaces in a string. But what if we have to remove all the whitespaces present in the string?
We can use the replaceAll() method in Java to remove all the whitespace characters from a string.
The following example shows how we can remove all whitespace characters from a string:
Explanation of the Example:
In the above example, we are given the string » This is an example » and we are supposed to remove all whitespace characters. To achieve this we are using str1.replaceAll() method.
Our first parameter is a regex notion for whitespace characters and our second parameter is an empty string. Thus, the replaceAll() method will replace all the whitespace characters present in the string with an empty string and we will get a new string with «Thisisanexample» as a result.
Conclusion
- trim() in Java removes all the leading and trailing spaces in the string.
- It does not take any parameter and returns a new string.
- The Unicode value for space character is ‘\u0020’
- The trim method checks for the Unicode value of the space and eliminates it.
- The trim() in Java does not remove middle spaces.
- If we want to remove all whitespace characters from a string, we need to use the replaceAll() method.
Java String trim() method with examples
We will be starting with a simple example to be familiar with the trim() method.
Before using trim fucntion: ==== codekru ===== After using trim fucntion: ====codekru=====
You can see that leading and trailing spaces were present in the string before using the trim() method, and afterward, there were no.
The What If scenarios
What happens if we use different whitespace from the list we shared and not a normal ‘U + 0020’?
So, let’s use ‘U + 00A0’ whitespace and see how the trim method behaves.
Before using trim fucntion: ==== codekru===== After using trim fucntion: ==== codekru=====
You can see here that the whitespace is not removed. If you want to remove different whitespaces, we recommend using the String class’s strip() method .
What if we use the trim() method on a String containing spaces?
In this case, the method will return an empty string. Remember, the string returned is empty and not null.
Before using trim fucntion: ==== ===== After using trim fucntion: ========= is str2 empty? true
What if we try to use the trim() method on a null string?
Yes, you guessed it right. It will give us NullPointerException as shown using the below code.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.trim()" because "in" is null
Does the trim() method return the same string reference if it doesn’t remove any whitespaces?
We know it’s not a what-if scenario, but we still want to put it there. And the answer to the question is Yes. Let’s see it with an example.
public class Codekru < public static void main(String[] args) < String str1 = "codekru"; String str2 = str1.trim(); if (str1 == str2) < System.out.println("str1 and str2 pointing to the same reference"); >else < System.out.println("str1 and str2 are not pointing to the same reference"); >> >
str1 and str2 pointing to the same reference
If you want to know more about strings and their methods, we recommend reading this article .
We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected].
15.30. Java – Метод trim()
Метод trim() – возвращает копию строки с пропущенными начальными и конечными пробелами, другими словами метод позволяет в Java удалить пробелы в начале и конце строки.
Синтаксис
Параметры
Подробная информация о параметрах:
Возвращаемое значение
- В Java trim() возвращает копию данной строки, в которой удаляются начальные и конечные пробелы, или данную строку, если она не имеет начальных или конечных пробелов.
Пример
import java.io.*; public class Test < public static void main(String args[])< String Str = new String(" Добро пожаловать на ProgLang.su "); System.out.print("Возвращаемое значение: "); System.out.println(Str.trim()); >>
Получим следующий результат:
Возвращаемое значение: Добро пожаловать на ProgLang.su
Оглавление
- 1. Java – Самоучитель для начинающих
- 2. Java – Обзор языка
- 3. Java – Установка и настройка
- 4. Java – Синтаксис
- 5. Java – Классы и объекты
- 6. Java – Конструкторы
- 7. Java – Типы данных и литералы
- 8. Java – Типы переменных
- 9. Java – Модификаторы
- 10. Java – Операторы
- 11. Java – Циклы и операторы цикла
- 11.1. Java – Цикл while
- 11.2. Java – Цикл for
- 11.3. Java – Улучшенный цикл for
- 11.4. Java – Цикл do..while
- 11.5. Java – Оператор break
- 11.6. Java – Оператор continue
- 12. Java – Операторы принятия решений
- 12.1. Java – Оператор if
- 12.2. Java – Оператор if..else
- 12.3. Java – Вложенный оператор if
- 12.4. Java – Оператор switch..case
- 12.5. Java – Условный оператор (? 🙂
- 13. Java – Числа
- 13.1. Java – Методы byteValue(), shortValue(), intValue(), longValue(), floatValue(), doubleValue()
- 13.2. Java – Метод compareTo()
- 13.3. Java – Метод equals()
- 13.4. Java – Метод valueOf()
- 13.5. Java – Метод toString()
- 13.6. Java – Метод parseInt()
- 13.7. Java – Метод Math.abs()
- 13.8. Java – Метод Math.ceil()
- 13.9. Java – Метод Math.floor()
- 13.10. Java – Метод Math.rint()
- 13.11. Java – Метод Math.round()
- 13.12. Java – Метод Math.min()
- 13.13. Java – Метод Math.max()
- 13.14. Java – Метод Math.exp()
- 13.15. Java – Метод Math.log()
- 13.16. Java – Метод Math.pow()
- 13.17. Java – Метод Math.sqrt()
- 13.18. Java – Метод Math.sin()
- 13.19. Java – Метод Math.cos()
- 13.20. Java – Метод Math.tan()
- 13.21. Java – Метод Math.asin()
- 13.22. Java – Метод Math.acos()
- 13.23. Java – Метод Math.atan()
- 13.24. Java – Метод Math.atan2()
- 13.25. Java – Метод Math.toDegrees()
- 13.26. Java – Метод Math.toRadians()
- 13.27. Java – Метод Math.random()
- 14. Java – Символы
- 14.1. Java – Метод Character.isLetter()
- 14.2. Java – Метод Character.isDigit()
- 14.3. Java – Метод Character.isWhitespace()
- 14.4. Java – Метод Character.isUpperCase()
- 14.5. Java – Метод Character.isLowerCase()
- 14.6. Java – Метод Character.toUpperCase()
- 14.7. Java – Метод Character.toLowerCase()
- 14.8. Java – Метод Character.toString()
- 15. Java – Строки
- 15.1. Java – Метод charAt()
- 15.2. Java – Метод compareTo()
- 15.3. Java – Метод compareToIgnoreCase()
- 15.4. Java – Метод concat()
- 15.5. Java – Метод contentEquals()
- 15.6. Java – Метод copyValueOf()
- 15.7. Java – Метод endsWith()
- 15.8. Java – Метод equals()
- 15.9. Java – Метод equalsIgnoreCase()
- 15.10. Java – Метод getBytes()
- 15.11. Java – Метод getChars()
- 15.12. Java – Метод hashCode()
- 15.13. Java – Метод indexOf()
- 15.14. Java – Метод intern()
- 15.15. Java – Метод lastIndexOf()
- 15.16. Java – Метод length()
- 15.17. Java – Метод matches()
- 15.18. Java – Метод regionMatches()
- 15.19. Java – Метод replace()
- 15.20. Java – Метод replaceAll()
- 15.21. Java – Метод replaceFirst()
- 15.22. Java – Метод split()
- 15.23. Java – Метод startsWith()
- 15.24. Java – Метод subSequence()
- 15.25. Java – Метод substring()
- 15.26. Java – Метод toCharArray()
- 15.27. Java – Метод toLowerCase()
- 15.28. Java – Метод toString()
- 15.29. Java – Метод toUpperCase()
- 15.30. Java – Метод trim()
- 15.31. Java – Метод valueOf()
- 15.32. Java – Классы StringBuilder и StringBuffer
- 15.32.1. Java – Метод append()
- 15.32.2. Java – Метод reverse()
- 15.32.3. Java – Метод delete()
- 15.32.4. Java – Метод insert()
- 15.32.5. Java – Метод replace()
- 16. Java – Массивы
- 17. Java – Дата и время
- 18. Java – Регулярные выражения
- 19. Java – Методы
- 20. Java – Потоки ввода/вывода, файлы и каталоги
- 20.1. Java – Класс ByteArrayInputStream
- 20.2. Java – Класс DataInputStream
- 20.3. Java – Класс ByteArrayOutputStream
- 20.4. Java – Класс DataOutputStream
- 20.5. Java – Класс File
- 20.6. Java – Класс FileReader
- 20.7. Java – Класс FileWriter
- 21. Java – Исключения
- 21.1. Java – Встроенные исключения
- 22. Java – Вложенные и внутренние классы
- 23. Java – Наследование
- 24. Java – Переопределение
- 25. Java – Полиморфизм
- 26. Java – Абстракция
- 27. Java – Инкапсуляция
- 28. Java – Интерфейсы
- 29. Java – Пакеты
- 30. Java – Структуры данных
- 30.1. Java – Интерфейс Enumeration
- 30.2. Java – Класс BitSet
- 30.3. Java – Класс Vector
- 30.4. Java – Класс Stack
- 30.5. Java – Класс Dictionary
- 30.6. Java – Класс Hashtable
- 30.7. Java – Класс Properties
- 31. Java – Коллекции
- 31.1. Java – Интерфейс Collection
- 31.2. Java – Интерфейс List
- 31.3. Java – Интерфейс Set
- 31.4. Java – Интерфейс SortedSet
- 31.5. Java – Интерфейс Map
- 31.6. Java – Интерфейс Map.Entry
- 31.7. Java – Интерфейс SortedMap
- 31.8. Java – Класс LinkedList
- 31.9. Java – Класс ArrayList
- 31.10. Java – Класс HashSet
- 31.11. Java – Класс LinkedHashSet
- 31.12. Java – Класс TreeSet
- 31.13. Java – Класс HashMap
- 31.14. Java – Класс TreeMap
- 31.15. Java – Класс WeakHashMap
- 31.16. Java – Класс LinkedHashMap
- 31.17. Java – Класс IdentityHashMap
- 31.18. Java – Алгоритмы Collection
- 31.19. Java – Iterator и ListIterator
- 31.20. Java – Comparator
- 32. Java – Дженерики
- 33. Java – Сериализация
- 34. Java – Сеть
- 34.1. Java – Обработка URL
- 35. Java – Отправка Email
- 36. Java – Многопоточность
- 36.1. Java – Синхронизация потоков
- 36.2. Java – Межпоточная связь
- 36.3. Java – Взаимная блокировка потоков
- 36.4. Java – Управление потоками
- 37. Java – Основы работы с апплетами
- 38. Java – Javadoc