How to add string to string java

How to add string to string java

In java, how would I add a string to a string variable?

I have code that generates a random number form 0-1 3 times and I need it to be added to a variable so it turns into a binary number.So, in theory, this would run three times and possibly give me 101;

But when I try and run this I get the NullPointerException error for storage. Is there a way to just «add» a string to the variable?

the method giveMeBinary just returns a 0 or a 1.

10 Answers 10

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Your problem is that you are initializing the string to null. Doing something like so should solve your problem:

However, concatenating strings in such a manner is not recommended. What you can do is use a StringBuilder like so:

You get the NullPointerException because you set the variable storage to null. You should start with

How to add string to string java. Смотреть фото How to add string to string java. Смотреть картинку How to add string to string java. Картинка про How to add string to string java. Фото How to add string to string java

If you want to use String concatenation then just initialise storage to «» (empty string) then use

but if you are looping and building Strings you should really use StringBuilder since Strings are immutable

You have two problems:

You’re assuming String.concat will modify the existing string value. It doesn’t. Strings are immutable in Java.

I would suggest using a StringBuilder instead, and calling append in the loop:

Quite why you’re then parsing a binary number such as «011» as if it were a decimal number is a different matter. What do you actually want the result to be? Do you really want the numbers 0, 1, 10, 11, 100, 101, 110 or 111?

How to add new text to string without removing old string text?

Suppose I have a string String text = «»; and I add a text to it

now I want it not to remove the old String when I add a new one, like this

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Since String is Immutable then you can’t edit t without reassigning it, however there is something called StringBuilder it is mutable so it can be changed.

original will not be affected expect if did you re assign it, but because of String builder is mutable you can do something like the following

and it should be retrieved as string like this

How to add string to string java. Смотреть фото How to add string to string java. Смотреть картинку How to add string to string java. Картинка про How to add string to string java. Фото How to add string to string java

You want the variable to hold multiple Strings. Yet, you don’t want to append the String. A data structure is what you are looking for.

In this case, ArrayList can fulfill your needs:

You can get the elemebt by the order you added the Strings with index beggining with 0:

To print all the elements from the ArrayList:

There are 2 ways you can achieve your desired output/result:

1. Using String:

You can simply append the new values at the end of String as following.

2. Using StringBuilder: [recommended]

Whereas String class in Java is immutable, so when you append a String in String literal, then it does update the existing object, it does create new object of String in String pool and points the reference to newly created String pool object.

Add character to String in java

In this post, we will see how to add character to String in java.

There are multiple ways to add character to String.

Add character to the start of String

You can add character at start of String using + operator.

Add character to the end of String

You can add character at start of String using + operator.

Further reading

How to compare characters in Java

Java remove last character from string

How to check if String has all unique characters in java

Here is the complete program to add character at start and end of the String.

Output:

Add character to String at given postion

There are several methods to add Add character to String at given position.

Using StringBuffer

You can use StringBuffer’s insert() method to add character to String at given position.
Let’s see with the help of an example.

Output:

In case, you want thread safe code, then you should use StringBuffer instead of StringBuilder.

Using substring

You can also use String’s substring method to add character to String at given position.
Let’s see with the help of an example.

Output:

Although this looks easy and readable solution, there is disadvantage of using this approach.

As we already know String is immutable in java. Each substring call creates new String object.

When we use + operator to concatenate string, it internally creates StringBuffer objects as well.

If we need to call this method many times, then this may cause frequent garbage collection as heap memory will be filled faster due to temporary objects.

Обработка строк в Java. Часть I: String, StringBuffer, StringBuilder

Вступление

Что вы знаете о обработке строк в Java? Как много этих знаний и насколько они углублены и актуальны? Давайте попробуем вместе со мной разобрать все вопросы, связанные с этой важной, фундаментальной и часто используемой частью языка. Наш маленький гайд будет разбит на две публикации:

String

Строка — объект, что представляет последовательность символов. Для создания и манипулирования строками Java платформа предоставляет общедоступный финальный (не может иметь подклассов) класс java.lang.String. Данный класс является неизменяемым (immutable) — созданный объект класса String не может быть изменен. Можно подумать что методы имеют право изменять этот объект, но это неверно. Методы могут только создавать и возвращать новые строки, в которых хранится результат операции. Неизменяемость строк предоставляет ряд возможностей:

Создание

Мы можем создать объект класса String несколькими способами:

1. Используя строковые литералы:

Строковый литерал — последовательность символов заключенных в двойные кавычки. Важно понимать, что всегда когда вы используете строковой литерал компилятор создает объект со значением этого литерала:

2. С помощью конструкторов:

Если копия строки не требуется явно, использование этих конструкторов нежелательно и в них нет необходимости, так как строки являются неизменными. Постоянное строительство новых объектов таким способом может привести к снижению производительности. Их лучше заменить на аналогичные инициализации с помощью строковых литералов.

Конструкторы могут формировать объект строки с помощью массива символов. Происходит копирование массива, для этого используются статические методы copyOf и copyOfRange (копирование всего массива и его части (если указаны 2-й и 3-й параметр конструктора) соответственно) класса Arrays, которые в свою очередь используют платформо-зависимую реализацию System.arraycopy.

Можно также создать объект строки с помощью массива байтов. Дополнительно можно передать параметр класса Charset, что будет отвечать за кодировку. Происходит декодирование массива с помощью указанной кодировки (если не указано — используется Charset.defaultCharset(), который зависит от кодировки операционной системы) и, далее, полученный массив символов копируется в значение объекта.

Ну и наконец-то конструкторы использующие объекты StringBuffer и StringBuilder, их значения (getValue()) и длину (length()) для создания объекта строки. С этими классами мы познакомимся чуть позже.

Приведены примеры наиболее часто используемых конструкторов класса String, на самом деле их пятнадцать (два из которых помечены как deprecated).

Длина

Важной частью каждой строки есть ее длина. Узнать ее можно обратившись к объекту String с помощью метода доступа (accessor method) length(), который возвращает количество символов в строке, например:

Конкатенация

Конкатенация — операция объединения строк, что возвращает новую строку, что есть результатом объединения второй строки с окончанием первой. Операция для объекта String может быть выполнена двумя способами:

1. Метод concat

Важно понимать, что метод concat не изменяет строку, а лишь создает новую как результат слияния текущей и переданной в качестве параметра. Да, метод возвращает новый объект String, поэтому возможны такие длинные «цепочки».

2. Перегруженные операторы «+» и «+=«

Это одни с немногих перегруженных операторов в Java — язык не позволяет перегружать операции для объектов пользовательских классов. Оператор «+» не использует метод concat, тут используется следующий механизм:

Используйте метод concat, если слияние нужно провести только один раз, для остальных случаев рекомендовано использовать или оператор «+» или StringBuffer / StringBuilder. Также стоит отметить, что получить NPE (NullPointerException), если один с операндов равен null, невозможно с помощью оператора «+» или «+=«, чего не скажешь о методе concat, например:

Форматирование

Класс String предоставляет возможность создания форматированных строк. За это отвечает статический метод format, например:

Методы

Благодаря множеству методов предоставляется возможность манипулирования строкой и ее символами. Описывать их здесь нет смысла, потому что Oracle имеет хорошие статьи о манипулировании и сравнении строк. Также у вас под рукой всегда есть их документация. Хотелось отметить новый статический метод join, который появился в Java 8. Теперь мы можем удобно объединять несколько строк в одну используя разделитель (был добавлен класс java.lang.StringJoiner, что за него отвечает), например:

Это не единственное изменение класса в Java 8. Oracle сообщает о улучшении производительности в конструкторе String(byte[], *) и методе getBytes().

Преобразование

1. Число в строку
2. Строку в число

StringBuffer

Строки являются неизменными, поэтому частая их модификация приводит к созданию новых объектов, что в свою очередь расходует драгоценную память. Для решения этой проблемы был создан класс java.lang.StringBuffer, который позволяет более эффективно работать над модификацией строки. Класс является mutable, то есть изменяемым — используйте его, если Вы хотите изменять содержимое строки. StringBuffer может быть использован в многопоточных средах, так как все необходимые методы являются синхронизированными.

Создание

Существует четыре способа создания объекта класса StringBuffer. Каждый объект имеет свою вместимость (capacity), что отвечает за длину внутреннего буфера. Если длина строки, что хранится в внутреннем буфере, не превышает размер этого буфера (capacity), то нет необходимости выделять новый массив буфера. Если же буфер переполняется — он автоматически становиться больше.

Модификация

В большинстве случаев мы используем StringBuffer для многократного выполнения операций добавления (append), вставки (insert) и удаления (delete) подстрок. Тут все очень просто, например:

Все остальные методы для работы с StringBuffer можно посмотреть в документации.

StringBuilder

StringBuilder — класс, что представляет изменяемую последовательность символов. Класс был введен в Java 5 и имеет полностью идентичный API с StringBuffer. Единственное отличие — StringBuilder не синхронизирован. Это означает, что его использование в многопоточных средах есть нежелательным. Следовательно, если вы работаете с многопоточностью, Вам идеально подходит StringBuffer, иначе используйте StringBuilder, который работает намного быстрее в большинстве реализаций. Напишем небольшой тест для сравнения скорости работы этих двух классов:

Спасибо за внимание. Надеюсь статья поможет узнать что-то новое и натолкнет на удаление всех пробелов в этих вопросах. Все дополнения, уточнения и критика приветствуются.

How to add string to string java

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.

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.

Field Summary

Fields

Constructor Summary

Method Summary

Modifier and TypeFieldDescription
static ComparatorCASE_INSENSITIVE_ORDER
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods

Modifier and TypeMethodDescription
charcharAt ​(int index)
voidgetBytes ​(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
voidgetChars ​(int srcBegin, int srcEnd, char[] dst, int dstBegin)
booleanregionMatches ​(boolean ignoreCase, int toffset, String other, int ooffset, int len)

Methods declared in class java.lang.Object

Field Detail

CASE_INSENSITIVE_ORDER

Note that this Comparator does not take locale into account, and will result in an unsatisfactory ordering for certain locales. The Collator class provides locale-sensitive comparison.

Constructor Detail

String

String

String

String

String

String

The offset argument is the index of the first byte of the subarray, and the count argument specifies the length of the subarray.

Each byte in the subarray is converted to a char as specified in the String(byte[],int) constructor.

String

String

The behavior of this constructor when the given bytes are not valid in the given charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

String

This method always replaces malformed-input and unmappable-character sequences with this charset’s default replacement string. The CharsetDecoder class should be used when more control over the decoding process is required.

String

The behavior of this constructor when the given bytes are not valid in the given charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

String

This method always replaces malformed-input and unmappable-character sequences with this charset’s default replacement string. The CharsetDecoder class should be used when more control over the decoding process is required.

String

The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

String

The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

String

String

Method Detail

length

isEmpty

charAt

If the char value specified by the index is a surrogate, the surrogate value is returned.

codePointAt

codePointBefore

codePointCount

offsetByCodePoints

getChars

The first character to be copied is at index srcBegin ; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin ). The characters are copied into the subarray of dst starting at index dstBegin and ending at index:

getBytes

getBytes

The behavior of this method when this string cannot be encoded in the given charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

getBytes

This method always replaces malformed-input and unmappable-character sequences with this charset’s default replacement byte array. The CharsetEncoder class should be used when more control over the encoding process is required.

getBytes

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

equals

contentEquals

contentEquals

equalsIgnoreCase

Note that this method does not take locale into account, and will result in unsatisfactory results for certain locales. The Collator class provides locale-sensitive comparison.

compareTo

compareToIgnoreCase

Note that this method does not take locale into account, and will result in an unsatisfactory ordering for certain locales. The Collator class provides locale-sensitive comparison.

regionMatches

Note that this method does not take locale into account. The Collator class provides locale-sensitive comparison.

regionMatches

startsWith

startsWith

endsWith

hashCode

indexOf

indexOf

All indices are specified in char values (Unicode code units).

lastIndexOf

lastIndexOf

All indices are specified in char values (Unicode code units).

indexOf

indexOf

lastIndexOf

lastIndexOf

substring

substring

subSequence

An invocation of this method of the form

concat

replace

matches

contains

replaceFirst

replaceAll

replace

split

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

    If the limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

    If the limit is negative then the pattern will be applied as many times as possible and the array can have any length.

    Split example showing regex, limit, and result

    RegexLimitResult
    :2
    5
    -2
    o5
    -2
    0

    split

    This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

    Split examples showing regex and result

    RegexResult
    :
    o

    toLowerCase

    toLowerCase

    toUpperCase

    toUpperCase

    If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes that are not space (as defined above), then a reference to this String object is returned.

    Otherwise, if all characters in this string are space (as defined above), then a String object representing an empty string is returned.

    This method may be used to trim space (as defined above) from the beginning and end of a string.

    strip

    This method may be used to strip white space from the beginning and end of a string.

    stripLeading

    Otherwise, returns a substring of this string beginning with the first code point that is not a white space up to to and including the last code point of this string.

    This method may be used to trim white space from the beginning of a string.

    stripTrailing

    This method may be used to trim white space from the end of a string.

    isBlank

    lines

    A line terminator is one of the following: a line feed character «\n» (U+000A), a carriage return character «\r» (U+000D), or a carriage return followed immediately by a line feed «\r\n» (U+000D U+000A).

    A line is either a sequence of zero or more characters followed by a line terminator, or it is a sequence of one or more characters followed by the end of the string. A line does not include the line terminator.

    The stream returned by this method contains the lines from this string in the order in which they occur.

    toString

    chars

    codePoints

    toCharArray

    format

    The locale always used is the one returned by Locale.getDefault(Locale.Category) with FORMAT category specified.

    format

    valueOf

    valueOf

    valueOf

    The offset argument is the index of the first character of the subarray. The count argument specifies the length of the subarray. The contents of the subarray are copied; subsequent modification of the character array does not affect the returned string.

    copyValueOf

    copyValueOf

    valueOf

    valueOf

    valueOf

    The representation is exactly the one returned by the Integer.toString method of one argument.

    valueOf

    The representation is exactly the one returned by the Long.toString method of one argument.

    valueOf

    The representation is exactly the one returned by the Float.toString method of one argument.

    valueOf

    The representation is exactly the one returned by the Double.toString method of one argument.

    intern

    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    repeat

    If this string is empty or count is zero then the empty string is returned.

    Report a bug or suggest an enhancement
    For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
    Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
    Copyright © 1993, 2022, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
    All rights reserved. Use is subject to license terms and the documentation redistribution policy.

    Источники информации:

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *