Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to init char array using char literals?

Tags:

java

char

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'};
like image 365
Victor S Avatar asked Jul 29 '12 17:07

Victor S


1 Answers

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?

like image 135
JB Nizet Avatar answered Oct 22 '22 12:10

JB Nizet