Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding nulls to stringbuffers

 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to the API:

The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are appended.


I tried to test this out as shown below:



But it is producing NullpointExceptions



 
Sebanti Sanyal
Ranch Hand
Posts: 58
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reference 'sb' is itself null here and therefore, invoking methods using sb causes NullpointerException. You may verify whatever the API says as follows:
 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sebanti Sanyal wrote:The reference 'sb' is itself null here


Doesnt StringBuffer sb = new StringBuffer(null); make it not null?
 
Sebanti Sanyal
Ranch Hand
Posts: 58
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doesnt StringBuffer sb = new StringBuffer(null); make it not null?

No it doesn't. Instead, 'new StringBuffer()' creates a new StringBuffer object with no content.
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot pass null to the StringBuffer constructor. Try this instead.
 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James Boswell wrote:You cannot pass null to the StringBuffer constructor. Try this instead.


I did try this before but it gives an error because multiple append() methods can allow nulls

 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah good point.

I think Sebanti has this right:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic