7

Can you have a negative string length? If so, is it the same as null?

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
robotchicken99
  • 105
  • 1
  • 3

6 Answers6

11

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:

Community
  • 1
  • 1
Jonik
  • 80,077
  • 70
  • 264
  • 372
4

No, never.

length is unsigned number, it can't be negative.

the first question's answer negates the second question's legitimacy.

Ken D
  • 5,880
  • 2
  • 36
  • 58
1

No. String length is any positive integer, or zero. Null is not equal to zero, nor is null equal to any negative value.

David Gillen
  • 1,172
  • 5
  • 14
1

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.

frm
  • 3,346
  • 1
  • 21
  • 21
1

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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

MimiEAM
  • 2,505
  • 1
  • 26
  • 28