Creating String object – Direct Method

  • Strings are objects in Java.
  • Just like creating other objects, you can create an instance of a String with the new keyword, like this,
  • String s = new String();
  • But since we will use Strings all the time, the most direct way to create a String is to write:
  • String str = "theopentutorials.com";
  • The above statement creates a new String object with the value “theopentutorials.com” and makes str refer to it.

String is the special case in Java and only String object can be created this way. Any other object in Java should be created using new keyword. There is a slight difference between String s = new String() and String str = “theopentutorials.com”. This is explained in detail here.

There is a difference between null initialization and empty string.

Null initialization

 String str = null; 
  • Here no object is created, the variable will not be initialized and it has no value. This method is similar to declaring a String reference variable as instance or static variable because it gets the default value as null.
     String str; 
  • Trying to access any member using this variable results in NullPointerException.

Empty String

 String s = "";
  • Here the variable will be initialized and it value is empty. A new String object will be created in the memory and its reference is given to the variable ‘s’. Invoking s.length() returns 0.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.