In this java example we will learn that given two strings, find out if they are equal or not without using any built-in function (without using equals() function in java).
Example Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public class JavaExample { public static boolean customCompare(String x, String y){ if(x==null || y==null){ return false; } //compare lengths if(x.length()!=y.length()) return false; //compare all characters for (int i = 0; i <x.length() ; i++) { if(x.charAt(i)!=y.charAt(i)) return false; } //if here, means both strings are equal return true; } public static void main(String[] args) { String str1 = "code4example"; String str2= "code4example"; System.out.println( customCompare(str1,str2) ); //return true, str1 and str2 are equal str1 = "Code4Example"; str2 = "code4example "; System.out.println( customCompare(str1,str2) ); //return false, str1 and str2 are not equal str1 = "code4example"; str2 = " "; System.out.println( customCompare(str1,str2) ); //return false, str1 and str2 are not equal } } |
Output:
1 2 3 4 5 | true false false |
Approach:
- If any of the string is null, return false.
- If lengths of both strings are not matching, return false.
- Check if all the characters of both strings are matching, if not return false.
- If all the steps above got executed without returning false then return true.