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.");


Messages In This Thread
Comparing String Variables - by Vinwarez - 06-12-2012, 12:03 PM
Re: Comparing String Variables - by Vinwarez - 06-13-2012, 04:02 AM

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

Forum Jump:


Users browsing this thread: 1 Guest(s)