File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes String Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Question" Watch "String Question" New topic
Author

String Question

Vijay jai Singh
Greenhorn

Joined: Jan 07, 2009
Posts: 26
Hi,

What is difference in these two statements:

String str = null;

and

String str = "";
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14266
    
  21

In the first one, you set the variable str to null (which means that it does not point to any object), and in the second one you set it to point to a String object which has no content.

Two very different things.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Prashant Hurria
Ranch Hand

Joined: Mar 23, 2009
Posts: 40
Seems you are a beginner in Java.No problems we all start somewhere.
I hope you are aware that there are two types of variables in Java


1.Primitive Variables
2.Reference Variables

For eg.
in the code line
int a ;
'a' is a primitive variable as it can refer to the primitive of the type int.

Similarly in the code line
String str;
str can contain a reference to a String object .
For your information in Java String is a class in the package java.lang.

So if you do a
String str= null what it does is
Makes a reference variable(the bit holder
for a reference value) named str of the type java.lang.String

and making it equal to null simply means the
variable is not referring to any object.

Whereas


String str=""
Simply creates an object of the type java.lang.String with no value in it and assigns the refernce variable str to this object.
Rohit Aggarawal
Ranch Hand

Joined: Jun 26, 2009
Posts: 39
str = null;
The variable does not point to any memory location.
str =""
The vairable points to some memory location having blank value


SCJP 6.0
SCBCD for JEE 5

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String Question