• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Initializing method local String object.

 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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').
 
rama murthy
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks.
 
reply
    Bookmark Topic Watch Topic
  • New Topic