Tuesday, March 27, 2007

Narrowing Primitive Conversions

Introduction

You have to cast explicitly from a type with more bits to a type with fewer bits.

Converting Primitive Types by Explicit Cast
From type To type Example
int byte byte b; int i; i = 20; b = (byte) i; // b = 20
double int int i; double d = 22.18; i = (int) d; // i = 22
float int int i; float f = 34.92f; i = (int) f; // f = 34

Program

public class Main {
    public static void main(String[] args) {
        int i = 20; 
        byte b = (byte) i; // explicit cast
        System.out.println(b);
    }    
}

Output

20

No comments: