Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initialization of character arrays

 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9067
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
\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).]
 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic