Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String question

 
ramaseshan T
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Output: String val: nullabc
Clarify: Why is it not throwing nullPointerException?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In some cases, a null reference of type String is treated as the String literal "null".

From JLS 4.3.1:
The string concatenation operator + (�15.18.1), which, when given a String operand and a reference, will convert the reference to a String by invoking the toString method of the referenced object (using "null" if either the reference or the result of toString is a null reference), and then will produce a newly created String that is the concatenation of the two strings

From the API doc for PrintWriter.print(String):
If the argument is null then the string "null" is printed.

[ February 24, 2005: Message edited by: Mike Gershman ]
 
Animesh Shrivastava
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ramaseshan,
Good Question

This is the sequence how the code runs:
1) It does a String.valueOf(null)--> If the null is passed as an argument, literal string "null" is returned
2) Then new StringBuffer("null") is called
3) Finally on the above created StringBuffer object append("abc") method is run.
The final output is a SringBuffer object having contents as "nullabc".

4) At the end toString() is called to return a new String object.

So,
a += "abc" ==> a = (new StringBuffer((String.valueOf(null)).append("abc")).toString();

Hope u got this
But there are some slight changes the way the program runs depending on the variables,
---------------------------------
Now if u have




The way it runs is like this
a = (new StringBuffer((String.valueOf(a)).append(String.valueOf(b))).toString();

----------------------------

Now if u have something like this


The simplified statement is:
a = (new StringBuffer("abc").append(b)).toString();

-----------------------------------------------------------
In the method append() of StringBuffer u have something like this:


I hope u got the point,

Thanks
 
ramaseshan T
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mike & Animesh. Animesh, Your illustrative examples helped me understand the concept.Thnks..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic