×

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

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 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.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.