Results 1 to 4 of 4
  1. #1
    laosu is offline Member
    Join Date
    Jan 2011
    Posts
    4
    Rep Power
    0

    Red face Trim for null string

    Hi,

    Please help.
    Why we will getting NullPointerException when we trying to trim a NULL string,
    but won't be getting error if we trim a string with "".

    Example: string a= null; System.out.println(a.trim()); -> NullPointerException
    string b= ""; System.out.println(b.trim()); -> No error


    Thanks..

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    There's no such thing as a null string. There is only null, a variable that refers to no object, nothing. So what happens here is the same thing that happens when you try to call any method of a null. This shouldn't come as a surprise.

  3. #3
    laosu is offline Member
    Join Date
    Jan 2011
    Posts
    4
    Rep Power
    0

    Default

    Got it, thanks for your reply.

    If i have a string variable that get the NULL value from database, what is the best way to check before to trim it?

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by laosu View Post
    Got it, thanks for your reply.

    If i have a string variable that get the NULL value from database, what is the best way to check before to trim it?
    Java Code:
    if (myString != null) {
      myString = myString.trim();
    }
    
    // or
    
    myString = (myString == null) ? null : myString.trim();

Similar Threads

  1. Replies: 1
    Last Post: 02-07-2011, 10:44 AM
  2. String.trim() method help.....
    By arson09 in forum New To Java
    Replies: 6
    Last Post: 04-23-2010, 01:19 AM
  3. How to trim text in viewer
    By diva_garg in forum SWT / JFace
    Replies: 4
    Last Post: 08-26-2008, 02:03 PM
  4. String returning null value
    By impact in forum New To Java
    Replies: 7
    Last Post: 08-03-2008, 07:49 AM
  5. String trim
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-21-2008, 04:35 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •