Check if strings are equal java

How Do I Compare Strings In Java

This article is originally published at https://coderolls.com/compare-strings-in-java/ In this article you are going to learn how to compare strings. What problem occurs when you compare string using equals to ( = )operator.

Introduction

  1. Using equals() method ( comparing the content)
  2. Using == operator (comparing the object reference)
  3. Using compareTo() method (comparing strings lexicographically)

1. Compare strings using equals() method

In this way, I am using .equals() instance method of the String class. Originally .equals() method is the Object class method, String class overrides it.

**equals()** method the compare two strings for value equality, weather they are logically equal.

equals() method in String class takes another string a parameter and compare it with the specified string, it returns true if and only if the parameter string is not null and contains the same characters as the specified string.

public boolean equals(Object anObject) It compare this string with the argument strings and return true if the argument is not null and contains the same character as the specified string. param - another string returns - true - if argument is not null and it contains same characters as the specified string false - if the argument is null or it does not contain same characters as the specified string ex. firstString.equals(secondString) // returns true if and only if the secondString is not null and contains the same characters as firstString. 

I have given the program to compare string using equals() method below

/** * A Java program to compare two strings using equsls() * and equalsIgnoreCase() method of the String. * * @author Gaurav Kukade at coderolls.com */ public class CompareUsingEquals < public static void main(String[] args) < String firstString = "coderolls"; String secondString = "javablog"; String thirdString = "coderolls"; String fourthString = "CodeRolls"; System.out.println("Comparing strings using equals() and equalsIgnoreCase() method\n"); // Using equals() method System.out.print("firstString.equals(secondString) : "); System.out.println(firstString.equals(secondString)); System.out.print("firstString.equals(thirdString) : "); System.out.println(firstString.equals(thirdString)); /* * Using equalsIgnoreCase() method to ignore * case consideration (i.e. Capital or small) of both the strings. */ System.out.print("firstString.equalsIgnoreCase(fourthString) : "); System.out.println(firstString.equalsIgnoreCase(fourthString)); >> 
Comparing strings using equals() and equalsIgnoreCase() method firstString.equals(secondString) : false firstString.equals(thirdString) : true firstString.equalsIgnoreCase(fourthString) : true 

2. Compare strings using == operator

In String, **==** operator is used to comparing the reference of the given strings, whether they are referring to the same objects.

Читайте также:  Smarty class php error

When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object, else it will return false .

I have given a Java program to compare using == operator below

/** * A Java program to compare strings using == operator. * * == operator ckecks weather both the strings referring * to the same String Object. * * @author Gaurav Kukade at coderolls.com */ public class CompareUsingEqualsToOperator < public static void main(String[] args) < String firstString = "coderolls"; String secondString = "javablog"; String thirdString = "coderolls"; // creating new String object with the same value as firstString or thirdString String fourthString = new String("coderolls"); System.out.println("Comparing strings using == operator \n"); System.out.print("firstString == secondString : "); System.out.println(firstString == secondString); /* * Here firstString and thirdString is referring to the same String object * hence it will print 'true'. */ System.out.print("firstString == thirdString : "); System.out.println(firstString == thirdString); /* * Here firstString and fourthString have same value * but they are referring to the different String object. * * hence it will print 'false' */ System.out.print("firstString == fourthString : "); System.out.println(firstString == fourthString); >> 
Comparing strings using == operator firstString == secondString : false firstString == thirdString : true firstString == fourthString : false 

Problem with using == operator for string comparison

Most of the beginner Java developers commit this mistake by comparing two strings using the == operator.

Logically, they have to check whether both the string contains the same character sequence or not.

In Java String, the == operator used to check the reference of both the string objects and equals() method used to check the value equality of both strings.

== – checks reference equality

equals() – checks the value equality

When we assign a string value to the string variable JVM will check if the string with the equal value already present in the string pool or not. If it is not present in the string pool, it will be added to the constant pool and the reference to that string object is returned.

If it is present in the string pool, the reference to the memory address of that string object is returned.

The following image shows the pictorial explanation of the same.

‘firstString’ pointing towards the “coderolls” string in string pool

If we are assigning the equal value to another string variable, JVM checks if the string with that value is present in the string constant pool or not.

Since the string object with that value is already created in the previous step. Another string variable starts referring to the previously created string object instance.

The following image shows the pictorial explanation for the same

‘firstString’ and ‘secondString’ pointing towards the “coderolls” string in string pool

When we create string using the new operator, a new string object is created and stored in the Java heap space.

‘firstString’ and ‘secondString’ pointing towards the “coderolls” string in string pool and ‘thirdString’ pointing towards the “coderolls” in java heap space.t

3. Compare strings using compareTo() method

compareTo() method is used to compare two strings lexicographically. i.e. Alphabetically.

compareTo() method compares the character sequence of the argument string with the character sequence of the specified string.

Showing argument string and specified string

Showing argument string and a specified string.

It returns a negative integer if the argument string is lexicographically greater than the specified string. i.e if the argument string follows the specified string. ( argument String > specified String )

It returns positive integer if the argument string is lexicographically smaller than the specified string. i.e. If the argument string precedes the specified string. ( argument String < specified String )

It returns zero if both the strings are lexicographical equals. ( argument String = specified String )

If you want to ignore the cases of both the string use compareToIgnoreCase() method.

I have given a program for comparing strings using the compareTo() method. It also consists a case for ignoring the cases with compareToIgnoreCase() method.

 * A Java program to compare strings using compareTo() * and compareToIgnoreCase() method. * * compareTo() compare strings lexicograpgically. * * @author Gaurav Kukade at coderolls.com */ public class CompareUsingCompareTo < public static void main(String[] args) < String firstString = "java"; String secondString = "coderolls"; String thirdString = "sql"; String fourthString = "CodeRolls"; System.out.println("Comparing strings using compareTo() and compareToIgnoreCase() method\n"); // Using compareTo() method System.out.print("firstString.compareTo(secondString) : "); System.out.println(firstString.compareTo(secondString)); System.out.print("firstString.compareTo(thirdString) : "); System.out.println(firstString.compareTo(thirdString)); /* * Using compareToIgnoreCase() method to ignore * case consideration (i.e. Capital or small) of both the strings. */ System.out.print("secondString.compareToIgnoreCase(fourthString) : "); System.out.println(secondString.compareToIgnoreCase(fourthString)); >> 
Comparing strings using compareTo() and compareToIgnoreCase() method firstString.compareTo(secondString) : 7 firstString.compareTo(thirdString) : -9 secondString.compareToIgnoreCase(fourthString) : 0 

I have written a detailed article on how to compare strings lexicographically in java. In this article, I have also created a user-defined method to compare two strings lexicographically.

Conclusion

We can compare strings using the ways given below

  1. Using equals() method : equals() method in the strings used to check the string value equality whether they contain the same character sequence.
  2. Using == operator : == operator used to check the reference equality of the two strings, whether they are pointing towards the same string object.
  3. Using compareTo() method : compareTo() method used to check the strings lexicographically. I.e alphabetically. Check the detailed articles on How to compare strings lexicographically.

Most of the beginner java developers do mistakes while comparing strings. They actually want to check the content of the string but they use == operator to check it.

It is always advised to use equals() method to compare the string on the basis of its content.

If you have any queries about the code blocks given above, please write it down in the comment section below. Also. let me know if you have any other way to compare two strings in java in the comment section.

Related Article

Источник

Check if Strings are equal in Java

Learn Algorithms and become a National Programmer

In this article, we have explored how to find if two strings are equal in Java. There are three ways to check if two strings in Java are equal:

Before going into this, we will get basic idea of strings in Java.

Like we use integer and floating point data type in programming, String is a data type used to represent the text. It is comprised of set of characters or in java it is an object which represents a sequence of characters which could have spaces as well as numbers.

String must be enclosed in quotations marks i.e in «» to make data recognized as a string.

"Open", "Genus" these are two different strings. 

As string could contain spaces, a sentence is also a string.

"OpenGenus is an open-source organization" is a string. 

As string could contain numbers.

"n comes 2 times in word OpenGenus","Open1" and "5678" are also strings. 

Strings are immutable . It means strings are constant object whose value cannot be changed or modified after once created.

Creation and storage of String

The way string is being stored depends on the way string has been created.
Whenever the memory is allocated to a java program, JVM divides the memory in to two parts-

1.stack- used for execution purpose.

2.heap- used for storage purpose.
So at the time of allocation JVM allocates some part of heap memory specially for string literals called String Constant Pool .

There are two ways to create a string-

1. By using String literal

In java string literal is created by using double quotes.

Here compiler will create the string object having string literal «Genus» and will assign it to the string instance s1.
These type of string objects are stored in String Constant Pool .
JVM first checks the content of the object to be created. If the object with same value already exist in the pool then it does not create a new object and rather, it assigns the reference of the same existing object to new instance. It means there can never be two objects in the pool having same content or value.

String s1 = "Genus"; String s2 = "Genus"; String s3 = "Genus"; 

These are three string instances that have same value «Genus», then it means that in pool space there is only one object suppose let it be s1 having the value «Genus» then all remaining string instances i.e s2 and s3 are pointing to s1.

But, what if we want to have two different string objects having same values?

So, the answer of your all doubts is below.

2. By using new Keyword

In java a new string object is created using a new keyword independent of whether the object with same value exist or not.
for example-

String s4 = new String("Genus"); String s5 = new String("Genus"); 

Here compiler would create two different string objects s4 and s5 in the memory each having the value «Genus».
These type of string objects are stored in the heap memory .

String Equality

There are three ways to check the equality of two strings in java.

It depends on which basis they are being compared i.e on the basis of value or reference.

1. By == operator

The == operator compares two string objects on the basis of their reference for equality i.e It returns true if two objects being compared have same physical address in the memory otherwise it will return false.

As we have learnt that if the strings created using string literal have same value then they have same address as well as both instance refers to same object then in that case == operator will return true and in case when new string is created using new keyword then new object would be created in nonpool then it will return false even after having the same value as it will have different address in the memory.

2. By equals() method

The equals() method compare two strings on the basis of their values or content for equality.

There are two methods provided by String class in java:

i) String.equalsIgnoreCase()

This method compare the strings ignoring the case( case-insensitive ). It returns true if values of both the strings is same ignoring the case, else return false.

ii) String.equals()

This method compare the strings considering the case( case-sensitive ), if the value or content of both strings is same considering the case then return true else return false.

3. By compareTo() method

The compareTo() method compare two strings lexicographically and returns 0 if strings are equal else positive or negative value depending upon if the first string is lexicographically larger or smaller respectively.

Suppose s1 and s2 are two strings.

if : s1 == s2 : 0 s1 > s2 : positive s1 < s2 : negative 

Each character of both the strings is converted into a Unicode value for comparison.

The value is calculated as (int)s1.charAt(i)-(int)s2.charAt(i) .
where i is an index for strings.

class CheckEquality3 < public static void main(String args[]) < String s1 = "Genus"; String s2 = "Genus"; String s3 = "Genius"; System.out.println(s1.compareTo(s2));// 0 (as s1=s2) System.out.println(s1.compareTo(s3));// 12(as s1>s3) System.out.println(s3.compareTo(s1));// -12(as s3>s1) > > 

With this article at OpenGenus, you must have the complete idea of checking if Strings are equal in Java.

Aayushi Ghadiya

OpenGenus Tech Review Team

Software Engineering

Complex Numbers in Python

In this article, we have explored how to work with Complex Numbers in Python which is supported in Python inherently as a fundamental datatype. We have covered the different operations as well.

Lyndi Castrejon

Lyndi Castrejon

Find the smallest element in an array

We are given an integer array of size N or we can say number of elements is equal to N. We have to find the smallest/ minimum element in an array. The time complexity to solve this is linear O(N) and space complexity is O(1).

Srashti Mittal

Srashti Mittal

Источник

Оцените статью