×

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 Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

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

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

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

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.