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.
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 ));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With