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
?
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
?
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.)
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");
}
Correct way of checking char
is actually described here.
It states:
Change it to:
if(position[i][j] == 0)
Eachchar
can be compared with anint
. The default value is'\u0000'
i.e. 0 for achar
array element. And that's exactly what you meant by empty cell, I assume.
You can use the null character ('\0'
):
while((s.charAt(j)=='\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.
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.