Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

type
casting
java
datatype

Typecasting in Java

Educative Answers Team

Typecasting is used to temporarily change the data type of a value. There are two types of data in Java:

  1. Primitive data types
  2. Non-primitive data types

Java supports widening casting and narrowing casting.

svg viewer

Widening casting

Widening casting changes a smaller data type to a larger data type. For example, byteshortcharintlongfloatdouble.

This type of casting is usually automatic; you do not need to use().

Narrowing casting

Narrowing casting changes the data type from a larger data type to a smaller data type. For example, doublefloatlongintcharshortbyte.

Code

Widening casting

class myClass {
    public static void main( String args[] ) {
    int number = 7;
    double doubleNumber = number; // Widening casting: int to double

    System.out.println(number);         // 7
    System.out.println(doubleNumber);   // 7.0
    }
}

Narrowing casting code

class myClass {
    public static void main( String args[] ) {
    double number = 7.3;
    int intNumber = (int) number; // Narrowing casting: int to double

    System.out.println(number);      // 7.3
    System.out.println(intNumber);   // 7
  }
}

RELATED TAGS

type
casting
java
datatype
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring