Any sequence of characters enclosed within double quotes (“ ”) is known as a string in Java. For Example: “Hello!! How are you?” is a string in Java programming language.
In Java, all objects of the String data type are immutable. This means that the object of the string type cannot be changed once it has been created and it remains as a constant.
Creating String in Java
The class used for creating and manipulation of string objects in Java is the java.lang.String class. There are two ways to create a String in Java.
Let us have a look at these ways of String creation one at a time.
String creation by using String Literal
This is the easiest and most direct way to create a String in Java. In order to create an object of String type with this approach, follow the following syntax.
Syntax: String Var_name = “<<text of the string>>”;
Have a look at the example.
For Example: String name = “Sunita”;
Here, we are creating a String object with the variable name as ‘name’ and the content as ‘Sunita’. Now, whenever the compiler will encounter the String object, then it will initialize it with its corresponding value i.e. “Sunita” in this example.
The problem with this approach is that whenever a new object is created and if it is already present in the memory (also referred to as the String pool) then a new object is not created rather a reference to the previously created object is returned.
Let us understand this with the help of an example.
In this example, we are creating three Strings. The first string str1 is created with a literal “Hello” and the second string str2 is created with a literal “Welcome”. Now when the third string str3 is created with the value “Hello” a reference to the previously created object is returned.
To overcome this problem, we make use of the new keyword in Java. Now, let us have a look at the concept of the new keyword.
String creation by using new keyword
When creating strings using the new keyword, the following syntax is used.
String var_name = new String (“<<String value>>”);
Let us take the same example as discussed previously.
String str1 = new String ("Hello"); String str2 = new String ("Welcome"); String str3 = new String ("Hello");
Now in this case, all the three strings i.e. str1, str2 as well as str3 will create three different objects in memory even if they are having the same string value.
Creating String in Java
There is yet another way of creating strings in Java. The String class has 11 constructors that allow you to create strings by providing the constructor with the initial value of the string and using it to make various strings.
One such method is to create strings by using an array of characters. Have a look at the example below.
For Example:
public class StrDemo { public static void main (String args[]) { char[] arr = {'w', 'e' ,'l', 'c', 'o', 'm', 'e'}; String str = new String (arr); System.out.println (str); } }
Output: