Java - Write code to create a method to compare two string values and handle null

Requirements

Write code to create a method to compare two string values and handle null

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str1 = "book2s.com";
        String str2 = "book2s.com";
        System.out.println(compare(str1, str2));
    }//  w  w w .  j  a va  2s  .co  m

    public static boolean compare(String str1, String str2) {
        if (str1 == null) {
            if (str2 != null) {
                return false;
            }
        } else {
            return str1.equals(str2);
        }

        return true;
    }

    public static boolean equals(String str1, String str2) {
        if (str1 == null) {
            if (str2 != null) {
                return false;
            }
        } else if (!str1.equals(str2)) {
            return false;
        }

        return true;
    }
}

Related Exercise