0

I have a function which gets passed in a string. From that I split the string with

String[] info = s.split("\\s+");

I then want to see if the first index is a plus sign (+). If i enter in a string: + other stuff it claims that + != +

System.out.println("Check if "+ info[0]+ " = +");
if(info[0]=="+") {
    System.out.println("yes");
} else
    System.out.println("no");

This is the output i get:

Interp> + 
Check if + = + 
no

anyone know why this is?

Joe Jankowiak
  • 295
  • 3
  • 15

3 Answers3

4

It should be:

if(info.length > 0 && "+".equals(info[0])) {
jdb
  • 4,419
  • 21
  • 21
3

When comparing Strings, always use String.equals(String str). == will compare strings for equal memory identity, String.equals() will compare for the same content.

if(info[0].equals("+")) { do stuff.. }

Timr
  • 1,012
  • 1
  • 14
  • 29
0

For comparing two Strings you should always use myString.equals(otherstring); In your case this could be

if(info[0].equalsIgnoreCase("+") {
    System.out.println("yes");
} else
    System.out.println("no");
}

These are the possibilities for Strings:

  • string1.equals(string2) -> returns boolean
  • string1.equalsIgnoreCase(string2) -> returns boolean
  • string1.compareTo(string2) -> returns -1 if string1 comes alphabetically before string2, 0 if both strings are equal, +1 if string2 comes alphabetically before string1

For explanation: the == operator compares the memory reference of the two strings not the content of the strings.

GameDroids
  • 5,584
  • 6
  • 40
  • 59