Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Java

Java: incompatible types: char cannot be converted to String

· 11 min read

You want the first letter of a name, you find charAt(0), and Java refuses to compile:

Terminal
Main.java:4: error: incompatible types: char cannot be converted to String
        String initial = name.charAt(0);
                                    ^
1 error

incompatible 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:

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:

  • char is 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).
  • String is 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:

Main.java
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);
    }
}
Terminal
AAAA

Which one to use:

  • String.valueOf(c): clear and common. It works for any primitive, not only char.
  • Character.toString(c): says exactly what it does.
  • name.substring(0, 1): skips the char completely. It takes a piece of the String, and a piece of a String is a String. A good choice when you wanted "the first letter as text" from the start.
  • "" + c: works because joining anything to a String gives a String. 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:

java
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:

java
String grade = 'A';
Terminal
Main.java:3: error: incompatible types: char cannot be converted to String
        String grade = 'A';
                       ^
1 error

Use 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:

Main.java
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);
        }
    }
}
Terminal
Main.java:6: error: incompatible types: char cannot be converted to String
            reversed = word.charAt(i);
                                  ^
1 error

There 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:

java
reversed += word.charAt(i);
Terminal
desserts

reversed += 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:

Main.java
public class Main {
    static String firstLetter(String word) {
        return word.charAt(0);
    }

    public static void main(String[] args) {
        System.out.println(firstLetter("Java"));
    }
}
Terminal
Main.java:3: error: incompatible types: char cannot be converted to String
        return word.charAt(0);
                          ^
1 error

Either 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:

Main.java
public class Main {
    static void greet(String letter) {
        System.out.println("Hello, " + letter);
    }

    public static void main(String[] args) {
        greet('A');
    }
}
Terminal
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 error

That Note line is worth reading. If you recompile with javac -Xdiags:verbose Main.java, Java explains the call in full:

Terminal
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 error

required 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:

java
ArrayList<String> letters = new ArrayList<>();
letters.add('x');
Terminal
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 error

Add "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:

java
for (String c : word.toCharArray()) {
    System.out.println(c);
}
Terminal
Main.java:4: error: incompatible types: char cannot be converted to String
        for (String c : word.toCharArray()) {
                                        ^
1 error

Write 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:

java
char c = "y";
Terminal
Main.java:7: error: incompatible types: String cannot be converted to char
        char c = "y";
                 ^
1 error

Use '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 '==' with first type: String and second type: char: you compared text with a character, as in answer == 'y'. Use answer.equals("y") or answer.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 a char. See String cannot be converted to int.
  • incompatible types: possible lossy conversion from int to char: you put an int result into a char, 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:

java
char a = 'H', b = 'i';
System.out.println(a + b);
System.out.println("" + (a + b));
System.out.println("" + a + b);
Terminal
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 same char cannot be converted to String error. Use String.valueOf.
  • name.charAt(0).toString(). A char is a primitive and has no methods, so this fails too (char cannot be dereferenced). Character.toString(c) is the version that works.
  • Changing every char to String. 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:

java
String initials = first.charAt(0) + last.charAt(0);
  1. Read the message. This time it says incompatible types: int cannot be converted to String. An int? There's no number in that line.
  2. Here's the catch: char + char adds the two character codes and gives an int. 'A' + 'S' is 65 + 83 = 148, not "AS".
  3. Put a String first so + joins: String initials = "" + first.charAt(0) + last.charAt(0);
  4. Or build it clearly: String.valueOf(first.charAt(0)) + last.charAt(0).
  5. Run it with first = "Alex" and last = "Smith", and check that it prints AS, not a number.

Practice

  1. String s = 'hello'; What does Java say, and why isn't it the error from this article?
  2. Fix: String last = word.charAt(word.length() - 1);
  3. 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

  1. Find where the char comes from: charAt, single quotes, or toCharArray().
  2. Decide what the value should be: one letter you compare (char) or text you join and pass on (String).
  3. To convert, use String.valueOf(c) or Character.toString(c); to avoid the char, use substring.
  4. Use double quotes for String and single quotes for char.
  5. When joining characters, make sure a String comes 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.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Java

Java error: cannot find symbol, and how to fix it

Fix Java's error: cannot find symbol: read the symbol and location lines, then fix typos, missing imports, variables out of scope and wrong method names. With compiled examples.

Error explained · · 10 min read

Java

bad operand types for binary operator (Java fix)

Fix Java's bad operand types for binary operator '&&', '<', '>=' or '*': what first type and second type mean, the causes and fixes, with examples.

Error explained · · 13 min read

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right