• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String concat() question required

 
PETER CARTER
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given:
11. String a = null;
12. a.concat(�abc�);
13. a.concat(�def�);
14. System.out.println(a);
Why it is :
Exception in thread "main" java.lang.NullPointerException at X.main(X.java:12)
I think it should be "abcdef".

Thanks !!
 
David Ulicny
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look into the documentation how concat is defined. It returns the String. Remember that String is IMMUTABLE, so there is no way how to modified it.
Your exmaple is
null.concat();
so it will throws the exception.
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Peter,

I think you are new to java/OOP technology.
The answer is in your question only.
You are writing String a = null;
then calling a method of String object on an object that is null.
This is what a null pointer exception is.

In other words, you are trying to c0ncatenate something to an "a" string object, what the jvm will think in which object to concatenate??

I think u just give a thought and it will be clear.

Regards
Sandeep Jindal
 
PETER CARTER
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David,
Thanks !!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic