GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Initialization of character arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Initialization of character arrays" Watch "Initialization of character arrays" New topic
Author

Initialization of character arrays

Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Hi. I came across this question and it has me confused.
Question:
After the declaration:
char[] c = new char[100];
what is the value of c[50]?
a) 50
b) 49
c) '\u0000'
d) '\u0020'
e) " "
f) cannot be determined
g) always null until a value is assigned
The given answer to the question is c.
I included the code above in a simple program and concluded from the output that character arrays are initalized with single space characters. Below is the code I used:
Sample program:
public class Test6 {
public static void main(String args[]) {
char[] c = new char[100];
System.out.println("This"+c[50]+"is what comes out");
} //end of class Test6

The output:
This is what comes out
My question is, what is the difference between the answers c and d? How does Java store the space character? When I tried it out in another simple program, both c and d yielded the space character.
Thanks in advance for the help.

[This message has been edited by Gaia Nathan (edited August 13, 2001).]
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9046
    
  10
\u0000 is null
\u0020 is a space
You can see the difference in some editors but not in others.
Elements of an uninitialized char array are by default initialized to null.

[This message has been edited by Marilyn deQueiroz (edited August 14, 2001).]


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Thanks Marilyn.
I'm using the DOS editor and I guess that's why I couldn't see the difference.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Initialization of character arrays