11

What is the difference between these two methods?

public boolean nameControl(String str) 
{
    if (str.trim().isEmpty()) return false;
    if (str.trim().length() == 0) return false;
    return true;
}

I need find out that str should have at least one character.

Sajad
  • 2,273
  • 11
  • 49
  • 92

6 Answers6

19

There is no real difference between them.

Javadocs for isEmpty()

Returns true if, and only if, length() is 0.

rgettman
  • 176,041
  • 30
  • 275
  • 357
4

From the Javadoc:

isEmpty

public boolean isEmpty()

Returns true if, and only if, length() is 0.

Community
  • 1
  • 1
djechlin
  • 59,258
  • 35
  • 162
  • 290
4

For Java 6+

isEmpty() works since Java 6 and length == 0 works since Java 1.2+ or possibly an older version.

If you notice, the implementation of the method

Apache Commons Lang (for Java 5+)

public static boolean isEmpty(String str) 

of the class org.apache.commons.lang.StringUtils from Apache Commons Lang use str.length() == 0 in order to support Java 5.0+.

Community
  • 1
  • 1
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
1

Luckily for you this is already documented:

IsEmpty(): http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#isEmpty()

Length(): http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#length()

Davie Brown
  • 717
  • 4
  • 23
0

If you need to detect if a string has at least one (non-whitespace) character, I would try:

public boolean nameControl(String str) {
    if (str == null) return false;
    else if (str.trim().length() == 0) return false;
    return true;
}

If a string containing only whitespace should return true I would remove the trim as follows:

public boolean nameControl(String str) {
    if (str == null) return false;
    else if (str.length() == 0) return false;
    return true;
}
Christopher
  • 58
  • 1
  • 6
  • By definition, isn't any form of whitespace a character? – Obicere Oct 01 '13 at 21:43
  • Based on the original posters use of trim, I had made the assumption that a string containing only whitespace should return false. I have updated the answer to reflect both scenarios. – Christopher Oct 01 '13 at 21:59
0

Wanted to update on this:

I Observed if the string is having newline char(\n or \r), that time length fun gives you not zero value but isEmpty fun standout with value as true which is expected.

Indrajeet Gour
  • 4,020
  • 5
  • 43
  • 70