×

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

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

Advanced Java skills

These were some of the contemporary talents that a Java developer should master in efforts to progress in the era of science in 2022. A database such as MySQL, a...

4 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.