File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String question" Watch "String question" New topic

String question

ramaseshan T
Ranch Hand

Joined: Feb 17, 2005
Posts: 30

Output: String val: nullabc
Clarify: Why is it not throwing nullPointerException?

Ramaseshan T<br />SCJP 1.4
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
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 ]

Mike Gershman
SCJP 1.4, SCWCD in process
Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
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.

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,

ramaseshan T
Ranch Hand

Joined: Feb 17, 2005
Posts: 30
Thanks Mike & Animesh. Animesh, Your illustrative examples helped me understand the concept.Thnks..
I agree. Here's the link:
subject: String question
It's not a secret anymore!