String() constructor
The String constructor is used to create a new String object. When called instead as a function, it performs type conversion to a primitive string, which is usually more useful.
Syntax
Note: String() can be called with or without new , but with different effects. See Return value.
Parameters
Anything to be converted to a string.
Return value
When String is called as a constructor (with new ), it creates a String object, which is not a primitive.
When String is called as a function, it coerces the parameter to a string primitive. Symbol values would be converted to «Symbol(description)» , where description is the description of the Symbol, instead of throwing.
Warning: You should rarely find yourself using String as a constructor.
Examples
String constructor and String function
String function and String constructor produce different results:
Here, the function produces a string (the primitive type) as promised. However, the constructor produces an instance of the type String (an object wrapper) and that’s why you rarely want to use the String constructor at all.
Using String() to stringify a symbol
String() is the only case where a symbol can be converted to a string without throwing, because it’s very explicit.
What is the purpose of the expression "new String(. )" in Java?
While looking at online code samples, I have sometimes come across an assignment of a String constant to a String object via the use of the new operator.
This, of course, compared to
I’m not familiar with this syntax and have no idea what the purpose or effect would be. Since String constants typically get stored in the constant pool and then in whatever representation the JVM has for dealing with String constants, would anything even be allocated on the heap?
9 Answers 9
The one place where you may think you want new String(String) is to force a distinct copy of the internal character array, as in
However, this behavior is unfortunately undocumented and implementation dependent.
I have been burned by this when reading large files (some up to 20 MiB) into a String and carving it into lines after the fact. I ended up with all the strings for the lines referencing the char[] consisting of entire file. Unfortunately, that unintentionally kept a reference to the entire array for the few lines I held on to for a longer time than processing the file — I was forced to use new String() to work around it, since processing 20,000 files very quickly consumed huge amounts of RAM.
The only implementation agnostic way to do this is:
This unfortunately must copy the array twice, once for toCharArray() and once in the String constructor.
There needs to be a documented way to get a new String by copying the chars of an existing one; or the documentation of String(String) needs to be improved to make it more explicit (there is an implication there, but it’s rather vague and open to interpretation).
Pitfall of Assuming what the Doc Doesn’t State
In response to the comments, which keep coming in, observe what the Apache Harmony implementation of new String() was:
That’s right, no copy of the underlying array there. And yet, it still conforms to the (Java 7) String documentation, in that it:
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
The salient piece being «copy of the argument string«; it does not say «copy of the argument string and the underlying character array supporting the string».
Be careful that you program to the documentation and not one implementation.
Class String
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
is equivalent to:
Here are some more examples of how strings can be used:
The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String .
The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.
Работа со строками
Строка представляет собой последовательность символов. Для работы со строками в Java определен класс String, который предоставляет ряд методов для манипуляции строками. Физически объект String представляет собой ссылку на область в памяти, в которой размещены символы.
Для создания новой строки мы можем использовать один из конструкторов класса String, либо напрямую присвоить строку в двойных кавычках:
При работе со строками важно понимать, что объект String является неизменяемым ( immutable ). То есть при любых операциях над строкой, которые изменяют эту строку, фактически будет создаваться новая строка.
Поскольку строка рассматривается как набор символов, то мы можем применить метод length() для нахождения длины строки или длины набора символов:
А с помощью метода toCharArray() можно обратно преобразовать строку в массив символов:
Строка может быть пустой. Для этого ей можно присвоить пустые кавычки или удалить из стоки все символы:
В этом случае длина строки, возвращаемая методом length(), равна 0.
Класс String имеет специальный метод, который позволяет проверить строку на пустоту — isEmpty() . Если строка пуста, он возвращает true:
Переменная String может не указывать на какой-либо объект и иметь значение null :
Значение null не эквивалентно пустой строке. Например, в следующем случае мы столкнемся с ошибкой выполнения:
Так как переменная не указывает ни на какой объект String, то соответственно мы не можем обращаться к методам объекта String. Чтобы избежать подобных ошибок, можно предварительно проверять строку на null:
Основные методы класса String
Основные операции со строками раскрывается через методы класса String, среди которых можно выделить следующие:
concat() : объединяет строки
valueOf() : преобразует объект в строковый вид
join() : соединяет строки с учетом разделителя
сompareTo() : сравнивает две строки
charAt() : возвращает символ строки по индексу
getChars() : возвращает группу символов
equals() : сравнивает строки с учетом регистра
equalsIgnoreCase() : сравнивает строки без учета регистра
regionMatches() : сравнивает подстроки в строках
indexOf() : находит индекс первого вхождения подстроки в строку
lastIndexOf() : находит индекс последнего вхождения подстроки в строку
startsWith() : определяет, начинается ли строка с подстроки
endsWith() : определяет, заканчивается ли строка на определенную подстроку
replace() : заменяет в строке одну подстроку на другую
trim() : удаляет начальные и конечные пробелы
substring() : возвращает подстроку, начиная с определенного индекса до конца или до определенного индекса