Core Java

Java char Primitive Type Example

In this article, we will see an example about the Java char, which is the character Primitive Type.

1. What are Primitive Types in Java?

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable’s type and name, as you’ve already seen:

char gear = '1';

Above code tell the Java Compiler that a field named “gear” exists, holds character data, and has an initial value of “1”. A variable’s data type determines the values it contains, and the operations that can be performed on it. In addition to char, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. 

The eight primitive data types supported by the Java are:

  • char: The char data type is a single 16-bit Unicode character.
  • byte: The byte data type is an 8-bit signed integer.
  • short: The short data type is a 16-bit signed integer.
  • int: By default, the int data type is a 32-bit signed integer.
  • long: The long data type is a 64-bit integer.
  • float: The float data type is a 32-bit floating point real number.
  • double: The double data type is a 64-bit floating point real number.
  • boolean: The boolean data type has only two possible values: true and false.

For more details about all the primitive data types in java please refer here.

2. Default Value for Java Char Type

It’s not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type.

This case applies generally for static variables and constants in java. If a variable is local within a class, it’s been allowed by java compiler to leave it un-initialized.

The Default value for java variable of char type is generally '\u0000' which is a Unicode representation for 0.

3. Initialization Of variable of Char Type

In Java, we can initialize our variable in 2 ways. One is using a literal (assigning value using equal operator) and the second is via Wrapper Classes.

3.1 Char Literal

Initializing a variable without new keyword is literal. A literal represents a fixed value in code form. For Example,

char gender = 'M';

Char literal holds one Unicode character at a time. If tried to assign a string, multiple character value, java compiler throws error.

Main.java

public class Main {
    public static void main(String[] args) {
        char name = 'AB';
    }
}

If the above code is compiled using javac src/Main.java, it will throw an error as shown in Fig. 1 below.

Java char - Output of Main.java
Fig. 1 Output of Main.java

3.2 Wrapper Class

As the name suggests, Wrapper classes encapsulates primitive Java types.
There is a Wrapper class for Each of the Eight Primitive Types in java.

Let’s try the same example with Wrapper classes.

MainWithWrapper.java

public class MainWithWrapper {
    public static void main(String[] args) {
        Character ch = new Character('a'); // Character is the wrapper class for char type
    }
}

When this file is compiled using the javac src/MainWithWrapper.java, it compiles successfully, but if MainWithWrapper.java is modified as shown in code snippet below, we get the same error shown in Fig. 1.

MainWithWrapper.java

public class MainWithWrapper {
    public static void main(String[] args) {
        Character ch = new Character('ab'); // Character is the wrapper class for char type
    }
}

3.3 Char Constant

Another way to initialize a char variable in java is by using constants. A constant in java is a variable whose value is determined at initialization and cannot be altered during the entire lifetime of the variable.

We can define constants in java program using the final and static keyword in java, as shown in the code snippet below,

CharLocalConstant.java

public class CharLocalConstant {
    static final char gender = 'M'; // this is where the constant is defined.
}

class SampleExtendedConstant extends CharLocalConstant {
    public static void main(String[] args) {
        System.out.println(CharLocalConstant.gender); // this is where we are simply using the Classname to access the constant
    }
}

This CharLocalConstant.java produces the same output as shown in Fig. 2.

Java char - Output of CharGlobalConstant.java
Fig. 2 Output of CharGlobalConstant.java

4. Common Operations on Char type variables

There are 8 Common operations that are applied on char type and provided by Character class.

  1. isLetter()
    A boolean isLetter() method is used in Java, for checking whether the given char value(ch) is a letter or not.
  2. isDigit()
    boolean isDigit() method in Java is used to check whether the given character is a digit or not.
  3. isWhitespace()
    Whitespace in Java is used as space, tab, or a new line, and this method checks whether the given char is whitespace or not.
  4. isUpperCase()
    boolean isUpperCase() method in Java is used, to checks whether the given char value is in uppercase or not.
  5. isLowerCase()
    boolean isLowerCase() method in Java is used to check whether the given char value is in lowercase or not.
  6. toUpperCase()
    char toUpperCase() method in Java is used when we want to transform the given lower case into the upper case.
  7. toLowerCase()
    char toLowerCase() method in Java is used to transform the given upper case to the lower case.
  8. toString()
    The toString() method in Java is a string class object which is returned for the specified char.

We can see all these functions in action in CharacterOps.java shown below,

CharacterOps.java

public class CharacterOps {
    public static void main(String[] args) {
        System.out.println(Character.isLetter('A'));
        System.out.println(Character.isDigit('1'));
        System.out.println(Character.isWhitespace(' '));
        System.out.println(Character.isUpperCase('C'));
        System.out.println(Character.isLowerCase('c'));
        System.out.println(Character.toUpperCase('a'));
        System.out.println(Character.toLowerCase('A'));
        System.out.println(Character.toString('D'));
    }
}

The output of the CharacterOps.java can be seen in Fig. 3 below.

Java char - Output of  CharacterOps.java
Fig. 3 Output of CharacterOps.java

5. Download the Source Code

Download
You can download the full source code of this example here: Java char Primitive Type Example

Abhinav Nath Gupta

Abhinav holds a Master degree in Computer Science and Engineering from the National Institute of Technology Karnataka. He has finished his graduation from Information Technology Department in the Anand Engineering College, Agra. During his studies he has been involved with a large number of projects ranging from Networking and Cryptography. He works as a software development engineer at a software development firm in bengaluru where he is mainly involved with projects based on Nodejs. He is interested in cryptography, data security, cryptocurrency and cloud computing, and published articles regarding these topics. He can be reached at abhi.aec89@gmail.com.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button