Cristian Jimenez
Cristian Jimenez

Reputation: 97

Strange 'null' string as value and makes the String object not empty, why?

Try this code, and you will see the output, the code uses two String one in a class and another in a variable, the output of the both usages is very different and strange, why and how can I solve it?

---------With class...
null
null
null hello
---------With variable...
null

 hello

Setting null to the name becomes into this value for the String, why? I need the name to be null and not 'null'.

Thanks by your help.

//'main' method must be in a class 'Rextester'.
//Compiler version 1.8.0_72

import java.util.*;
import java.lang.*;

class Car {
   private String name;

   public void setName( String name ) { 
       if (this.validateName( name )) 
          this.name = name; 
   }

   public String getName() { return name; }

   public boolean validateName(String name) { 
      return name != null && name.trim() != ""; 
   }

   public boolean validate()
   { return this.validateName( this.name ); }
}

class Rextester
{  
    public static void main(String args[])
    {

        System.out.println( "---------With class..." );
        Car t = new Car();

        t.setName(null);
        System.out.println( t.getName() );

        t.setName("");
        System.out.println( t.getName() );

        t.setName(t.getName() + " hello" );
        System.out.println( t.getName() );     

        System.out.println( "---------With variable..." );

        String nullString = new String();

        nullString = null;
        System.out.println( nullString );

        nullString = "";
        System.out.println( nullString );

        nullString = nullString + " hello";
        System.out.println( nullString );
    }
}

Upvotes: 1

Views: 1512

Answers (5)

josivan
josivan

Reputation: 2063

I made a mistake in other answer.

I believe that StringUtils.defaultIfBlank from Apache Commons Lang solve your problem.

In API you can see that:

Returns either the passed in CharSequence, or if the CharSequence is whitespace, empty ("") or null, the value of defaultStr.

t.setName(StringUtil.defaultIfBlank(request.getParameter("name"), null));

Upvotes: 0

Andreas
Andreas

Reputation: 159096

You output is from this statement:

System.out.println( "'" + name + "'" )

which just prints the result of a string concatenation with a null value in it.

According to JLS 15.18.1 String Concatenation Operator +:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

JLS 5.1.11 String Conversion says:

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

If you want to print the text null without the quotes, then you have to not print quotes:

System.out.println( name != null ? "'" + name + "'" : "null" )

or if you want a null to print like an empty string (dumb, because then you cannot see the difference):

System.out.println( "'" + (name != null ? name.toString() : "") + "'" )

On a different topic, name.trim() != "" won't work.

You cannot use == and != to compare strings.

Use ! name.trim().isEmpty().


Third note: You setName() should not silently ignore bad input.

public void setName( String name ) { 
    if (this.validateName( name )) 
        this.name = name; 
}

This code should either fail on bad input:

public void setName( String name ) { 
    if (! this.validateName( name ))
        throw new IllegalArgumentException("Name cannot be null or blank");
    this.name = name; 
}

Or assign null or blank on bad input:

public void setName( String name ) { 
    if (this.validateName( name )) 
        this.name = name; 
    else
        this.name = null; // or ""
}

Upvotes: 0

JanLeeYu
JanLeeYu

Reputation: 1001

Maybe you could just try to change you setName to :

   public void setName( String name ) { 
       if (this.validateName( name )) {
          this.name = name; 
       } else {
          this.name = "";
       }
   }

as an alternative? Hope it helps.

Upvotes: 0

RZet
RZet

Reputation: 1074

It's because your 'validateName(String name)' method returns 'false' hence 'setName(String name)' method doesn't do anything and the class member 'name' remains 'null'.

This originates from the fact that 'request.get parameter("name")' call returns an empty string as per your post.

Upvotes: 0

Till
Till

Reputation: 994

You can call the isEmpty() method which will return true if name is empty.

name.isEmpty()

Upvotes: 1

Related Questions