Home » Java programming language

Typecasting in Java

Java typecasting: Here, we are going to learn about the typecasting in java – how a type converts to another type?
Submitted by Preeti Jain, on July 01, 2019

Typecasting

  • Typecasting is a term which is introduced in all the language similar to java.
  • When we assign primitive datatype to another datatype.
  • In java Typecasting is of two types:
    1. Widening Typecasting
    2. Narrowing Typecasting

We will study both typecasting with examples...

a) Widening Typecasting

  • When we convert a smaller size datatype to the larger size datatype.
  • In this typecasting no data loss is there.
  • It is done by the compiler (i.e automatic). It is not done by the user.
  • Hierarchy of widening typecasting is described below:
    byte → short → char → int → long → float → double

Example of Widening Typecasting

public class WideningTypecast {
    public static void main(String[] args) {
        int num1;
        byte num2 = 20;

        // We are assigning smaller datatype 
        // byte to larger datatype 
        num1 = num2;

        // Print the output 
        System.out.println("The value of num1 is :" + num1);
    }

}

Output

D:\Programs>javac WideningTypecast.java

D:\Programs>java WideningTypecast
The value of num1 is :20

b) Narrowing Typecasting

  • When we convert a larger size datatype to the smaller size datatype.
  • In this typecasting data loss is there.
  • It is not done by the compiler (i.e manually). It is done by the user.
  • Hierarchy of narrowing typecasting is described below:
    double → float → long → int → char → short → byte

Example of Narrowing Typecasting

public class NarrowingTypecast {
    public static void main(String[] args) {
        int num1;
        double num2 = 20.8;

        // We are assigning larger size datatype 
        // long to smaller size datatype 
        num1 = (int) num2;

        // Print the output 
        System.out.println("The value of num1 is :" + num1);
    }
}    

Output

D:\Programs>javac NarrowingTypecast.java

D:\Programs>java NarrowingTypecast
The value of num1 is :20





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.