2

Was doing some Java code,What I tried was:

 public class Tester {
 public static void main(String args[]){
       String str = "";
       System.out.println(str.length());
   }
 }   

and the length was as expected zero. and then I tried something like following

public class Tester {
public static void main(String args[]){
   String str = ""+""+""+""+"";
   System.out.println(str.length());
 }   
}

and the String length was again zero. So whats that "" thing is. What this append operation ""+""+""+""+"" is doing here. I hope it is doing something but the length was again Zero. I am not understanding these double quotes without any spaces.

There is something there,that is why it is not null,but whatever it is,it is of zero length,....not able to swallow this thing

EDIT: Why using empty Strings?Why not relying on null ?Just looking for clarifications....Although I am afraid of null ghost too :(

nobalG
  • 4,544
  • 3
  • 34
  • 72
  • 4
    simple math : 0 + 0 = 0 – Lrrr May 26 '15 at 12:24
  • But there is something,thats why it is not null,but whatever it is,it is of zero length,hOW COME – nobalG May 26 '15 at 12:25
  • I'm not sure why this seems strange to you. A string literal in Java is basically equivalent to whatever there is between the quotes, not including them. Since that is nothing, then it's empty, and its length is zero. What's the problem with that? – RealSkeptic May 26 '15 at 12:25
  • http://stackoverflow.com/questions/4802015/difference-between-null-and-java-string – sp00m May 26 '15 at 12:26
  • I think you are confusing the value and the internal representation of the object. True, there's an object, `String`, that exists but it's value is nothing. So if I take the sum of, or concatenate, multiple instance of nothing, I'll get a new object that has the value of nothing. That value is a zero-length `String` instance. – MadConan May 26 '15 at 12:31
  • @MadConan This can be an acceptable answer – nobalG May 26 '15 at 12:38

4 Answers4

3

Double quotes mean an empty string - A string with with nothing in it.

As Lrrr commented, nothing + nothing + nothing is still nothing.

Phil Anderson
  • 3,146
  • 13
  • 24
1

Double quote without any character means empty String in Java. If you concat multiple empty String values result will again be an empty String. That is why you are getting str.length() as zero everytime.

justAbit
  • 4,226
  • 2
  • 19
  • 34
1

If you do + "" with anything, to performs the toString(), "" is empty string, no matter how many empty strings you concatenate , it ll always be an empty string.

Soumitri Pattnaik
  • 3,246
  • 4
  • 24
  • 42
1

String literal assignment in java takes "" as empty string. Which means, there is an object without any content in it.

Method length() actually returns the size of the underlying array of String, which in this case is 0.

So if you add a lot of empty strings, the answer you will get is just 0

aksappy
  • 3,400
  • 3
  • 23
  • 49