-2

I'm reading some data from file.

String content = null;

    File file=new File(str);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    byte byt[] = new  byte[1024];
    try {
        while(fis.read(byt)!=-1)
        {
            content += new String(byt);
        }
        fis.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

File contains some text say Hello. when I read complete file it gives me string nullHello. why it is so. and when I set content = "" it gives me right string. In first case jvm will not any memory to content object then while concatenating how it uses null as string ?

Vishvesh Phadnis
  • 2,448
  • 5
  • 19
  • 35

4 Answers4

2

See the JLS - 15.18.1 String Concatenation Operator +:

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

That's why you're getting "null" concatenated as a String, you probably want to initialize the variable to empty String, which is "".

It's highly advised to use StringBuilder instead of +, when it comes to performance, you'll feel the difference.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • but String class toString() return same String object. In declaration of string class there private final char value[]; and int hash is there.so how and why it convert to "null" string? why it allocate 4 byte to store "null" when user specified I will allocate memory later, till the time String object will not point to any memory location – Vishvesh Phadnis Nov 16 '14 at 14:54
  • I know I need to use "" but I have question why it allocate memory? – Vishvesh Phadnis Nov 16 '14 at 14:59
  • It convert to "null" because that's how the language is defined. Also declaring a variable to `null` reference doesn't mean that there's no memory allocated. – Maroun Nov 16 '14 at 15:20
0

Replace

String content = null;

with

String content = "";
Maroun
  • 94,125
  • 30
  • 188
  • 241
coder hacker
  • 4,819
  • 1
  • 25
  • 50
0

Because in Java, a null String object can be concatenated to other strings. A null String object will print "null."

An empty String object will print a 0-character string and that is why when you start with the empty string, it will print the correct string.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64
0
String content = null;

This is clearly assigned by you only. Later you are concatenating null+hello thats why it is giving nullhello as output.

So, keep String content=""; instead of String content=null

Sagar Pudi
  • 4,634
  • 3
  • 32
  • 51