Reputation: 495
I need to know the difference of initializing the String in java when using the runtime.
For Exmaple:
String declare = null;
otherwise:
String declare = "";
I declared the two type of declaration of string. Which one is best for runtime declaration.
Upvotes: 0
Views: 250
Reputation: 2041
As @AljoshaBre commented, it depends on what you are going to do with it. Having it initialized to null is somewhat redundant, for the initial value usually is that. The blank initialization ("") makes it impossible to receive a null pointer exception if you go through an unexpected path (which may be good or bad, because it might mask logic errors in your code).
Having an initial value is usually good, but make it so that it is meaningful for the code that is going to use your String, not a random initial value.
Upvotes: 0
Reputation: 1408
First example will not create a String object, and second will. So, the statement:
declare.equals("some string");
will generate a NullPointerException for your first example, but not for the second.
Upvotes: 0
Reputation: 4693
In first case you have created a 'pointer' to a null
object (objec is not created). In second one - the 'pointer' to the object with value "" (empty string). These are qiute different things - you need to decide, which one do you need for further manipulations.
Upvotes: 0
Reputation: 15675
A String is an object. If you initialize it to null, you are telling the compiler that you are aware that wasn't initialized, and that there should be no warnings when you first try to use the variable. Aside from that, you are pointing a reference to null, of course.
If you initialize the String to an empty String, however, the following happens:
So, the question is, how do you handle nulls or empty Strings in your code? That's what should guide your decision
Upvotes: 3