JAVA String: Difference between Null and ""?

    public static void main(String[] args) {
    String frase;

    String palabra = "";

    String mostrar = null;

    int i;
    int c = 0;

    frase = JOptionPane.showInputDialog("Ingrese al frase: ");
    frase += " ";
    for (i = 0; i < frase.length(); i++) {
        palabra = palabra + frase.charAt(i);
        if (frase.charAt(i) == ' ') { //asi se valida una cadena vacia
            if (palabra.length() - 1 > c) {
                c = palabra.length() - 1;
                mostrar = palabra.trim();
            palabra = "";
    System.out.println("La palabra de mayor longitud es: " + mostrar);
    System.out.println("Su longitud es: " + c);


I found this code and what I wanted to know is ... why use the String show = null and not a String show="";? When changing by "" and running the program does not recognize the word of greater length, I would appreciate your response.

asked by FransMB 17.06.2017 в 10:12

5 answers


The two options mean different things, and should be used accordingly.

  • null means "there is no value"

  • "" means "there is a value". Whether this value is the empty string or not, is not relevant.

Now, it depends on your logic what is more sensible to initialize.

  • If there is a valid default value for that attribute, you simply initialize with that value. That value will depend on the logic, and can even be null .

  • If there is no valid default value, it is best to leave it in null . The reason is that if you assign a special instance (for example, "" in the case of String ), vas a estar teniendo que distinguir siempre entre si ese valor es el caso especial o no. Y si alguna vez te dejas esa comprobación, te vas a comer el error en vez de tener un NullPointerException ' 1 .

For example, these days I am modifying an OS program that has the bloody craze that, when it does not find an element in the DB, it returns an "empty" object instead of null . So I have to do something like that

 MiBean miBean = dao.getBean(clavePrimaria);
 if (miBean.getId() == 0) {
    throw new Exception("No hay bean con " + clavePrimaria);

If I forget the check, hopefully I will have an unexpected error in hacerCosasConElBean() and I will have to analyze the code until I find the error. If I do not have luck, I will do something that I do not have controlled 2 and I will not notice until much later,

If the code returned null , it would

 MiBean miBean = dao.getBean(clavePrimaria);
 if (miBean == null) {
    throw new Exception("No hay bean con " + clavePrimaria);

It is not more complicated, and in case I forgot the check would jump a NullPointerException that would indicate exactly the point and error failure.

Your example is similar. Unless "" is a valid value, for the only thing that serves to initialize "" is to hide any possible error that causes that a value is not assigned to the variable, and to confuse whoever reads your code making you believe that "" is a valid value and that nothing happens if an execution branch does not assign a value to that variable.

So "" should be used if and only if the initialization of that value is optional and "" works as the default value.

1 The rule is "fail as soon as possible". If you have a programming error, you want the program to fail when you arrive at the error, not to introduce an unexpected behavior that causes the program to fail much later, which makes it more difficult to debug.

2 Including the risk of tampering with my system data incorrectly.

answered by 17.06.2017 в 13:05

An example image

  • When declaring a variable this is null because it has no value
  • If a variable of type example is declared string=""; or int = 0; you're just initializing
  • answered by 17.06.2017 в 18:02

    They are perfectly valid initializations.

    It is more an agreement between the team that you are developing the project if it is initialized to NULL or to string.Empty.

    Here come many factors that may be inclined towards one or the other. If it is to write in database, and NULL is not allowed. If you need to consume a service where the parameters can not be passed as NULL.

    Finally, although from what I see, many people initialize in string.Empty, we must not forget that when you declare a string variable, its default value is NULL, so I can use it by default that initialization is worth me unless it is for some limitation previously described.

    But at the logic level, the only thing that changes is how it compares against another chain and established validations.

    answered by 17.06.2017 в 12:41

    That program is wrong and the best explanation of why it has been done in one way or another is: because the author has made a mistake .
    Do not use that program as an example of how to program.

    We can see that this program is incorrect if we enter an empty string in the dialog. This demo shows it: link
    The result is:


    The longest word is: null
      Its length is: 0

    Which is obviously false. The phrase is empty so it does not have the word null.

    If we start showing " " instead of null we have a much more correct result (demo: link ):


    The longest word is:
      Its length is: 0

    It is therefore clear that it is not the same to initialize the variable show a null or a " " .
    That difference will only be noticed if the string read from the dialog is empty or contains only spaces, in which case the following conditional is never executed:

            if (palabra.length() - 1 > c) {
                c = palabra.length() - 1;
                mostrar = palabra.trim();

    And when the variable variable is not executed, it remains with the value with which it was originally initialized. That's why you notice the difference between assigning null or " " . In any other case, the variable is overwritten by that conditional and you will not notice functional difference in those other cases.

    Regarding the difference between null and "" in general.

    It is easy to find wrong ideas about null like:

    • null means "no value"
    • If you initialize the variable with null value, it indicates that it does not contain any value.
    • When declaring a variable this is null because it has no value

    All previous statements are incorrect. The Java Language Specification tells us what is null :


    3.10.7. The Literal Null


    The null type has a value, the null reference, represented by the   literal null, which is formed by its ASCII characters.


    NullLiteral: null


    A null literal is always of the null type (§4.1).

    About the null type the specification says :


    4.1. The categories of Types and Values.


    (.. part omitted because it is not relevant ..)


    There is also a special type null, the type of the expression   null (§3.10.7, §15.8.1), which has no name.


    Since the null type does not have a name, it is impossible to declare a variable of   type null or do a conversion (cast) to type null ..


    The null reference is the only possible value of an expression of type   null.


    The null reference can always be assigned or converted (cast) to any type of reference (§5.2, §5.3, §5.5).


    In practice, the programmer can ignore the null type and   simply pretend that null is a special literal that can be   any reference type.

    Emphasis mine. The bold part is the answer to this question. null is a special value, is a value that can be assigned to any variable of type reference.
    Therefore all the following lines are correct:

    Integer i = null;
    String s = (String) null;
    List<String> ls = (List<String>) null;
    Object o = null;

    " " however it is a string literal and when assigning it to a variable with the operator = we are assigning a reference to an object of type String that contains the string of that literal. That reference of type String can not be assigned to any variable, it can be assigned only to declared variables of type String or a type that is superclass of String . In this case only Object is superclass of String .
    For this reason two of the following lines are incorrect:

    Integer i = ""; //Error de compilación
    String s = (String) ""; // Correcto
    List<String> ls = (List<String>) ""; //Error de compilación
    Object o = ""; // Correcto
    answered by 17.06.2017 в 21:29

    JAVA String: Difference between null and ""?

    • If you initialize the variable with null value, it indicates that it does not contain no value
    • If you initialize with "", it indicates that you are initializing with a String value.

    In the case you mention, it only implies initialization, and revising your code by initializing the variable show with a null value:

    String mostrar = null 

    or a String "",

    String mostrar=" ";

    In this case you should not make a difference in the results , since this variable is overwritten in this line:

     mostrar = palabra.trim();

    How does this demo test initializing mostrar with a value ""


    and initializing mostrar with a null value:


    Graphic explanation of the difference of 0 vs Null vs NaN

    answered by 17.06.2017 в 16:00