BP Forums
Comparing String Variables - Printable Version

+- BP Forums (https://bpforums.info)
+-- Forum: Archived Forums (https://bpforums.info/forumdisplay.php?fid=55)
+--- Forum: Archived Forums (https://bpforums.info/forumdisplay.php?fid=56)
+---- Forum: Java (https://bpforums.info/forumdisplay.php?fid=19)
+---- Thread: Comparing String Variables (/showthread.php?tid=541)



Comparing String Variables - Vinwarez - 06-12-2012

Hello, everybody.

I don't remember when was the last time I logged in on this website.
Like that matters, right?

If you ever tried to write a Java application, I am sure you encountered this problem.

When I tried to compare two strings, it always gave me the wrong result, so I did a bit of a research and found out that I was doing it wrong.

Here is the code snippet that I used:
Code:
if (string1 == string2){
  System.out.println("The strings match!");
}else{
  System.out.println("The strings do not match!");
}

And when I executed the application, the given result was totally wrong. Those two strings matched, but it said "The two strings do not match."

So, after the research, I've found out that what I did was checking if those two variables are EXACTLY the same. (This might confuse you.)

The code snippet for comparing the two strings is this:
Code:
if (string1.equals(string2)){
  System.out.println("The two strings contain the same value.");
}else{
  System.out.println("The two strings do not contain the same value.");
}

This problem gave me really bad headache and I almost smashed my computer into the wall. I hope it helped someone.

Thank you for reading,
Vinwarez.


Re: Comparing String Variables - brandonio21 - 06-12-2012

Thanks for sharing! You can also use the following code snippet to see if two strings are equal to eachother.

Code:
if (string1.compareTo(string2) == 0){
  System.out.println("The two strings contain the same value.");
}else{
  System.out.println("The two strings do not contain the same value.");
}



Re: Comparing String Variables - Vinwarez - 06-13-2012

It's good to know that there are multiple ways to do the same thing. Thanks for sharing!