Como comparar no if strings

public class CompareStrings { public static void main(String[] args) { String style = "Bold"; String style2 = "Bold"; if(style == style2) System.out.println("Equal"); else System.out.println("Not Equal"); } }

Output

Equal

In the above program, we've two strings style and style2. We simply use the equal to operator (==) to compare the two strings, which compares the value Bold to Bold and prints Equal.

Example 2: Compare two strings using equals()

public class CompareStrings { public static void main(String[] args) { String style = new String("Bold"); String style2 = new String("Bold"); if(style.equals(style2)) System.out.println("Equal"); else System.out.println("Not Equal"); } }

Output

Equal

In the above program, we have two strings named style and style2 both containing the same world Bold.

However, we've used String constructor to create the strings. To compare these strings in Java, we need to use the equals() method of the string.

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not.

On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

If you instead change the program to use equality operator, you'll get Not Equal as shown in the program below.

Example 3: Compare two string objects using == (Doesn't work)

public class CompareStrings { public static void main(String[] args) { String style = new String("Bold"); String style2 = new String("Bold"); if(style == style2) System.out.println("Equal"); else System.out.println("Not Equal"); } }

Output

Not Equal

Example 4: Different ways to compare two strings

Here is the string comparison which is possible in Java.

public class CompareStrings { public static void main(String[] args) { String style = new String("Bold"); String style2 = new String("Bold"); boolean result = style.equals("Bold"); // true System.out.println(result); result = style2 == "Bold"; // false System.out.println(result); result = style == style2; // false System.out.println(result); result = "Bold" == "Bold"; // true System.out.println(result); } }

Output

true false false true

In Go language, the string is an immutable chain of arbitrary bytes encoded with UTF-8 encoding. You are allowed to compare strings with each other using two different ways:

1. Using comparison operators: Go strings support comparison operators, i.e, ==, !=, >=, <=, <, >. Here, the == and != operator are used to check if the given strings are equal or not, and >=, <=, <, > operators are used to find the lexical order. The results of these operators are of Boolean type, meaning if the condition is satisfied it will return true, otherwise, return false.

Example 1: 

    fmt.Println("Result 1: ", result1)

    fmt.Println("Result 2: ", result2)

    fmt.Println("Result 3: ", result3)

    fmt.Println("Result 4: ", result4)

    fmt.Println("\nResult 5: ", result5)

    fmt.Println("Result 6: ", result6)

    fmt.Println("Result 7: ", result7)

    fmt.Println("Result 8: ", result8)

Output: 



Result 1: false Result 2: false Result 3: false Result 4: true Result 5: true Result 6: true Result 7: true Result 8: false

Example 2: 

    myslice := []string{"Geeks", "Geeks",

    fmt.Println("Slice: ", myslice)

    result1 := "GFG" > "Geeks"

    fmt.Println("Result 1: ", result1)

    result2 := "GFG" < "Geeks"

    fmt.Println("Result 2: ", result2)

    result3 := "Geeks" >= "for"

    fmt.Println("Result 3: ", result3)

    result4 := "Geeks" <= "for"

    fmt.Println("Result 4: ", result4)

    result5 := "Geeks" == "Geeks"

    fmt.Println("Result 5: ", result5)

    result6 := "Geeks" != "for"

    fmt.Println("Result 6: ", result6)

Output: 

Slice: [Geeks Geeks gfg GFG for] Result 1: false Result 2: true Result 3: false Result 4: true Result 5: true Result 6: true

2. Using Compare() method: You can also compare two strings using the built-in function Compare() provided by the strings package. This function returns an integer value after comparing two strings lexicographically. The return values are: 

  • Return 0, if str1 == str2.
  • Return 1, if str1 > str2.
  • Return -1, if str1 < str2.

Syntax: 

func Compare(str1, str2 string) int

Example:

    fmt.Println(strings.Compare("gfg", "Geeks"))

    fmt.Println(strings.Compare("GeeksforGeeks",

    fmt.Println(strings.Compare("Geeks", " GFG"))

    fmt.Println(strings.Compare("GeeKS", "GeeKs"))

Output: 

1 0 1 -1

Article Tags :

String is a sequence of characters. In Java, objects of String are immutable which means they are constant and cannot be changed once created.

Below are 5 ways to compare two Strings in Java:

  1. Using user-defined function : Define a function to compare values with following conditions :
    1. if (string1 > string2) it returns a positive value.
    2. if both the strings are equal lexicographically
      i.e.(string1 == string2) it returns 0.
    3. if (string1 < string2) it returns a negative value.

    The value is calculated as (int)str1.charAt(i) – (int)str2.charAt(i)

    Examples:

    Input 1: GeeksforGeeks Input 2: Practice Output: -9 Input 1: Geeks Input 2: Geeks Output: 0 Input 1: GeeksforGeeks Input 2: Geeks Output: 8

    Program:



    public class GFG {

        public static int stringCompare(String str1, String str2)

        {

            int l1 = str1.length();

            int l2 = str2.length();

            int lmin = Math.min(l1, l2);

            for (int i = 0; i < lmin; i++) {

                int str1_ch = (int)str1.charAt(i);

                int str2_ch = (int)str2.charAt(i);

                if (str1_ch != str2_ch) {

                    return str1_ch - str2_ch;

                }

            }

            if (l1 != l2) {

                return l1 - l2;

            }

            else {

                return 0;

            }

        }

        public static void main(String args[])

        {

            String string1 = new String("Geeksforgeeks");

            String string2 = new String("Practice");

            String string3 = new String("Geeks");

            String string4 = new String("Geeks");

            System.out.println("Comparing " + string1 + " and " + string2

                               + " : " + stringCompare(string1, string2));

            System.out.println("Comparing " + string3 + " and " + string4

                               + " : " + stringCompare(string3, string4));

            System.out.println("Comparing " + string1 + " and " + string4

                               + " : " + stringCompare(string1, string4));

        }

    }

    Output: Comparing Geeksforgeeks and Practice : -9 Comparing Geeks and Geeks : 0 Comparing Geeksforgeeks and Geeks : 8

  2. Using String.equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.

    Syntax:

    str1.equals(str2);

    Here str1 and str2 both are the strings which are to be compared.

    Examples:

    Input 1: GeeksforGeeks Input 2: Practice Output: false Input 1: Geeks Input 2: Geeks Output: true Input 1: geeks Input 2: Geeks Output: false

    Program:

    public class GFG {

        public static void main(String args[])

        {

            String string1 = new String("Geeksforgeeks");

            String string2 = new String("Practice");

            String string3 = new String("Geeks");

            String string4 = new String("Geeks");

            String string5 = new String("geeks");

            System.out.println("Comparing " + string1 + " and " + string2

                               + " : " + string1.equals(string2));

            System.out.println("Comparing " + string3 + " and " + string4

                               + " : " + string3.equals(string4));

            System.out.println("Comparing " + string4 + " and " + string5

                               + " : " + string4.equals(string5));

            System.out.println("Comparing " + string1 + " and " + string4

                               + " : " + string1.equals(string4));

        }

    }

    Output: Comparing Geeksforgeeks and Practice : false Comparing Geeks and Geeks : true Comparing Geeks and geeks : false Comparing Geeksforgeeks and Geeks : false

  3. Using String.equalsIgnoreCase() : The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false.

    Syntax:

    str2.equalsIgnoreCase(str1);

    Here str1 and str2 both are the strings which are to be compared.

    Examples:

    Input 1: GeeksforGeeks Input 2: Practice Output: false Input 1: Geeks Input 2: Geeks Output: true Input 1: geeks Input 2: Geeks Output: true

    Program:

    public class GFG {

        public static void main(String args[])

        {

            String string1 = new String("Geeksforgeeks");

            String string2 = new String("Practice");

            String string3 = new String("Geeks");

            String string4 = new String("Geeks");

            String string5 = new String("geeks");

            System.out.println("Comparing " + string1 + " and " + string2

                               + " : " + string1.equalsIgnoreCase(string2));

            System.out.println("Comparing " + string3 + " and " + string4

                               + " : " + string3.equalsIgnoreCase(string4));

            System.out.println("Comparing " + string4 + " and " + string5

                               + " : " + string4.equalsIgnoreCase(string5));

            System.out.println("Comparing " + string1 + " and " + string4

                               + " : " + string1.equalsIgnoreCase(string4));

        }

    }

    Output: Comparing Geeksforgeeks and Practice : false Comparing Geeks and Geeks : true Comparing Geeks and geeks : true Comparing Geeksforgeeks and Geeks : false

  4. Using Objects.equals() : Object.equals(Object a, Object b) method returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.

    Syntax:

    public static boolean equals(Object a, Object b)

    Here a and b both are the string objects which are to be compared.

    Examples:

    Input 1: GeeksforGeeks Input 2: Practice Output: false Input 1: Geeks Input 2: Geeks Output: true Input 1: null Input 2: null Output: true

    Program:

    import java.util.*;

    public class GFG {

        public static void main(String args[])

        {

            String string1 = new String("Geeksforgeeks");

            String string2 = new String("Geeks");

            String string3 = new String("Geeks");

            String string4 = null;

            String string5 = null;

            System.out.println("Comparing " + string1 + " and " + string2

                               + " : " + Objects.equals(string1, string2));

            System.out.println("Comparing " + string2 + " and " + string3

                               + " : " + Objects.equals(string2, string3));

            System.out.println("Comparing " + string1 + " and " + string4

                               + " : " + Objects.equals(string1, string4));

            System.out.println("Comparing " + string4 + " and " + string5

                               + " : " + Objects.equals(string4, string5));

        }

    }

    Output: Comparing Geeksforgeeks and Geeks : false Comparing Geeks and Geeks : true Comparing Geeksforgeeks and null : false Comparing null and null : true

  5. Using String.compareTo() :

    Syntax:

    int str1.compareTo(String str2)

    Working:
    It compares and returns the following values as follows:

    1. if (string1 > string2) it returns a positive value.
    2. if both the strings are equal lexicographically
      i.e.(string1 == string2) it returns 0.
    3. if (string1 < string2) it returns a negative value.

    Examples:

    Input 1: GeeksforGeeks Input 2: Practice Output: -9 Input 1: Geeks Input 2: Geeks Output: 0 Input 1: GeeksforGeeks Input 2: Geeks Output: 8

    Program:

    import java.util.*;

    public class GFG {

        public static void main(String args[])

        {

            String string1 = new String("Geeksforgeeks");

            String string2 = new String("Practice");

            String string3 = new String("Geeks");

            String string4 = new String("Geeks");

            System.out.println("Comparing " + string1 + " and " + string2

                               + " : " + string1.compareTo(string2));

            System.out.println("Comparing " + string3 + " and " + string4

                               + " : " + string3.compareTo(string4));

            System.out.println("Comparing " + string1 + " and " + string4

                               + " : " + string1.compareTo(string4));

        }

    }

    Output: Comparing Geeksforgeeks and Practice : -9 Comparing Geeks and Geeks : 0 Comparing Geeksforgeeks and Geeks : 8

Why not to use == for comparison of Strings?

In general both equals() and “==” operator in Java are used to compare objects to check equality but here are some of the differences between the two:

  • Main difference between .equals() method and == operator is that one is method and other is operator.
  • One can use == operators for reference comparison (address comparison) and .equals() method for content comparison.
  • In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.

    Example:

    public class Test {

        public static void main(String[] args)

        {

            String s1 = new String("HELLO");

            String s2 = new String("HELLO");

            System.out.println(s1 == s2);

            System.out.println(s1.equals(s2));

        }

    }

    Explanation: Here two String objects are being created namely s1 and s2.

    • Both s1 and s2 refers to different objects.
    • When one uses == operator for s1 and s2 comparison then the result is false as both have different addresses in memory.
    • Using equals, the result is true because its only comparing the values given in s1 and s2.

Article Tags :

Practice Tags :