Tuesday, March 27, 2007

Widening Primitive Conversion

Introduction

The widening primitive conversions are implicit casts, meaning that the programmer does not have to tell the compiler that a primitive type need to be converted. You can cast implicitly from a type with fewer bits to a type with more bits.

Note: char cannot be converted to short implicitly.

Converting Primitive Types by Implicit Cast
From type To type Example
byte int int i; byte b = 125; i = b; // i = 125
int double double d; int i = 512; d = i; // d = 512.0
int float float f; int i = 35; f = i; // f = 35.0

Program

public class Main {
    public static void main(String[] args) {
        byte b = (byte) 54; 
        short s = b;
        s = b; // implicit cast
        System.out.println(s);
    }    
}

Output

54

No comments: