null character java

In this tutorial, I will be sharing about the null character in java. char keyword represents a primitive data type. First, we will look into how to represent empty char in Java.

Read Also:  How to convert char to Character in Java

💡 Did You Know?

The length of the null character in Java is not 0 but 1 as shown below:

  String str = Character.toString('\0');
System.out.println(str.length()); // Output: "1"

How to represent a Null or Empty Character in Java

There are 3 ways through which we can represent the null or empty character in Java.

1. Using Character.MIN_VALUE
2. Using '\u0000'
3. Using '\0'

1. Using Character.MIN_VALUE


Below we have assigned the smallest value of char data type i.e. Character.MIN_VALUE to variable ch.

public class EmptyCharacterExample {
    public static void main(String args[]) {
      // Assign null character to ch variable    
      char ch = Character.MIN_VALUE;
      String givenString = "Alive is Awesome";
      // Replacing 'A' in the givenString with null character 
      String result = givenString.replace('A',ch);
      // Printing the result string
      System.out.println("Replace givenString with null char: " + result);
    }
}

Output:
Replace givenString with null char: live is wesome


2. Using '\u0000'


We will assign char variable ch with '\u0000'. '\u0000' is the lowest range of the Unicode system used by Java.

public class EmptyCharacterExample2 {
    public static void main(String args[]) {
      // Assign null character to ch variable    
      char ch = '\u0000';
      String givenString = "Be in present";
      // Replacing 'e' in the givenString with null character 
      String result = givenString.replace('e',ch);
      // Printing the result string
      System.out.println("Replace givenString with null char: " + result);
    }
}

Output:
Replace givenString with null char: B in pr s nt


3. Using '\0'


We will assign char variable ch with '\0' special character. '\0' represents null.

public class EmptyCharacterExample3 {
    public static void main(String args[]) {
      // Assign null character to ch variable    
      char ch = '\0';
      String givenString = "Love Yourself";
      // Replacing 'o' in the givenString with null character 
      String result = givenString.replace('o',ch);
      // Printing the result string
      System.out.println("Replace givenString with null char: " + result);
    }
}

Output:
Replace givenString with null char: L ve Y urself


That's all for today. Please mention in the comments in case you have any questions related to the null character in java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry