This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Declare and initialize empty String

 
Cathie Lee
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

And

" " means it is just initialised to something

(Please, please be kind!)
 
Cathie Lee
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks,
 
Mark Patrick
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic