Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Comparing String Variables
#1
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.
Also known as Rocketalypse.
System.out.println("I prefer Java.");
#2
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.");
}
My Blog | My Setup | My Videos | Have a wonderful day.
#3
It's good to know that there are multiple ways to do the same thing. Thanks for sharing!
Also known as Rocketalypse.
System.out.println("I prefer Java.");


Possibly Related Threads…
Thread Author Replies Views Last Post
  Comparing String Variables 0 2,135 Less than 1 minute ago
Last Post:

Forum Jump:


Users browsing this thread: 1 Guest(s)