0

I have a variable named title which is having the value "Javascript,XML,XHTML,CSS,Ajax". I need to compare in an if statement if the title equals to the above value some code needs to be run.

I have used

if (title == "Javascript,XML,XHTML,CSS,Ajax"){

} else if (title == " ") {

} else {

}

When the title is null, the code goes to the second else part and gets the correct result. But when the title is equal to Javascript,XML,XHTML,CSS,Ajax the code goes to the last else part instead of going to the if part.

What mistake have I done here? I have checked the upper lower case and also spelling along with the delimiter comma the string is same just as in the variable title. Then why do I not get the correct answer.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Archana
  • 237
  • 3
  • 9
  • 17

5 Answers5

3

The == comparison operator is not correct way to compare string contents. You should instead use the .equals method:

if (title.equals("Javascript,XML,XHTML,CSS,Ajax")) {
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
hanumant
  • 1,091
  • 4
  • 15
  • 27
2

You are using == to compare strings. You have to use title.equals("Javascript, ...") for string comparison; otherwise, you are checking to see if they are in fact the same object in memory.

0

If you're using Java, you'll need to use if (title.equalsIgnoreCase("Javascript,XML,XHTML,CSS,Ajax")). The equals operator is used to determine if two pointers have the same value (i.e. point to the same object).

Christopher Armstrong
  • 7,907
  • 2
  • 26
  • 28
0
if(title.equals("Javascript,XML,XHTML,CSS,Ajax")) {
....
}

Another advice, you should take a look at some basic Java first!

Yeameen
  • 833
  • 7
  • 8
0

In Java, strings are objects. The == operator tells you whether they are the same instance of the same object. Use the equals(...) method for this instead.

Brad
  • 603
  • 4
  • 12