19

The following statement doesn't work in Java, but works in C:

char c[] = "abcdefghijklmn";

What's wrong?

Does the char array can only be initialized as following?

char c[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'};
5
  • It should be String str="something"; for Java. You can use toCharArray() method of String class to get the char[]. Commented Jul 29, 2012 at 17:13
  • 2
    There's nothing wrong, those are just two different languages. Commented Jul 29, 2012 at 17:15
  • 1
    It doesn't work because Java has a real String class, not just a null terminated array of chars like C. Commented Jul 29, 2012 at 17:15
  • 1
    char[] is generally useless in Java. You will use String class in Java more than you will ever touch char[] Commented Jul 29, 2012 at 17:24
  • Or use StringBuilder if you want a mutable char[] Commented Jul 29, 2012 at 17:35

5 Answers 5

25

You could use

char c[] = "abcdefghijklmn".toCharArray();

if you don't mind creating an unnecessary String.

Unlike in C, Strings are objects, and not just arrays of characters.

That said, it's quite rare to use char arrays directly. Are you sure you don't want a String instead?

Sign up to request clarification or add additional context in comments.

2 Comments

The primitive types are not enough to represent all data types comparing to C?
All objects are built from basic data types, String included. But the point of using objects is that they offer a much richer API than basic data types. Want to remove whitespace from the beginning and end, use trim(). Want to search for a substring, use indexOf(). Want to split on separators, use split(). Want to make sure accesses to the String from concurrent threads is safe: no problem: String is thread-safe and immutable, unlike a char array. Why use a char array and reimplement all this by yourself?
11

You can initialize it from a String:

char[] c = "abcdefghijklmn".toCharArray();

However, if what you need is a string, you should simply use a string:

String s = "abcdefghijklmn";

Comments

3

If you don't want to use String toCharArray(), then yes, a char array must be initialized like any other array- char[] c = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'};

Comments

2

The literal "abcdefghijklmn" is a String object in Java. You can quickly convert this into a char array by using the String toCharArray() method.

Try this:

char[] c = "abcdefghijklmn".toCharArray();

Comments

2

Try this:

String a = "abcdefghijklmn";   
char[] c = a.toCharArray();

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.