Kallar_Mannargudi
Kallar_Mannargudi

Reputation: 495

What is the runtime difference of using the string initialization in java?

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

Answers (4)

rlinden
rlinden

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

Robert Kovačević
Robert Kovačević

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

Alex Stybaev
Alex Stybaev

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

Miquel
Miquel

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:

  • There's now a String object allocated
  • The compiler will put that String literal in the String pool
  • Any other String that you initialize to "" will point to the same inmutable String from that pool

So, the question is, how do you handle nulls or empty Strings in your code? That's what should guide your decision

Upvotes: 3

Related Questions