-4

Yesterday I was working on an android project & found that null value too is concatenated to a String also it effects the String length , while empty string doesn't have any effect. Why is it so ?

UPDATED QUESTION : Why is it so ? null is supposed to hold nothing !

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


class Sample
{
    public static void main (String[] args) 
    {
    String nullVar  = null;
    String emptyVar = "";


    String newNullVar = nullVar + "Some,String";
    String newEmptyVar = emptyVar + "Some,String";



    System.out.println(newNullVar + " & length is " +newNullVar.length());
    System.out.println(newEmptyVar +  " & length is " +newEmptyVar.length());


    }
}

OUTPUT :

nullSome,String & length is 15
Some,String & length is 11

Output Online

Sachin Gadagi
  • 749
  • 5
  • 14
  • 3
    What do you mean *"Why"* ? Do you want to know why Java (most languages in fact) is designed like this ? – Denys Séguret Apr 15 '14 at 12:50
  • This is part of the Java fundamentals. – mat_boy Apr 15 '14 at 12:50
  • possible duplicate of [Java Strings subtle differences](http://stackoverflow.com/questions/22969348/java-strings-subtle-differences) – Not a bug Apr 15 '14 at 12:51
  • 1
    Having `""` and `null` behave the same would *not* be useful. – Denys Séguret Apr 15 '14 at 12:51
  • It is so strange , possible duplicate got 20 upvotes and mine question is getting down votes . – Sachin Gadagi Apr 15 '14 at 12:54
  • @SachinGadagi It is not a duplicate at all! Your question is like: "why if i try to multiply two double and then to assign the result to an int the code is not compiled?" Or "why when i get the length of a String i use length() and for an array I use length?". These are very basic questions, it seems that you don't have the basis for programming in Java. – mat_boy Apr 15 '14 at 12:57

2 Answers2

5

The null reference is rendered as "null" because the JLS says so:

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

On the other hand, the empty string is a sequence consisting of zero characters, and this is how it is rendered.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

because that way if you try to print a null abject, you will get a "null" that is a little more helpfull than a void. for example

Integer i;
try{
    i = Integer.parseInt(str);
}catch(NumberFormatException e){
    //we don't care
}
System.out.println(i);
njzk2
  • 38,969
  • 7
  • 69
  • 107
Lesto
  • 2,260
  • 2
  • 19
  • 26