wood burning stoves 2.0
The moose likes Beginning Java and the fly likes Declare and initialize empty String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Declare and initialize empty String" Watch "Declare and initialize empty String" New topic

Declare and initialize empty String

Cathie Lee

Joined: Nov 20, 2004
Posts: 8
I have read someone's code. There are two String declarations and initializations for empty String. Could anyone explain the difference? Which is better way to use?

1. String = "";
2. String = null;

Thanks a lot,
Mark Patrick
Ranch Hand

Joined: Feb 22, 2004
Posts: 51
First, you need a variable name in there for it to be legal.

Question: does line 2 initialize 'b' to an empty string?

Line 1 create a String object and assigns it the reference 'a'.
Line 2 only creates a reference( 'b' ) to a String object. It will need to be assigned a String object before it can be used. If you try to use before-hand, you'll get a null pointer exception.

Which one is correct? Preference.

Mark Patrick<br />SCJP 1.4
Maureen Charlton
Ranch Hand

Joined: Oct 04, 2004
Posts: 218
Probably going to sound totally dumb here and embarras myself!!

BUT if I don't say something I won't learn...........

I thought the following:

null means it is empty i.e. nothing there


" " means it is just initialised to something

(Please, please be kind!)
Cathie Lee

Joined: Nov 20, 2004
Posts: 8
Oh, my typo, without variables...
Thanks for the explanation.

So my understand is:
Line 1: "" means a value with empty.
Line 2: null means no value.

The same as in Oracle.
Correct me if I'm wrong.

Mark Patrick
Ranch Hand

Joined: Feb 22, 2004
Posts: 51
null means "nothing".

"" is a String object with in length of 0.
null means no object

Similar to Oracle. In Oracle, you can't perform math on NULL because NULL is non-existant. In Java, instead of meaning no-value, null means no object is assigned to the variable.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Aloe1138 --

Welcome to JavaRanch!

On your way in, you might not have noticed the sign on the wall explaining our policy on display names. Let me spell it out fer ya: yer handle has to be a real-lookin' first and last name. Please head over here and fix yours up, please.

Thanking you kindly,

-- your local law enforcement officer.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link: http://aspose.com/file-tools
subject: Declare and initialize empty String
It's not a secret anymore!