Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes solve this 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 "solve this" Watch "solve this" New topic

solve this

himanshu kesarwani
Ranch Hand

Joined: Aug 27, 2008
Posts: 84
What is the output ?

class Test02{

public String fetch(){
return null;

public static void main(String args[]){
Test02 obj = new Test02();
String str = obj.fetch();

Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

Did you try to run the program??

Also please quote the source of the question...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
vamsi kris

Joined: Feb 04, 2009
Posts: 28

Hi, nice tricky question

examine the code you can clear your doubt

null< >
null<a b>


SCJP 1.5 97%
Adi Kulkarni
Ranch Hand

Joined: Mar 12, 2009
Posts: 86
Hi himanshu ,

I think the example mentioned by you will throw a NullpointerException ( Runtime) , since in the system.out.println you are trying to use a reference variable not referring to any object. ( Its having null value).


SCJP 1.5
vamsi kris

Joined: Feb 04, 2009
Posts: 28

i think it doesnt throw a null pointer exception because you are converting a null object a string object in system.out.println(); statement so it compiles and runs correctly
Muhammad Ijaz
Ranch Hand

Joined: Mar 03, 2009
Posts: 34
Actually it doesn't throw NullpointerException. Indeed the null is first concatinated with "" string. After that when null has been concatinated to "" String then it convert the null+"" into String with toString() method. So if we convert null+"" into String, no reason for NullpointerException.


IBM Certified WebSphere Commerce Application Developer

NagarajGoud uppala
Ranch Hand

Joined: Nov 13, 2008
Posts: 86
Hi vamsi,
your right. himunshu thank you for posting such a tricky question!!!

I know Life is very Tough...But I AM TOUGHER
SCJP 1.5
Chaitanya Jadhav
Ranch Hand

Joined: Mar 13, 2009
Posts: 42

yes answer is null

BUT ... fallowing code throws Runtime NullPointerException

SCJP 1.5 80%
Rocky Singh

Joined: Mar 12, 2009
Posts: 8
First of all please quote the source Himanshu !!

This program will throw a nullpointer exception !!

Have you seen executing this code ???
I agree. Here's the link:
subject: solve this
It's not a secret anymore!