Last Updated:

String Class in Java: Examples

String Class in Java

A string in Java is an element consisting of a sequence of characters. The tool has become widespread, refers to the number of objects. The String class is in the Java programming language and is used to work with specified components. There are features and hints that make the work easier.

General description of the String class

The public final java.lang.String class is presented just to create strings and manipulate them. The presence of subclasses in this case is unacceptable. Any changes are also not expected. Sometimes it seems that methods have the right to make adjustments, but such thoughts are misconceptions.

The methods only help create and return new rows that store the results of operations.

Due to the immutability of the lines, a number of possibilities appear:

  1. Strings as keys in HashMap. It is recommended that you make sure that the element cannot be changed.
  2. StringPool support—Denotes a collection of references to String objects. Helps optimize memory.
  3. Combined with multi-threaded environments.

Creation rules

A String object is created in several ways:

  • With the participation of string literals.

String habr = “habrahabr”.

This name denotes a symbolic sequence that is enclosed in double quotation marks. An object with a literal value is always created if you use a string compiler:

System.out.print(«habrahabr»); created an object and displayed its value

  • Constructors.

String habr = «habrahabr»;

char[] habrAsArrayOfChars = {‘h’, ‘a’, ‘b’, ‘r’, ‘a’, ‘h’, ‘a’, ‘b’, ‘r’};

byte[] habrAsArrayOfBytes = {104, 97, 98, 114, 97, 104, 97, 98, 114};

String first = new String();

String second = new String(habr);

But it is better to abandon the constructors if you can clearly do without a copy of a particular line. After all, the element itself remains unchanged. Performance is degraded if you consistently use this method when constructing strings. It is better to give preference to similar initializations, to resort to the help of string literals.

String third = new String(habrAsArrayOfChars); «habrahabr»

String fourth = new String(habrAsArrayOfChars, 0, 4); «habr»

A string object in Java can be formed from a character array. The entire array is copied by using static type methods labeled copyOfRange and copyOf. Accordingly, this is a copy of the entire array, or only a certain part of it.

The last option is relevant when specifying the 2nd and 3rd parameters in the constructor. The required class in this case is Arrays. In turn, the parameters themselves assume reliance on System.arraycopy - this is a platform-dependent implementation.

When you create a string object, you can use a byte array. The encoding parameter of the Charset class can be redone. The specified encoding contributes to the organization of the decoding of the array. The encoding may affect a parameter called Charset.defaultCharset().

It is always used, unless otherwise indicated. The resulting character array is copied to the object value.

Finally, you can use the StringBuffer, StringBuilder, and length (length()) constructors to create a string.

In fact, the number of constructors for strings reaches 15, above are only the most common types.

Length

When working with Java strings, this is an important element. To recognize this characteristic, it is enough to access the String object with the usual accessory method. (accessor method) length (). Then the number of characters in the string is returned, it is easier to determine the length of the Java string.

Description of concatenation

This is the name of the string concatenation operation. A new row is returned, which is the result of the concatenation of the second line and the end of the first. Two methods are used on the String object when performing the operation:

  1. The concat method. Here, the string is not changed. Only create a new one that is the result of merging the current one and the one that is passed as a parameter. A new String object is returned, so you can create really long chains.
  2. Operators "+" and "+=" with overload. The programming language in Java does not allow you to overload statements to perform one of these actions. But in the operator "+" the concat method also does not pass, the mechanism will differ from other solutions. As well as the use of string and trim Java methods.

For a one-time merge, only the Concat method is selected. In other cases, choose between the "+" operator and StringBuilder/StringBuffer. However, with the "+" operator, you cannot get a NullPointerException if at least one operand is null.

Another thing is the concat method, the substring of Java.

Formatting

In the String class, you can choose not to create formatted strings. To do this, they turn to the statistical method format. It also helps with the Java length parameter.

About common methods

The manipulation of a string and its characters is simplified by a large number of methods. Oracle has numerous articles on each of the available tools. Except that special mention deserves join - one of the statistical methods that appeared recently. You can now use delimiters to conveniently combine multiple rows into one.

The added java.lang.StringJoiner class is responsible for this option.

StringBuffer

The creation of new objects is caused by frequent modifications of strings, which in themselves remain unchanged elements. Because of this, more memory is consumed each time. To solve this problem, use the newly created java.lang.StringBuffer class. The tool is needed to increase the efficiency of working with string modifications.

This is a variable class with the designation marble. If the content of the line requires changes, you need to use the available functionality. All the necessary methods are synchronized, which makes it possible to use StringBuffer for multi-line environments.

StringBuilder

StringBuilder is the designation of a class that essentially becomes a variable sequence of characters. It first appeared in the 5th version of Java, the API is almost identical to StringBuffer. The lack of synchronization becomes the only difference between these two classes. Therefore, it is not desirable to use the tool when working with multi-threaded environments.

About string comparisons

The identity of the strings is easily checked with the Boolean equals (Object and Object) parameter. Only if there is the same sequence of characters with the same value is True returned.

Another important parameter for resolving the issue is int compareTo (String anotherString). Can contain negative or positive integers, depending on consecutive strings.

Findings

 

When getting acquainted with the main elements, further work with strings is not so difficult. It is important to repeat the exercises and the main details of the code several times in order to quickly memorize the information. It will not hurt to apply the knowledge gained in practice, including in the implementation of your own projects. Then the main parameters are remembered faster. You can write them out separately in order to quickly find them at the appropriate moments.