You want the first letter of a name, you find charAt(0), and Java refuses to compile:
Main.java:4: error: incompatible types: char cannot be converted to String
String initial = name.charAt(0);
^
1 errorincompatible types: char cannot be converted to String means you put a single character, a char, into a place that expects text, a String. To you, A and "A" look the same. To Java, they are two different types, and it won't turn one into the other on its own. This article shows where the char comes from in each common case and four ways to make it a String.
Try it yourself
Save this as Main.java and run javac Main.java:
public class Main {
public static void main(String[] args) {
String name = "Alex";
String initial = name.charAt(0);
System.out.println("Initial: " + initial);
}
}You'll see the error above. The ^ points at the end of name.charAt(0): that expression produced the char.
What the error means
Java has two types for text, and they are not interchangeable:
charis one character, like'A','7'or'?'. It's a primitive type, written with single quotes, and Java stores it as a number (the character's code).Stringis a sequence of characters, like"Alex","A"or even""(empty). It's an object, written with double quotes.
char cannot be converted to String says: the value is a char, and the place it's going (a variable, a parameter, a return value, a list) is a String. A String with one letter in it is still a String, not a char.
Cause 1: charAt() returns a char
charAt(i) gives you the character at position i, and its return type is char. That's the cause of the example above, and it's by far the most common one.
The fix: four ways to turn a char into a String
All four of these compile and give the same result:
public class Main {
public static void main(String[] args) {
String name = "Alex";
String initial = String.valueOf(name.charAt(0));
String initial2 = Character.toString(name.charAt(0));
String initial3 = name.substring(0, 1);
String initial4 = "" + name.charAt(0);
System.out.println(initial + initial2 + initial3 + initial4);
}
}AAAAWhich one to use:
String.valueOf(c): clear and common. It works for any primitive, not onlychar.Character.toString(c): says exactly what it does.name.substring(0, 1): skips thecharcompletely. It takes a piece of theString, and a piece of aStringis aString. A good choice when you wanted "the first letter as text" from the start."" + c: works because joining anything to aStringgives aString. It's short, but the other three show your intent better.
Or keep it a char
Sometimes the right fix is the other direction: maybe you don't need a String at all. If you only want to compare or print the letter, store it as a char:
char initial = name.charAt(0);
System.out.println("Initial: " + initial);Ask yourself what you'll do with the value next. A single letter you compare with 'A' is happiest as a char. Text you'll join, store in a list of names, or pass to a method that wants a String should be a String.
Cause 2: single quotes instead of double quotes
Java decides the type from the quotes. Single quotes make a char:
String grade = 'A';Main.java:3: error: incompatible types: char cannot be converted to String
String grade = 'A';
^
1 errorUse double quotes for a String: String grade = "A";. If you come from Python or JavaScript, this one catches many people: in those languages, single and double quotes both make text. In Java, they don't.
Cause 3: building a String in a loop
Reversing a word is a classic exercise, and a classic place to meet this error:
public class Main {
public static void main(String[] args) {
String word = "stressed";
String reversed = "";
for (int i = word.length() - 1; i >= 0; i--) {
reversed = word.charAt(i);
}
}
}Main.java:6: error: incompatible types: char cannot be converted to String
reversed = word.charAt(i);
^
1 errorThere are two problems on this line. The type problem is the one Java reports. The logic problem is hidden behind it: = would replace reversed each time, so even with the right type you'd end up with one letter. You want to add each letter, and += does both jobs:
reversed += word.charAt(i);dessertsreversed += c means reversed = reversed + c. The left side is a String, so + joins the character on as text. (For long texts in big loops, StringBuilder is faster, but for a word or a sentence, += is fine.)
Cause 4: a method that should return a String
The return type on the method's first line decides what return must give back:
public class Main {
static String firstLetter(String word) {
return word.charAt(0);
}
public static void main(String[] args) {
System.out.println(firstLetter("Java"));
}
}Main.java:3: error: incompatible types: char cannot be converted to String
return word.charAt(0);
^
1 errorEither change the return type to static char firstLetter(...), or convert: return String.valueOf(word.charAt(0));.
Cause 5: passing a char to a String parameter
The same happens when you call a method:
public class Main {
static void greet(String letter) {
System.out.println("Hello, " + letter);
}
public static void main(String[] args) {
greet('A');
}
}Main.java:6: error: incompatible types: char cannot be converted to String
greet('A');
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorThat Note line is worth reading. If you recompile with javac -Xdiags:verbose Main.java, Java explains the call in full:
Main.java:6: error: method greet in class Main cannot be applied to given types;
greet('A');
^
required: String
found: char
reason: argument mismatch; char cannot be converted to String
1 errorrequired is what the method expects, found is what you gave it. Call it with greet("A").
Cause 6: lists and for-each loops
A list declared as ArrayList<String> only accepts String values:
ArrayList<String> letters = new ArrayList<>();
letters.add('x');Main.java:5: error: incompatible types: char cannot be converted to String
letters.add('x');
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorAdd "x" instead. Or, if the list should hold single characters, declare it as ArrayList<Character> (lists hold objects, so you use Character, the object version of char).
The loop version: toCharArray() gives an array of char, so the loop variable must be a char too:
for (String c : word.toCharArray()) {
System.out.println(c);
}Main.java:4: error: incompatible types: char cannot be converted to String
for (String c : word.toCharArray()) {
^
1 errorWrite for (char c : word.toCharArray()), and the loop prints J, a, v, a on separate lines.
The opposite error: String cannot be converted to char
Double quotes where Java expects a char give the mirror image:
char c = "y";Main.java:7: error: incompatible types: String cannot be converted to char
char c = "y";
^
1 errorUse 'y'. If you have a String and need one of its characters, use charAt: char c = text.charAt(0);.
The same error appears in a switch on a char with String labels, for example switch (answer.charAt(0)) { case "y": ... }. The labels must be char values: case 'y':.
Errors that look alike
bad operand types for binary operator '=='withfirst type: Stringandsecond type: char: you compared text with a character, as inanswer == 'y'. Useanswer.equals("y")oranswer.charAt(0) == 'y'. The full explanation is in bad operand types for binary operator.incompatible types: String cannot be converted to int: the same family, with a number instead of achar. See String cannot be converted to int.incompatible types: possible lossy conversion from int to char: you put anintresult into achar, often after doing maths on a character. Cast it on purpose:(char) (c + 1).
The surprise that isn't an error: adding two chars
Because a char is stored as a number, + between two char values adds their codes instead of joining them:
char a = 'H', b = 'i';
System.out.println(a + b);
System.out.println("" + (a + b));
System.out.println("" + a + b);177
177
Hi'H' is 72 and 'i' is 105, so a + b is 177. Putting "" first changes everything, but only when Java reads it first: "" + a + b is worked out from left to right, so it becomes "H" and then "Hi". In the middle line, the brackets are calculated first, so the sum is already 177 before the text joins in.
Wrong fixes that don't help
- Casting:
(String) name.charAt(0). You can't cast a primitive to an object type. Java answers with the samechar cannot be converted to Stringerror. UseString.valueOf. name.charAt(0).toString(). Acharis a primitive and has no methods, so this fails too (char cannot be dereferenced).Character.toString(c)is the version that works.- Changing every
chartoString. It makes this error go away and creates new ones wherever you compare with'A'. Choose one type per value based on what you'll do with it.
A debugging walkthrough
You write a program that prints initials, and it fails on this line:
String initials = first.charAt(0) + last.charAt(0);- Read the message. This time it says
incompatible types: int cannot be converted to String. Anint? There's no number in that line. - Here's the catch:
char + charadds the two character codes and gives anint.'A' + 'S'is 65 + 83 = 148, not"AS". - Put a
Stringfirst so+joins:String initials = "" + first.charAt(0) + last.charAt(0); - Or build it clearly:
String.valueOf(first.charAt(0)) + last.charAt(0). - Run it with
first = "Alex"andlast = "Smith", and check that it printsAS, not a number.
Practice
String s = 'hello';What does Java say, and why isn't it the error from this article?- Fix:
String last = word.charAt(word.length() - 1); - What does
System.out.println('a' + 1);print?
Answers. (1) unclosed character literal (three errors, in fact): single quotes can only hold one character, so Java can't even read it as a char. Use "hello". (2) String last = String.valueOf(word.charAt(word.length() - 1));, or word.substring(word.length() - 1). (3) 98: 'a' is 97, plus 1. For the next letter, cast: (char) ('a' + 1) prints b.
Frequently asked questions
What is the difference between char and String in Java?
char holds exactly one character and uses single quotes. String holds any number of characters, including one or none, and uses double quotes. char is a primitive; String is an object with methods like length() and equals().
How do I convert a char to a String in Java?
String.valueOf(c) or Character.toString(c). Both are standard and clear.
How do I get the first letter of a String as a String?
text.substring(0, 1). It returns a String directly, so there's nothing to convert.
How do I convert a char array to a String?
new String(chars) or String.valueOf(chars). Both turn {'H', 'i'} into "Hi".
Why does charAt return a char and not a String?
Because a String is built from char values, and charAt gives you one of them as it is. It's cheaper and lets you compare with 'A' or do maths on the character code.
A quick checklist
- Find where the
charcomes from:charAt, single quotes, ortoCharArray(). - Decide what the value should be: one letter you compare (
char) or text you join and pass on (String). - To convert, use
String.valueOf(c)orCharacter.toString(c); to avoid thechar, usesubstring. - Use double quotes for
Stringand single quotes forchar. - When joining characters, make sure a
Stringcomes first, or you'll add numbers.
For a method that works on every error in every language, read how to read an error message. The official documentation for String.valueOf(char)) and charAt) lists the exact types.
