• Post Reply Bookmark Topic Watch Topic
  • New Topic

Retrieve null array value  RSS feed

 
Nikunj Sharda
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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) {
 
Nikunj Sharda
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 &quot;null&quot; -- 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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!