Compares the two String for equality while ignoring the case. - Java java.lang

Java examples for java.lang:String Compare

Description

Compares the two String for equality while ignoring the case.

Demo Code

/*//w  ww.j a  v  a2s  .c  om
 * Copyright (c) 2015-2016 QuartzDesk.com.
 * Licensed under the MIT license (https://opensource.org/licenses/MIT).
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s1 = "java2s.com";
        String s2 = "java2s.com";
        System.out.println(safeEqualsIgnoreCase(s1, s2));
    }

    /**
     * Compares the two String for equality while ignoring the case. This method returns true if
     * both String are null,
     * or they are equal according to the {@link String#equalsIgnoreCase(String)} method, false otherwise.
     *
     * @param s1 the first object.
     * @param s2 the second object.
     * @return true if both Strings are equal while ignoring the case, false otherwise.
     */
    public static boolean safeEqualsIgnoreCase(String s1, String s2) {
        if (s1 == s2)
            return true;

        if (s1 != null && s2 == null)
            return false;

        if (s1 == null) // o2 != null
            return false;

        return s1.equalsIgnoreCase(s2);
    }
}

Related Tutorials