Java

How to declare a String in Java

Java offers a couple of approaches for declaring a string, for example using double quotes and using a new keyword. The strings declared with double quotes are referred to as string literals. In Java, strings are nothing but an array/sequence of characters. There are multiple built-in methods that can be used with the strings to perform various operations on the strings. However, to perform any action/task on a string, firstly, we have to declare a string.

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:

String stringObj = "string literal example";

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?

String stringObj = "Welcome to Linuxhint.com";
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.

String stringObj = new String("string literal example");

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?

String stringObj = new String("www.linuxhint.com");
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.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.