How to create a char[] using data from a boolean array?

According to Primitive Data Types in the Language Basics lesson of trail Learning the Java Language in Oracle's Java tutorials:

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

Unicode value 0 (zero) is a non-printing character, as is unicode value 1 (one). That's why you aren't seeing anything printed. Either change digits to a int array or fill it with character literals such as '0' or '1'

If you use int array, the following code will suffice:

int[] digits = new int[n];
for (int i=0; i<n; i++) {
    if (nums[i]) {
        digits[i] = 1;
    }
}

for (int k=0; k<n; k++) {
    System.out.print (digits[k]);
}

Note that a int array is implicitly initialized such that all the elements are initially 0 (zero).


Your problem is that you don't have quotes surrounding the 1 and 0.

for (int i = 0; i < n; i++) {
    if (nums[i]) {
        digits[i] = '1';
    }
    else {
        digits[i] = '0';
    }
}

Without the quotes, they are cast from ints to chars. 0 is actually the null character (NUL), and 1 is start of heading or something like that. Java chars are encoded using UTF-16 (they're 16 bits long). The characters '0' and '1' are actually encoded by 48 and 49 respectively (in decimal).

EDIT: Actually, don't look at the ASCII table, look at the Unicode character set. Unicode is really a superset of ASCII, but it'll probably be more useful than the ascii table

Tags:

Java

Arrays