Can you have a negative string length? If so, is it the same as null?
-
No. What makes you think it could? – moinudin Feb 19 '11 at 15:22
-
8We don't want to break up the space-time continuum now do we? – Johan Sjöberg Feb 19 '11 at 15:24
-
2Try thinking in terms of real-life strings. Do you think those things can have negative length? :) – BoltClock Feb 19 '11 at 15:33
-
you are asking this question to implement a string variable without any empty string or null ,so that it doest not occupy space initially .Later you may initialse. – Dead Programmer Feb 19 '11 at 15:40
6 Answers
No; the length of a string is 0 (empty string, represented as ""
) or higher. And an empty string is not the same as null either (in Java it is not called a null string).
To better understand what null means in Java, you could check out these questions:
No, never.
length is unsigned number, it can't be negative.
the first question's answer negates the second question's legitimacy.

- 5,880
- 2
- 36
- 58
No. String length is any positive integer, or zero. Null is not equal to zero, nor is null equal to any negative value.

- 1,172
- 5
- 14
String.length()
returns the legth of the string as a primitive int
, so the return value can't be null.
The javadoc doesn't state that the return value can be less than zero, but that the method returns the number of characters in the string.

- 3,346
- 1
- 21
- 21
You cannot construct a valid String with a negative length.
However to answer you question in more depth, the length() method is
public int length() {
return count;
}
and you can use reflection to change the count
to -1 or any negative int
value. This is highly unlikely to be useful but could create some very confusing bugs in your system.

- 525,659
- 79
- 751
- 1,130
i don't think so except if you deliberately chose to use an offset (like -1) Otherwise No, any empty string is of length 0

- 2,505
- 1
- 26
- 28