Can you check if char is null or not in Java ?

Javacharter
1 min readApr 10, 2023

--

In this post, I will be sharing one important information about char in Java. char stands for character. Java has a char type which represents a primitive data type. char can be created from character literals & numeric representation.

One day I was writing code for “Finding the first non repeated character in a string using Java” as that was the question asked in one of my interviews. Simplest approach I could think of is the following :

Note : Please note that this program may not be perfect and can be improved further.

If you go through the code, I have put one condition if(ch!=0) ! Yes that is true! A char in Java cannot be null as it is a primitive . If you put a null check, it will give you compile time error. “The operator != is undefined for the argument type(s) char, null

So workaround for that is to check using ‘0’. Is this correct ? What are your thoughts about this ? Please write down in the comment section .

Happy Learning 😇😊

--

--

Javacharter

At Java Charter you can get evolve with Java and technologies like Spring , Spring Boot , REST APIs, Microservices, Various Tools, Azure Cloud etc…