1

I have a very simple question that I really can't understand.

I have a method that takes a string and determines what the first character of the string is, and then returns it.

public String deterFirstChar(String value){
    String keyValue;
    char res; 
    res = value.charAt(0);
    keyValue = Character.toString(res);
    if (keyValue == "C"){
        return keyValue;
    } else if (keyValue == "G") {
        return keyValue;
    }
    System.out.println("Error: Wrong keyParam");
    return "F";
}

However, intstead of returning, for an example keyValue = C, it skipps the if statement and returns "F" when I know for sure that keyValue is "C".

Why is this occurring?

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
Erik Soderstrom
  • 313
  • 5
  • 19

3 Answers3

7

First, check How do i compare string?

Secondly, you don't have to convert the char to String to check its value, you can do it like below

res = value.charAt(0);
//keyValue = Character.toString(res); NOT REQUIRED
if (res == 'C'){
    return Character.toString(res);
} else if (res == 'G') {
Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
4

You should not compare strings using ==, use equals() method

 if (someString.equals("C")){
        return someString;
    } else if (someString.equals("G")) {
        return someString;
    }
  • == checks whether two variables refer to the same object.
  • equals() method checks whether the contents of the object are same or not.
  • so If == returns true, then equals() method also returns true because they are referring to the same object hence they are equal

You can find a great explanation for string comparison with equals and assignment If you want to use characters,

res = value.charAt(0);
if (res == 'C'){
    return Character.toString(res);
} else if (res == 'G') {
    return Character.toString(res);
 }
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
0

Try this

public static char findFirstChar(String string){
    return string.charAt(0);
}
    char out = findFirstChar("Rakesh");
    System.out.println("First Character:"+out);
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55