String Literal Vs String Object

Both expression gives you String object, but there is subtle difference between them. When you use new String( "Hello World!!" ); , it explicitly creates a new and referentially distinct instance of a String object. It is an individual instance of the java.lang.String class. String s="Hello World!!"; may reuse an instance from the string constant pool if one is available (String Pool is a pool of Strings stored in Java heap memory ).

In this example both string literals refer the same object:

In the following code, 2 different objects are created and they have different references:

In terms of good coding practice: do not use == to check for String equality, use .equals() instead.

In general, you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code.

Java String Class

Java String Class represents character strings. The java.lang.String class provides a lot of methods to work on string. Java String is not a primitive data type like int and long. It is basically an object that represents sequence of char values . It is like an array of characters works same as java string.

More about... String Class
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About