-1

I don't understand why i should use {b=(byte) i} or {i =(int) d} this to conversion . Please can say me cordially why it happens in conversion. My sample code below.

public class Conversion {

    public static void main(String[] args) {
        byte b;
        int i = 257;
        double d = 323.142;
        System.out.println("\n Conversion int to byt");
        b = (byte) i;
        System.out.println("i and b "+i+ " after "+b);

        System.out.println("\n Conversion int to byt");
        i = (int) d;
        System.out.println("d and i "+d+ " after "+i);

    }

}
rckrd
  • 2,426
  • 1
  • 11
  • 18
Anjan
  • 62
  • 11

2 Answers2

0

You are doing "Widening Primitive Conversion" and "Narrowing Primitive Conversion".

https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.2 https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3

Lakatos Gyula
  • 3,529
  • 4
  • 28
  • 52
0

byte have range from -128 to 127 if you exceeds its limit you have to explicitly cast it to int the same way int have range and if it exceeds from its range you have to explicitly cast it

if we have value of byte in between the range of -128 to 127 there is no requirement of explicitly cast it to int

for more help i have follow link which will guide you

  1. Oracle description about primitive data type

  2. Why is the range of bytes -128 to 127 in Java?

  3. Chapter 5. Conversions and Promotions
Community
  • 1
  • 1
Nirav Prajapati
  • 2,828
  • 22
  • 32