1

I am trying to work out whether a certain portion of a string equals something. Here is the code:

String words[] = resulter.split(" ");
    secondword = words[1];
    if (secondword == "is"){
        isarepresent = true;
    }

So, for example the string resulter could equal "Someone is famous" and then this should detect that the second word is "is". But, for some reason the if statement does not seem to work.

Simon
  • 14,407
  • 8
  • 46
  • 61
James
  • 161
  • 1
  • 2
  • 12
  • 1
    Hi James, Welcome to StackOverflow. Just a note: you really should do a Google search before deciding to ask a question. This one has been asked and answered several times over here :) – W.K.S Dec 05 '13 at 20:43

4 Answers4

2
if (secondword.contentEquals("is")
{
isarepresent = true;
}
FinalDark
  • 1,748
  • 1
  • 16
  • 26
0

The equal operator (==) checks if two objects have the same location in memory. To check if two strings are equal, use the equals or equalsIgnoreCase() methods.

if(secondword.equals("is")){}

if(secondword.equalsIgnoreCase("Is")){}
W.K.S
  • 9,787
  • 15
  • 75
  • 122
0

You should not use == for String comparison. It will check the direct memory addresses.

Instead use this: if (secondword.equals("is").

skiwi
  • 66,971
  • 31
  • 131
  • 216
  • I disagree with the idea that you *cant*. If the Strings are `intern`ed == would work and nothing actually stops you from doing it anyway. – Sinkingpoint Dec 05 '13 at 20:57
  • @Quirliom True, I edited my post to reflect that you should not do it. The full explanation is indeed much more sophisticated, however I do not think the OP needs to know it. – skiwi Dec 05 '13 at 21:00
0

Only two add two useful lines. There are 2 main ways to compare Strings:

str1.equals(str2)

str1.contentEquals(str2)

With the first one (actually also equalsIgnoreCase()) you will compare two instances of String while with the second one you can compare a String with any instance of implementation of CharSequence. So depending on what you want to compare you should use the first or the second one.

It is also a good practice to place the literal at the beginning, so it's ensured that you don't get a NPE

"str".equals(strVar)
iberbeu
  • 15,295
  • 5
  • 27
  • 48