| Author |
Retrieve null array value
|
Nikunj Sharda
Greenhorn
Joined: Mar 25, 2009
Posts: 3
|
|
Hi,
find the below code
char[] eid = new char[20];
eid[0]='1';
eid[1] = '1';
eid[2]='3';
eid[3]='1';
eid[4]='1';
i have to check whether
for(int i=0;i<20;i++){
if(eid[i]==' '){ // here is the problem
throw new Exception();
}
}
the code is not going to if condition although after eid[5] is null.....what is the reason?
|
 |
Uli Hofstoetter
Ranch Hand
Joined: Nov 24, 2006
Posts: 57
|
|
Elements of char[] cannot be null.
Check out JLS, Section 4.12.1:
"A variable of a primitive type always holds a value of that exact primitive type."
So you start with an array full of zeros and then overwrite the first 5 elements, the rest is untouched.
Regards,
Uli
|
SCEA5, Certified ScrumMaster
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
Uli Hofstoetter wrote:
So you start with an array full of zeros and then overwrite the first 5 elements, the rest is untouched.
Correct. Nikunj Sharda, the point is that a new char[] isn't filled with "null" -- it's filled with 0 (not '0', but 0). So your test should be
if (eid[i] == 0) {
|
[Jess in Action][AskingGoodQuestions]
|
 |
Nikunj Sharda
Greenhorn
Joined: Mar 25, 2009
Posts: 3
|
|
Ernest Friedman-Hill wrote:
Uli Hofstoetter wrote:
So you start with an array full of zeros and then overwrite the first 5 elements, the rest is untouched.
Correct. Nikunj Sharda, the point is that a new char[] isn't filled with "null" -- it's filled with 0 (not '0', but 0). So your test should be
if (eid[i] == 0) {
thanks...that's works but what happen if 0 already exists than that will not give result as expected
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
|
If you really need to be able to tell the difference between a character 0 and "no character", then you'll have to do something fancier. For example, you could use an array of java.lang.Character objects; such an array could include nulls. Or you could use two arrays: one char[] to hold the values, and one boolean[] to hold a "full/empty" flag. The second idea would actually use less memory, although it's less elegant.
|
 |
 |
|
|
subject: Retrieve null array value
|
|
|