9

I tried the below, but Eclipse throws an error for this.

while((s.charAt(j)== null)

What's the correct way of checking whether a character is null?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
user2062360
  • 1,323
  • 5
  • 16
  • 29
  • 1
    A `char` is a primitive. `null` is reserved for unasigned references. – madth3 Feb 13 '13 at 01:07
  • 3
    Is `s` String? If so `s.charAt` will return primitive type `char`, not object `Character` so it can't be null. Default values of `char` array are `'\u0000'` or simpler `'\0'`. You could even use `s.charAt(j) == 0` – Pshemo Feb 13 '13 at 01:09
  • Are you trying to check for the end of the String as in C? – madth3 Feb 13 '13 at 01:11

6 Answers6

14

Check that the String s is not null before doing any character checks. The characters returned by String#charAt are primitive char types and will never be null:

if (s != null) {
  ...

If you're trying to process characters from String one at a time, you can use:

for (char c: s.toCharArray()) {
   // do stuff with char c  
}

(Unlike C, NULL terminator checking is not done in Java.)

Reimeus
  • 158,255
  • 15
  • 216
  • 276
10

Default value to char primitives is 0 , as its ascii value. you can check char if it is null. for eg:

char ch[] = new char[20]; //here the whole array will be initialized with '\u0000' i.e. 0
    if((int)ch[0]==0){
        System.out.println("char is null");
    }
Rashmi singh
  • 151
  • 1
  • 5
8

Correct way of checking char is actually described here.

It states:

Change it to: if(position[i][j] == 0) Each char can be compared with an int. The default value is '\u0000' i.e. 0 for a char array element. And that's exactly what you meant by empty cell, I assume.

Community
  • 1
  • 1
Bugs Happen
  • 2,169
  • 4
  • 33
  • 59
3

You can use the null character ('\0'):

while((s.charAt(j)=='\0')
double-beep
  • 5,031
  • 17
  • 33
  • 41
Mayank Soni
  • 81
  • 1
  • 4
0

I actually came here from reading a book "Java: A Beginner's Guide" because they used this solution to compare char to null:

(char) 0

Because in ASCII table, null is at the position of 0 in decimal.

So, solution to OP's problem would be:

while((s.charAt(j) == (char) 0)

I also tried out the already offered solution of:

while((s.charAt(j)=='\0')

And it also worked.

But just wanted to add this one too, since no one mentioned it.

tapavko
  • 196
  • 1
  • 5
-2

If s is a string and is not null, then you must be trying to compare "space" with char. You think "space" is not a character and space is just null, but truth is that space is a character. Therefore instead of null, use (which is a space) to compare to character.

Qiu
  • 5,651
  • 10
  • 49
  • 56
Harpreet
  • 11
  • 2