Aaron
Aaron

Reputation: 151

char datatype and returning a letter v number

I've got this method here:

public char charAt(int location) {
    //TODO Finish method
    return "a";
}

which I've added return "a" just to test the char datatype as I'm a student and new to java. I am getting an error from Eclipse telling me to convert to String. Is "A" not a character?

It will return 1; no problems, but it won't take a single letter character?

Thanks.

Upvotes: 0

Views: 114

Answers (6)

StampedeXV
StampedeXV

Reputation: 2805

Everything in "doublequotes" is treated as string by the compiler. If you want a character use single quotes: 'a'.

Why return "a"; is not working but return 1; is:

int can be converted to char.
string cannot be (automatically) converted to char.

Upvotes: 2

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

If this is a char use follows

 public char charAt(int location) { //return char       
    return 'a';
    }

Or

public int charAt(int location) {   //return  int value of char
  return 'a';
}

Upvotes: 0

upog
upog

Reputation: 5531

try

  public char charAt(int location) {
            //TODO Finish method
            String str ="a";  // actual string could be different 
            return str.charAt(location);
        }

Upvotes: 0

SpringLearner
SpringLearner

Reputation: 13844

you are returning a string instead of char

do this way

public char charAt(int location) {
    //TODO Finish method
    return 'a';
}

Upvotes: 0

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

it should be 'a' instead of "a" . Double quotes represent String while single quotes represent char. So your code should be

public char charAt(int location) {
    //TODO Finish method
    return 'a';
}

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Should be

public char charAt(int location) {
    //TODO Finish method
    return 'a';
}

Not " quotes , should be '

Prefer to read :Is there a difference between single and double quotes in Java?

Upvotes: 8

Related Questions