Creating String object – Direct Method

20 January 2012 By Nithya Vasudevan 1,986 views 2 Comments
1 Flares Twitter 0 Facebook 0 Google+ 1 1 Flares ×
  • 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 = "";
  • The above statement creates a new String object with the value “” 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 = “”. 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.

Tags: , ,

  • Pingback: JavaPins

  • Bhushan

    Good one :) keep posted

    keep it up !!

    IBM Java Developer