0

In Java, I have been trying to append a string to a Char Array. I am using the code:

list = (new String(list) + word).toCharArray();

With list being the char array, and word being a string.

What am I doing wrong?

2
  • What is the exact error that you get? Commented Oct 8, 2013 at 16:32
  • code is valid to do the toCharArray if list and word are String. Commented Oct 8, 2013 at 16:33

3 Answers 3

1

Make sure that:

  • list is char[] or byte[] (or String, StringBuilder, StringBuffer but that's a bit off-topic)
  • list != null

Explanation:

  • the String one-argument constructor only takes the types I've listed above
  • new String(null) is an ambiguous call to the String one-argument constructor
  • word can be any type, including a null object (in which case it will be represented as "null")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - I was using a null string
0

what is the list type? Character[] or char[].

Since arrays are objects, they are not interchangeable.

For this situation list must be char[].

Comments

0

You could show us the exact error what you get. By using the below code I can get some output without any error.

    String word="hi";
    char[] list=null;
    if(list!=null)
        list = (new String(list) + word).toCharArray();
    else
        list = word.toCharArray();
    for(char ch: list)
    System.out.println("List: "+ch);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.