Копировать строку в java

Class StringBuilder

A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

For example, if z refers to a string builder object whose current contents are » start «, then the method call z.append(«le») would cause the string builder to contain » startle «, whereas z.insert(4, «le») would alter the string builder to contain » starlet «.

In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .

Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Читайте также:  Java string charat exception

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

Источник

Скопируйте строку в Java

Скопируйте строку в Java

В языке Java String — это тип данных, в котором хранится последовательность символов. Строка — это класс-оболочка, который предоставляет такие методы, как compare() , replace() и substring() . Объекты сохраняются в куче памяти всякий раз, когда создается экземпляр объекта.

Скопируйте строку в Java

Ниже приведен блок кода, в котором показано, как скопировать строку в Java.

public class StringCopy   public static void main(String[] args)   String first = "First String";  System.out.println("First initially = " + first);  String second = first;  System.out.println("String copy in second = " + second);  first = "Updated string";  System.out.println("First after update = " + first);   String newCopy = String.copyValueOf(first.toCharArray());  System.out.println("Copy using copyValueOf() = " + newCopy);   String copyString = new String(first);  System.out.println("Copy using new = " + copyString);  > > 

В приведенной выше программе строка инициализируется в первой части операции. Представление String first = «First String» создает в памяти экземпляр First String ; кроме того, этот новый строковый адрес сначала присваивается переменной. Это значение печатается методом println() .

Теперь строка String second = first сохраняет первую ссылку во втором экземпляре и печатает значение копии в другой строке. В результате second переменная содержит first ссылку. Затем first = «Updated string» изменит ссылку на первую строку с существующего значения на другую строку в памяти кучи.

Строки Java неизменны по своей природе. Это означает, что когда строка создается, она находится в куче памяти. И когда первой переменной присваивается другое значение, оно не отменяется. Вместо этого переменная теперь ссылается на другую строку из кучи. Ссылки в куче памяти сохраняются в куче, если сборщик мусора не сработает. Функция удаляет переменную из пула константной памяти, если на нее не ссылается никакая переменная.

Другой способ скопировать строку — это метод copyValueOf . Это статический фабричный метод, который принимает в качестве входных данных массив символов. Экземпляр сначала преобразуется в массив символов с помощью функции toCharArray . На последний экземпляр строки ссылается переменная newCopy и печатается в другой строке.

Третий способ скопировать строку — использовать ключевое слово new . Метод создает в памяти два экземпляра: первый содержит значение, а другая переменная copyString хранит ссылку на first переменную.

Ниже приведен блок кода, полученный в результате выполнения вышеуказанной программы.

First initially = First String String copy in second = First String First after update = Updated string Copy using copyValueOf() = Updated string Copy using new = Updated string 

Rashmi is a professional Software Developer with hands on over varied tech stack. She has been working on Java, Springboot, Microservices, Typescript, MySQL, Graphql and more. She loves to spread knowledge via her writings. She is keen taking up new things and adopt in her career.

Сопутствующая статья — Java String

Источник

Оцените статью