Search code examples
javaargumentsnull-pointer

null argument java null pointer


this is my code and I don't know why "one == null" and "two == null" are always False and I can't send any Null argument to my method! please help me

public class RepeatInString {
    public int StringInString(String one, String two) {
        if (one.equals("") || two.equals("") || one == null || two == null){
            return 0;
        }
        else{
            char[] oneChar = one.toCharArray();
            char[] twoChar = two.toCharArray();
            int repeatCounter = 0;
            int matchChars = 0;
            for (int i=0 ; i < (one.length()-two.length()+1) ;i++ ){
                matchChars = 0;
                for (int j=0; j<two.length() ;j++) {
                    if (oneChar[i + j] == twoChar[j])
                        matchChars += 1;
                    else
                        break;
                }
                if (matchChars == two.length())
                    repeatCounter += 1;
            }
            return repeatCounter;
        }
    }

Solution

  • The 'dot' is the 'dereference' operator. It means: Take the thingie on the left of the dot, follow the reference, and on the object you find there, do this operation.

    Hence, if you write x.foo() and x is null, you get a NullPointerException.

    The expression a || b || c is resolved left-to-right. First a is calculated. If it's true, evaluation ends, the result is already clear. If it is false, then b is resolved, and so on and so forth.

    So, let's say one is null.

    First, one.equals("") is evaluated (note, you should use one.isEmpty(), that's more idiomatic). one is null, so, this evaluation results in a thrown NullPointerException, and execution ends then and there.

    You presumably want if (one == null || two == null || one.equals("") || two.equals("")) {.

    Except, you don't want that either.

    null isn't a standin for 'empty'. null is best taken as meaning: Unknown or no value.

    So, if I ask you: is 'this unknown value in this other unknown value', the only possible answer is: "I don't know".

    If you answer that question with either true or false, you're lying, or at least guessing. Don't do that. It is perfectly sensible in this scenario to throw a nullpointerexception if null is provided.

    Sometimes you read input from external systems and it is perfectly acceptable to explicitly choose to treat null input as empty strings or some other sentinel value. If that's the case, do that, explicitly, right there, on the system border.