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 Initializing method local String object. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Initializing method local String object." Watch "Initializing method local String object." New topic
Author

Initializing method local String object.

rama murthy
Ranch Hand

Joined: Jan 13, 2006
Posts: 82
class Test {

public static void main(String[] args){

new Test().stringTest();

}

public void stringTest() {

String secondName = null; // Version 1
String secondName = ""; // Version 2
String firstName = "Java";


secondName = firstName + " Ranch";

System.out.println(secondName);

}

}

What is the difference between version 1 and version 2 in initializing the String.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Remember, variables are REFERENCES to objects. Variables are not objects themselves.

Setting secondName to null means that it is a reference to no object. No methods may be executed using that reference (you'll get NullPointerException if you try).

Setting secondName to "" means that it is a reference to a zero-length String object. Any method of the String class may be executed using that reference. Java will ensure that only one such object gets created, no matter how many times you use "" in your program (literal Strings are 'interned').


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
rama murthy
Ranch Hand

Joined: Jan 13, 2006
Posts: 82
Thanks.
 
 
subject: Initializing method local String object.