0

Please consider this scenario:

char[] array = new char[4];
array[0] = 'a';
array[1] = '3';
array[3] = 'q';

As you can see, array[2] was never 'filled' with anything. What would be the value of array[2]?

What do I need to check for when iterating through a char array, looking for 'empty' cells?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131

5 Answers5

6

array[2] will be populated with the null char literal. The value of which is \u0000.

char is a primitive type. This means that it can never hold null, so like int, double and the rest, it needs some starting value. For int it's 0, for char it's \u0000, which actually evaluates to 0.

You can view the starting values for primitive types here.

christopher
  • 26,815
  • 5
  • 55
  • 89
  • So in an integer array of size 2 if I fill one cell with integer 0 and leave the other blank....does it mean both have same values ? Since null for int is 0 too. – Arnav Das Jan 31 '18 at 18:49
  • 1
    There is no `null` for any primitive types - there are default values that they get initialised to. If you set the first value in an array to 0 and leave the second, they will both have the same value. https://ideone.com/tB2NxQ – christopher Jan 31 '18 at 21:05
3

The answer is: (char)0.

Default values for primitives are 0, 0.0f, 0.0 (double), (char)0 and false (for boolean).

Applies to arrays and single variables.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
3

In Java, char[] array = new char[4]; will set all the memory associated to that array to zero. In this case therefore each element will have the value of the null character literal '\0'.

(This is not true for all languages, in C and C++, for example, the memory is unitialised and to access it before initialisation is, technically, undefined behaviour).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • It's not "technically undefined behaviour", it's just undefined behaviour :-) (and a very bad idea). – sleske Apr 11 '14 at 13:57
1

Empty cells of the array will be always 0, becs the arrays are automatically initialized by 0 so it will be '0'

Raju Sharma
  • 2,496
  • 3
  • 23
  • 41
0

Like others already said, the default value will be null '\u0000'. If you try to print it out, it will be an empty value. (Meaning you can't see it)

user3437460
  • 17,253
  • 15
  • 58
  • 106