-1

What's the best way to compare character of an array to a string.

    import java.io.Console;
    class msd{
    public static void main(String[] args){
    Console console= System.console();
    String letter="Hello";
    String[] Arrayname=letter.split("");

    if(Arrayname[0] == "H")
    console.printf("success");
    else
    console.printf("failure");
    }
   }

Output

    failure

Expecting to be success.

Mari Selvan
  • 171
  • 1
  • 7
  • You're better off using the `charAt()` method rather then splitting the string. E.g. `letter.charAt(0) == 'H'` – radoh Mar 27 '17 at 11:17
  • You can use String.substring() and equals method. For your case, you can use Arrayname.substring(0,1).equals("H") condition. – Rishabh Gupta Mar 27 '17 at 11:20

1 Answers1

1

You have to use the equals method to do so:

Arrayname[0].equals("H")

The == operator compares references not values.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207