Apps/Gaming

String objects in Java

Strings are one of the most common types of data in any Java program. They come with special support from the Java libraries. Unlike many programming languages ​​that define strings as arrays, Java defines strings as objects instead. In addition, Java strings are immutable. This means that they cannot be changed after initialization.

This property of Java strings as immutable objects leads to interesting properties, which are explored in detail in this tutorial on Java programming.

How to create strings in Java

There are three ways a developer can create a string in Java. The first way is to pass a message to the String constructor, as shown in the following code snippet: String s1 = new String (“Hello”);

The above instruction creates an object s1 of the type String and assigns it the value “Hello”.

The second way to create a string in Java is to pass it an array of character values, as shown below:

char[] p = {‘W’, ‘o’, ‘r’, ‘l’, ‘d’}; String s2 = new string (p);

The third method is to assign a string literal to a variable of type String. Java provides this as a shortcut for the first method shown, since strings are a commonly used data type.

String s3 = “Yes”;

You are probably more familiar with the above syntax because it is the most widely used. Later in this article, you will see how the syntaxes shown earlier differ in execution from the latter.

It is interesting to note that a String literal can be used anywhere a String object can be used. See the following example:

System.out.println (“apples” .length ());

Note that the apples string literal is used with the length () method. This method is used with String objects to return the length of a string.

Here it was used with a string literal and still returns its character length (e.g. 6) to println without errors.

Read: How to print an array in Java

Internal strings in Java

Java offers a way to save memory in case you have multiple strings with the same string in your program. It does this by returning the address of a matching string if it already exists in the storage pool. This is known as string interning.

Consider the following Java code example:

public class Fruits {public static void main (String args[]) {String s1 = “Mango”; String s2 = new String (“Mango”); String s3 = “Mango”; if (s1 == s2) {System.out.println (“s1 and s2 have the same reference”); } else {System.out.println (“s1 and s2 have different references”); // this is done} if (s1 == s3) {System.out.println (“s1 and s3 have the same reference”); // this is done} else {System.out.println (“s1 and s3 have different references”);}}}

When s1 is initialized with a string literal, the Java Virtual Machine (JVM) checks whether the same string is in the memory heap. If an internal object already exists for the character string “Mango”, no new object will be created. In this case there is no such object. Therefore a new object – s1 – is created.

However, if the new operator is used, a new address space is created immediately. Therefore s1 and s2 have different references.

When s3 is created with a string initializer, the JVM checks to see if the string already exists (same process as for s1). Since the interned object s1 already exists, no new object is created for s3 in this case. Instead, the reference for s1 is returned.

Now would be a good time to mention that the equality operator == is used to compare memory addresses, not strings. As you noticed in the example above, the strings s1, s2, and s3 all have the same string (“Mango”).

To check if strings have matching strings, consider using the equals () method instead, as shown here:

if (s1.equals (s2)) {// s1 and s2 have the same content} if (s3.equals (s1)) {// s3 and s1 have the same content}

By now, you must be wondering whether Java has a way to internalize strings if the string was created with the new keyword. Java actually provides the internal () method for the String class for this purpose.

The internal () method takes no argument. When used, it returns the reference of a String object if it already exists; otherwise a new reference is created:

String str1 = new String (“berry”). Internal (); String str2 = new String (“berry”). Internal (); System.out.println (str1 == str2); // true

Read: Java multithreading explained

StringBuilder and StringBuffer in Java

As mentioned earlier, Java strings are immutable by default. This means that you can no longer change the content of a string that has been created. Consider the following code where we create a string called s4 and assign it the text value “colors”. Then we try to change the value of s4 to ”fruits”:

String s4 = “colors”; s4 = “fruits”;

The above code would cause your compiler to throw an error because you cannot change an immutable data type value. However, Java provides two classes that you can use to write mutable strings whose values ​​can be changed. The classes are StringBuilder and StringBuffer. They are both used in a similar way to the String class.

The difference between the two is that StringBuffer provides thread safety and synchronization while StringBuilder does not. However, because of this, StringBuilder has much better performance. The choice of use ultimately depends on the needs of the programmer and the program environment.

Here is an example of creating a mutable string in Java using the StringBuilder class:

StringBuilder str1 = new StringBuilder (“Java”); // create changeable string, str1 str1.append (“Programmer”); // adds another string to str1

The example shown shows how to create a modifiable string. The append () method is explained in the code comments; it is essentially used to append another string value to an existing mutable string.

Read: An introduction to the JVM threading implementation

Summary of the Java String Objects

Strings in Java are immutable. This has many advantages, including consistency across different program states and better multithreaded performance.

Java also offers string interning so that you can save memory. However, you shouldn’t always use internal () if your program doesn’t have a lot of repeated values. This is because the JVM has limited cache space in the persistent storage pool.

Related posts

Java Primitive Data Types

TechLifely

Questions to Ask During a Project Manager Interview

TechLifely

Reference Types in Java

TechLifely

Leave a Comment