0

I have

String x = g.substring(0, 1);
if (x == "S") {
    stuff
}

I have a string, "Safety", but "stuff" doesn't run and my watch say x value = S and x=="S" = false.

0

9 Answers 9

3

== is used for identity comparison, and it checks whether the two reference points to the same object (in your case the object is String).

You should use the equals method to compare the contents of your string:

if (x.equals("S"))
Sign up to request clarification or add additional context in comments.

Comments

1

This compares references not string equality x=="S" you should use "S".equals(x).

Comments

1

Use equals() method of String class instead, not ==.

Comments

0
if(x.equals("S"))

== checks the reference and not the value.

Comments

0

You should use the .equals method to compare Strings (and any non-primitives in general).

if (x.equals("S")) {
    //stuff
}

Comments

0

Many problems...

  • Your variable x is a String! You shouldn't use == operator with that, use .equals() instead

  • Also, while you're at it, you should use .equalsIgnoreCase() to ignore case.

  • By the way, I should note that there is the String.charAt(int) function too, which returns the character at the specified place...

But if you would like to select all Strings (your question didn't reveal your original intentions why and what you are trying to achieve), but I'd look into regular expressions, and using String.matches()

Comments

0

You need to use String.equals for comparing string content. The == operator is used for comparing object references.

Switching the positions of the arguments will avoid a NullPointerException:

if ("S".equals(x))

Comments

0

In Java equals() checks equality and == checks identity.

Comments

0

Why don't you use the charAt function and do it like this:

    char x = g.charAt(0);
    if (x == 'S') {
       // Stuff
    }

If you don't want to use char, use the equals method in the if block comparison as:

   String x = g.substring(0, 1);
   if (x.equals("S")) {
      // stuff
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.