×

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer handles the manual conversion. With appropriate examples, we will discuss type casting in this section.

Type casting is divided into the following types. They are

  • Widening Type Casting
  • Narrowing Type Casting

Widening Type Casting

Widening type casting refers to the transformation of a lower data type into a higher one. Casting down and implicit conversion are other names for it. It happens on its own. It is secure because there is no possibility of data loss. The event occurs when:

  • It is necessary for both data types to be compatible.
  • The target type must be larger than the source type.

Byteà short à char à int àlong àfloatà double  

There is no automatic conversion from a numeric data type to a char or boolean data type. Additionally, the data types char and boolean are incompatible with one another.

Consider the following example.

TypeCast.java

import java.io.*;
import java.util.*;
class TypeCast
{  
    public static void main(String[] args)  
    {  
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the value of n");
        int a = sc.nextInt();  
        //converts the integer  into long   
        long b = a;  
        //converts the long  into float   
        float c = b;  
        System.out.println("Before conversion, a= "+a);  
        System.out.println("After conversion, b= "+b);  
        System.out.println("After conversion, c= "+c);     
    }     
}  

Output:

Java Type Casting

TypeCast1.java

import java.io.*;
import java.util.*;
class TypeCast1 {
   public static void main(String args[]){
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter an character value: ");
      char n = scan.next().charAt(0);
      int c =  n;
      System.out.println("converted integer value of the character is: "+c);
   }
}

Output:

Java Type Casting

Narrowing Type casting

Narrowing type casting in Java refers to the conversion of a higher prioritized data type to the lower one. In this type, type casting is not done directly. It is done explicitly with the help of the cast operator.

The order of type casting is as follows,

Doubleà floatàlongàintàcharàshortàbyte

Example program:

Conversion of int to char

TypeCast2. java

import java.io.*;
import java.util.Scanner;
class TypeCast2 {
   public static void main(String args[]){
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter an integer value: ");
      int n = scan.nextInt();
      char c = (char) n;
      System.out.println("converted charater value of the integer is: "+c);
   }
}

Output:

Java Type Casting

Conversion of char to byte

TypeCast3.java

import java.io.*;
import java.util.*;
class TypeCast3 {
   public static void main(String args[]){
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a Character value: ");
      char n = scan.next().charAt(0);
      byte c = (byte) n;
      System.out.println("converted byte value of the character is: "+c);
   }
}

Output:

Java Type Casting

Conversion of double to byte:

TypeCast4. java

import java.io.*;
import java.util.*;
class TypeCast4 {
   public static void main(String args[]){
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a Character value: ");
      double n = scan.nextDouble();
      char c = (char) n;
      System.out.println("converted byte value of the character is: "+c);
   }
}

Output:

Java Type Casting

Related Topics

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.