Shumail
Shumail

Reputation: 3143

Initialize character array

I am just new to Java and I am struck in my program with Array initialization because it's not working and contains some garbage. This is what I am doing:

char[] expArray = new char[expEv.length];   //expEv.length is int - expEv is another array
//I have tried all following but not working

expArray = {'\0'};     // error i get: Array constants can only be used in initializers
expArray = {'',};
expArray = {'\0'};

System.out.println("array value: " + expArray); // prints " array value: [C@1cd761a " 

Edit: I have also tried to use char[] expArray = new char[expEv.length] {'\0'}; but this doesn't work as

Please help me with this and explain the array initialization for the context.

Upvotes: 3

Views: 15999

Answers (2)

btse
btse

Reputation: 8021

The suggestion that these people are giving you is incorrect since I bet you still want to create a variable sized array. In fact, what you are currently doing is 100% fine.

Java automatically initializes variables that are not explicitly set. In your case, each value of your array is initialized to the null character. Here is what each variable type will be initialized to.

The only reason you are getting gibberish when printing like that is because Java's built in toString() is not doing what you're expecting. Here is what the built-in toString() is actually returning:

getClass().getName() + '@' + Integer.toHexString(hashCode()) 

If you really want to print the array's values then you need to do something like this:

System.out.println(Arrays.toString(expArray ));

Upvotes: 3

Dolda2000
Dolda2000

Reputation: 25855

Sorry, but Java just doesn't allow you to do that. However, this may be close enough:

char[] expArray = {'\0'};
expArray = java.util.Arrays.copyOf(expArray, expEv.length);

Though, in the case of initializing the array with a '\0', that is completely unnecessary, since the array creation itself will clear all the elements to zero.

Upvotes: -1

Related Questions