Java Type Conversions - What is Type Conversion in Java

Java internally converts the data types of values in an expression to ensure compatibility among them. In this unit, we will learn different types of Type Conversions in Java. To get started, let's learn how to check the data type of a value in Java.

1. Checking the Data Type

We have already learned that Java supports various data types that are categorized into primitive and non-primitive data types. We can check the data type of the variable or value by calling getClass().getSimpleName() method.

 

1.1 Checking the Data Type of Non-primitives

Example

class Main {

    public static void main(String[] args) {

        String username = "Java";

        System.out.println(username.getClass().getSimpleName());

    }

}

 

Output

String

getClass().getSimpleName() returns the class name of the object

 

1.2 Checking the Data Type of Primitives

The getClass().getSimpleName() is callable by objects only, so the primitives must first be cast (change) into an object.

The object is an instance of a class. For example, in the statement String str = new String("ABC");, str is an object (also called as instance) of the class String.

We can convert the primitive data types into an object using the Object keyword.

Example 1:

class Main {

    public static void main(String[] args) {

        int age = 10;

        System.out.println(((Object)age).getClass().getSimpleName());

    }

}

 

Output

Integer

 

Here, Integer is the wrapper class of int which we will learn about in upcoming sessions.

Example 2:

class Main {

    public static void main(String[] args) {

        float value = 10.0f;

        System.out.println(((Object)value).getClass().getSimpleName());

    }

}

 

Output

Float

Example 3:

class Main {

    public static void main(String[] args) {

        char letter = 'A';

        System.out.println(((Object)letter).getClass().getSimpleName());

    }

}

 

Output

Character

 

2. Type Conversion

Type conversion is a process of converting the value of one data type (int, char, float, etc.) to another data type.

Java provides two types of type conversion :

  1. Implicit Type Conversion

  2. Explicit Type Conversion (Type Casting)

 

2.1 Implicit Type Conversion

Java compiler automatically converts one data type to another data type. This process is called Implicit type conversion.

 

2.1.1 Hierarchy of Data Types

char -> byte -> short -> int -> long -> float -> double -> boolean -> String

If an expression contains values of more than one data type, the lower data type values will be converted to a higher data type.

When an expression contains any combination of char, byte, short or int, the result will be of int data type.

 

Example 1: Type conversion from int to long

class Main {

    public static void main(String[] args) {

        int value1 = 4;

        long value2 = 5L;

        System.out.println(((Object) (value1 + value2)).getClass().getSimpleName());

    }

}

 

Output

Long

In the above example, the expression value1 + value2 consists of two different data types int and long. As the long is higher data type than int, the int is converted to long resulting in a final value of long data type.

Example 2: Implicit type conversion on assignment

class Main {

    public static void main(String[] args) {

        int value1 = 4;

        long value2 = 5L;

        long sum = value1+value2;

        System.out.println(((Object)sum).getClass().getSimpleName());

    }

}

 

Output

Long

The sum of value1+value2 in the example above results in a long data type. If we want to store the result, we must declare a variable of this type.

What if we store the result in an int data type?

class Main {

    public static void main(String[] args) {

        int value1 = 4;

        long value2 = 5L;

        int sum = value1+value2;

        System.out.println(((Object)sum).getClass().getSimpleName());

    }

}

 

Output

file.java:5: error: incompatible types: possible lossy conversion from long to int

      int sum = value1+value2;

 

As the result value is of type long, it throws an error if stored in the int data type

Below, the table gives you the data type of the result of an expression involving different data types.

Data type 1

Data type 2

Final Data type

char

int

int

char

long

long

char

float

float

char

String

String

int

long

long

int

float

float

int

String

String

long

float

float

long

String

String

float

String

String

boolean

String

String

 

Example 3: Implicit type conversion on assignment

class Main {

    public static void main(String[] args) {

        int value1 = 10;

        float value2 = value1;

 

        System.out.println(value1);

        System.out.println(value2);

    }

}

 

Output

10

10.0

Here we have assigned int variable value1 with a value of 10 to a float variable value2. At assignment, Java converts the data type of value 10 to float implicitly resulting in a float value of 10.0

 

2.2 Explicit Type Conversion (Type Casting)

In Explicit Type Conversion, programmers change the data type of a value to the desired data type. This type of conversion is also called Type Casting since the programmer casts (changes) the data type. Any combination of int, float and long is possible.

Example 1: Type casting from long to float

class Main {

    public static void main(String[] args) {

        long x = 10L;

        float y = (float) x;

        System.out.println(y);

    }

}

 

Output

10.0

 

Example 2: Type casting data type from float to int

class Main {

    public static void main(String[] args) {

        float x = 10.0f;

        int y = (int)x + 1;

        System.out.println(y);

    }

}

 

Output

11

Any combination of int, float, or long with char is possible. The result will be a character based on the Unicode values.

 

Example 3: Type casting data type from int to char

class Main {

    public static void main(String[] args) {

        int x = 65;

        System.out.println((char) x);

    }

}

 

Output

A

The number 65 of Unicode represents character A. Hence, the output is A.

 

Example 4: Type casting data type from char to int

class Main {

    public static void main(String[] args) {

        char x = 'A';

        System.out.println((int) x);

    }

}

 

Output

65

 

3. Type Conversion using Methods

3.1 Converting any Primitive Type to String

Any data type can be converted to String using the string method valueOf() We will learn more String Methods later in the course.

class Main {

    public static void main(String[] args){

        int num = 2;

        float floatNum = 2.34f;

        char ch = 'a';

 

        String str1 = String.valueOf(num);

        String str2 = String.valueOf(floatNum);

        String str3 = String.valueOf(ch);

 

        System.out.println(num);

        System.out.println(floatNum);

        System.out.println(ch);

    }

}

 

Here, we are calling the method valueOf() of the class String to convert from any primitive data type to String

Output

2

2.34

a

 

3.2 Converting String to int

We can convert String to int in Java using Integer.parseInt() method.

class Main {

    public static void main(String[] args) {

        String str = "21";

        int num = Integer.parseInt(str);

 

        System.out.println(num);

    }

}

 

Output

21

Here, we are calling the method parseInt() of the wrapper class Integer to convert from String to int We will learn about Wrapper Classes later in the course.

 

3.3 Converting char to int

We can convert char to int in Java using Character.getNumericValue() method.

class Main {

    public static void main(String[] args) {

        char ch = '3';

        int num = Character.getNumericValue(ch);

 

        System.out.println(num);

    }

}

 

Output

3

Here, we are calling the method getNumericValue() of the wrapper class Character to convert from char to int

 

3.4 Converting int to char

We can convert int to char in Java using Character.forDigit() method. It accepts two arguments,

  • int value, that is being converted

  • base value

The base value is the number of unique digits, including the digit zero, used to represent numbers. For decimal system, the base value is 10.

class Main {

    public static void main(String[] args) {

        int num = 3;

        char ch = Character.forDigit(num, 10);

 

        System.out.println(ch);

    }

}

 

Output

3

Conclusion

  • The getClass().getSimpleName() method is used to check the data type of a variable or value.

  • For primitive data types, to check their data type, we need to cast them into objects,

    • ((Object) primitiveValue) Type Conversion is of two types:

    • Implicit Type Conversion: Java compiler automatically converts one data type to another data type.

  • Explicit Type Conversion: Programmers change the data type of an object to the desired data type