What are different ways to create String Object?
Strings can be created in many ways.
- Direct method
- Using String class constructors
- Using toString() method defined in java.lang.Object
Direct Method
String s = new String("hello");
|
The above statement creates a new String object with the value “hello” and makes str refer to it.
--------------
We can create String object using
new
operator like any
normal java class or we can use double quotes to create a String object.
There are several constructors available in String class to get String
from char array, byte array, StringBuffer and StringBuilder.String str = new String( "abc" ); String str1 = "abc" ; |
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use
intern()
method to store the String object into String pool or return the
reference if there is already a String with equal value present in the
pool.
Comments
Post a Comment