- 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();
String str = "theopentutorials.com";
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.