• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparing lengths on Strings  RSS feed

 
rahi ali
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ma making a program i want String length and compare it that it
will be null or not but it gives me error.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Since this appears to be a new question, it merits a thread of its own, so I shall create a new thread for you.
I do not fully understand the question. What are you comparing to null? Are you string to sort Strings by their length?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I understand the confusion, so I'll give it a try.

If you are thinking of a String object as something like a ruler that has length, then I can see how it could be confusing to tell the difference between a ruler that has no length, and a ruler that doesn't exist at all! Can a ruler with no length even exist?

But that's not the right way to think about a String object. Think of it as a container that can contain characters. So if we imagine a box that can contain characters like so:



It's easier to see that we can have a box that can contain any number of characters, even none. But even an empty box still exists, even though there are no characters in it.

When we have an empty String object, it's like the empty box. The box still exists, but the number of characters in it (its length) is zero.

Now, if we get rid of the box itself, then we have the concept of null which is the case where the box does not exist at all, and therefore can have no length, not even zero, because the box doesn't even exist

So, no box means null.
An empty box has a length of zero.
A box with characters in it has a non-zero, positive length.

That help?
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah!

If you use the String#length method, you see it returns an int. Now an int is a primitive and a primitive can never be null. So if you try something like
if (myString.length() == null) ...
the javac tool will not be at all happy and will fail to compile your code. If you try this
if (myString.length() == 123) ... or
if (myString.length() == 0) ...
that is perfectly all right and the compiler will be happy and the code will run nicely.
Of course, you can use this as an alternative to ...length() == 0
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!