3

Firstly: what is the difference between s.equals("") and "".equals(s)?

Secondly: what would happen if I was to perform one of these functions? "".substring(1) or "".charAt(0)

Idos
  • 15,053
  • 14
  • 60
  • 75
user2131803
  • 95
  • 1
  • 2
  • 10
  • 4
    For your second questions, what's stopping you from running some code and seeing? You can even run Java online at several websites in the browser. – CollinD Feb 12 '16 at 22:36
  • 1
    Please ask [one question per post](http://meta.stackexchange.com/questions/222735/can-i-ask-only-one-question-per-post). – Pshemo Feb 12 '16 at 22:39
  • 2
    Highly related: http://stackoverflow.com/q/9888508/1743880 – Tunaki Feb 12 '16 at 22:40
  • If you can't run the second example, you can read the documentation which will tell you what happens. – Peter Lawrey Feb 12 '16 at 22:49

3 Answers3

7

Regarding the equals, there is no difference between the two equals variants when it comes to the result. However, the second one is nullsafe. If s would be null, the first one would throw a NullPointerException, the second variant would just evaluate to false.

dunni
  • 43,386
  • 10
  • 104
  • 99
6

First question: If s is not null, then there is no difference. If s is null, then s.equals("") will throw a NullPointerException while "".equals(s) will merely return false.

Second: Both of those will throw an IndexOutOfBoundsException.

Douglas
  • 5,017
  • 1
  • 14
  • 28
0

First:

The method of the instance of the class is called for both. So there is no difference in its internals.

It worth noting, however, that "".equals(s) is not likely to throw an NullPointerException. It is implemented as follows for the String class:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                    return false;
            }
            return true;
        }
    }
    return false;
}

Second:

"".substring(1);

This call would throw an IndexOutOfBoundsException. From the Java's Documentation the exception occurs: if beginIndex is negative or larger than the length of this String object.

"".charAt(0):

Also, it would throw the exception, and as stated in the previous example: IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

thyago stall
  • 1,654
  • 3
  • 16
  • 30