-1

I'm trying to make a dutch zipcode validator. On the first step i need to check if the first char of the zipcode (which is always a number), is between 1-9. But when i just tried to make a simple if statement to check if the first char is false, it comes back as true. In this example I took a premade string "2097AR" as input for the method "checkPostcode".

public static boolean checkPostcode(String postcode){
        String postcodeEen = postcode.substring(0,1);

        boolean resultCheck = true;

        System.out.println(postcodeEen);

        if (postcodeEen == "1"){
            resultCheck = false;
        }


        return resultCheck;

    }
Pakjethee
  • 11
  • 2

1 Answers1

2

The = operator for strings in Java checks if the two objects are the same, whereas #equals(String s) checks if the contents of the string are the same.

The function always returns true because postcodeEen and "1" aren't the same object, which makes the condition postcodeEen == "1" false.

Here is the working code segment:

if(postcodeEen.equals("1"){
    return false;
}
pr0f3ss
  • 527
  • 1
  • 4
  • 17
  • Please don't answer these obvious duplicates. Flag to close them instead. We have 1000s of questions about string comparison. New ones are superfluous. Answers make it harder to delete them. – Sotirios Delimanolis Mar 30 '19 at 00:05