This write-up will explain a couple of approaches for declaring a string in java:
So, let’s get started!
How to declare a string using String literals?
In java, a string literal can be declared using the double quotes “”. The below-given syntax will provide you with more clarity about the string literals:
When we declare a String Object as a literal, consequently, the JVM verifies it from the “string constant pool”. If the string already exists then the JVM will return the reference of the already created string literal. However, if the string doesn’t exist in the pool then a new object will be created in the String constant pool.
Example: how to declare a string literal in Java?
System.out.println(stringObj);
In this program, firstly, we declared a string literal and afterward we printed the value assigned to the string using println() method:
This is how we can declare a string literal in Java.
How to declare a string using a new keyword?
In Java, we can declare a string using a new keyword. The below-given syntax will provide you with more clarity about the string literals.
The new keyword will declare two objects (i.e. one in the String pool while the other one in the heap) and one reference variable.
Example: how to declare a string using the new keyword in Java?
System.out.println(stringObj);
In the above-given piece of code, initially, we declared a string using the new keyword and afterward we utilized the println() method to print the string’s value:
In this way, we can declare a string using the new keyword.
Conclusion
The new keyword and string literals are used to declare a string in Java. In Java, it is preferred to use the string literals for string declaration. Because the string literals don’t create a new object if it already exists, therefore, the string literals provide more memory efficiency and memory optimization. This write-up considered a couple of examples to explain how to declare a string in java.