Jump to content

Java: What is the difference between comparing strings with == and "str.equals()"?

RockSolid1106
Go to solution Solved by tikker,

The equals method checks if the contents of the string are the same. == checks if they are the same object.

 

https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

So I just made this very simple code which checks if an array contains an item equal to something.

Code:

Spoiler


import java.util.*;
public class pg202Q7 {
    public static void main(String args[]){
        Scanner in=new Scanner(System.in);
        String x[]={"hello", "how", "are", "you"};
        String y=in.next();
        System.out.println(inarray(x, y));
        in.close();
        }

    public static Boolean inarray(String array[], String needle){
        int i=0;
        Boolean p=false;
        for(;i<array.length; i++){
            if (array[i].equals(needle)){
                p=true;
                return p;
            }
        }
        return p;
    }
    

}
    

 

 

It works, but if I change the <string>.equals(needle) part to:

if (array[i]==needle){

then the code would always return false, even though the item is present in the array.

 

But, if I call the method by:

inarray(x, "hello"){

then the result is perfect(true).

But it wont work if I use:

inarray(x, y)

where String y is taken as input from the user with Scanner.

 

Could someone please explain to me, why == doesn't work the same as string.equals?

On 4/5/2024 at 10:13 PM, LAwLz said:

I am getting pretty fucking sick and tired of the "watch something else" responses. It's such a cop out answer because you could say that about basically anything, and it doesn't address the actual complaints. People use it as some kind of card they pull when they can't actually respond to the criticism raised but they still feel like they need to defend some company/person. If you don't like this thread then stop reading it. See how stupid it is? It's basically like telling someone "shut the fuck up". It's not a clever responsive, it doesn't address anything said, and it is rude. 

 ^

 

bruh switch to dark mode its at the bottom of this page

VPN Server Guide

Link to comment
Share on other sites

Link to post
Share on other sites

The equals method checks if the contents of the string are the same. == checks if they are the same object.

 

https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

Crystal: CPU: i7 7700K | Motherboard: Asus ROG Strix Z270F | RAM: GSkill 16 GB@3200MHz | GPU: Nvidia GTX 1080 Ti FE | Case: Corsair Crystal 570X (black) | PSU: EVGA Supernova G2 1000W | Monitor: Asus VG248QE 24"

Laptop: Dell XPS 13 9370 | CPU: i5 10510U | RAM: 16 GB

Server: CPU: i5 4690k | RAM: 16 GB | Case: Corsair Graphite 760T White | Storage: 19 TB

Link to comment
Share on other sites

Link to post
Share on other sites

24 minutes ago, RockSolid1106 said:

snip

As @tikker said

When using == in Java or C#, the compiler is doing a check to see if something has the same memory address/is the same object  as the other item being compared/evaluated in the check.

 

Using the equals method checks the contents of the string or variable.

Judge a product on its own merits AND the company that made it.

How to setup MSI Afterburner OSD | How to make your AMD Radeon GPU more efficient with Radeon Chill | (Probably) Why LMG Merch shipping to the EU is expensive

Oneplus 6 (Early 2023 to present) | HP Envy 15" x360 R7 5700U (Mid 2021 to present) | Steam Deck (Late 2022 to present)

 

Mid 2023 AlTech Desktop Refresh - AMD R7 5800X (Mid 2023), XFX Radeon RX 6700XT MBA (Mid 2021), MSI X370 Gaming Pro Carbon (Early 2018), 32GB DDR4-3200 (16GB x2) (Mid 2022

Noctua NH-D15 (Early 2021), Corsair MP510 1.92TB NVMe SSD (Mid 2020), beQuiet Pure Wings 2 140mm x2 & 120mm x1 (Mid 2023),

Link to comment
Share on other sites

Link to post
Share on other sites

The method equals() checks if the contents of an object (string in this case) are equal. The equality operator when used on non basic data types (==) checks if two references are the same. So when you create a string object you actually don't hold the object it self you hold a reference to it. A reference is nothing more than a number that shows where that object is located. 

 

So since you don't actually have the object you can't directly compare them with the == operator. You can only compare if references point to the same object. That's why we have the equals method so that you can compare the contents of objects.

CPU: Intel i7 - 5820k @ 4.5GHz, Cooler: Corsair H80i, Motherboard: MSI X99S Gaming 7, RAM: Corsair Vengeance LPX 32GB DDR4 2666MHz CL16,

GPU: ASUS GTX 980 Strix, Case: Corsair 900D, PSU: Corsair AX860i 860W, Keyboard: Logitech G19, Mouse: Corsair M95, Storage: Intel 730 Series 480GB SSD, WD 1.5TB Black

Display: BenQ XL2730Z 2560x1440 144Hz

Link to comment
Share on other sites

Link to post
Share on other sites

25 minutes ago, RockSolid1106 said:

But, if I call the method by:


inarray(x, "hello"){

then the result is perfect(true).

But it wont work if I use:


inarray(x, y)

where String y is taken as input from the user with Scanner.

In addition, the reason for this behaviour is probably related to the interned strings explanation in that post. It's been a long time since I've done any Java, but when directly passing "hello" as

inarray(x, "hello")

the compiler may be smart enough to optimise it to a string constant, after which it ends up as one of those "interned" strings they refer to, in which case they are the same object. This doesn't happen if you pass it as a variable through Scanner.

Crystal: CPU: i7 7700K | Motherboard: Asus ROG Strix Z270F | RAM: GSkill 16 GB@3200MHz | GPU: Nvidia GTX 1080 Ti FE | Case: Corsair Crystal 570X (black) | PSU: EVGA Supernova G2 1000W | Monitor: Asus VG248QE 24"

Laptop: Dell XPS 13 9370 | CPU: i5 10510U | RAM: 16 GB

Server: CPU: i5 4690k | RAM: 16 GB | Case: Corsair Graphite 760T White | Storage: 19 TB

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, AluminiumTech said:

As @tikker said

When using == in Java or C#, the compiler is doing a check to see if something has the same memory address/is the same object  as the other item being compared/evaluated in the check.

 

Using the equals method checks the contents of the string or variable.

Watchout, this is only true for reference type object not value type.

 

On a side note I think everyone forgot to mention that Equals also perform check for reference type if the pointer is the same. If the pointer is the same it skips else it start comparing the values.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...
On 7/16/2021 at 7:14 PM, AluminiumTech said:

As @tikker said

When using == in Java or C#, the compiler is doing a check to see if something has the same memory address/is the same object  as the other item being compared/evaluated in the check.

 

Using the equals method checks the contents of the string or variable.


Careful, in C# the == operator can be overwritten, in fact is overwritten for strings, so comparing strings in C# with == compares also contents and not just references

Software developer.
Case: be quiet! Dark Base Pro 900 Orange rev. 2 MB: GIGABYTE Z590 AORUS ULTRA (rev. 1.0) CPU: Intel® Core™ i9-11900K WC: be quiet! Pure Loop 280mm GPU: AORUS GeForce RTX 3080 Ti MASTER 12G RAM: 128GB (4x Kingston FURY 32 GB DDR4-3600) M.2: 3TB (Samsung 970 EVO Plus 1 TB & Crucial P5 2TB PCIe M.2 2280SS) PSU: be quiet! Dark Power Pro 12 1500W

Link to comment
Share on other sites

Link to post
Share on other sites

On 7/16/2021 at 6:53 PM, RockSolid1106 said:

But, if I call the method by:




inarray(x, "hello"){

then the result is perfect(true).

by the way that is only true because JavaVM only instantiates strings once for equal literals, since it looks them up in the constant pool.
 

so the "hello"s from 

String x[]={"hello", "how", "are", "you"};

and

inarray(x, "hello")

will have the same reference, just as

"hello" == "hello"

is true, but

"hello" == nonConstantHelloString

is false

EDIT:

sorry @tikker I just noticed you basically already explained that, but yea that's the standard behavior

Software developer.
Case: be quiet! Dark Base Pro 900 Orange rev. 2 MB: GIGABYTE Z590 AORUS ULTRA (rev. 1.0) CPU: Intel® Core™ i9-11900K WC: be quiet! Pure Loop 280mm GPU: AORUS GeForce RTX 3080 Ti MASTER 12G RAM: 128GB (4x Kingston FURY 32 GB DDR4-3600) M.2: 3TB (Samsung 970 EVO Plus 1 TB & Crucial P5 2TB PCIe M.2 2280SS) PSU: be quiet! Dark Power Pro 12 1500W

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×