Context & conversion

Assignment context

conversion and context

Indentitiy conversion

void main(){
    System.out.println("Conversion & Contexts");

    boolean flag = true;
    int x = 10;
    long y = 20;
    float f = 2.5f;
    double d = 3.2;
    double d2 = 2d;
    char c = 'a';
    String str = "abc";

    // The Following are identity conversions
    byte b = 5; // byte <= int
    short s = 10; // short <= int
    char c2 = 25; // char <= int
    long l = 5; // long <= int
    float f2 = 2; // float <= int
    double d3 = 3; // double <= int
    float f3 = 2l; //float <= long
    double d4 = 'a'; // double <= char
    Object o = "dep"; // object <= str
    String str2 = null; // String <= null 
}

Widening primitive Conversion

related on numeric data types only (byte, short, int, long, float, double, char)

image.png

Widening conversions (e.g., byte to short or int to long) are safe as the destination type can hold all values of the source. However, converting a long (64-bit) to a float (32-bit) can lead to precision loss because float uses the IEEE 754 format, which stores numbers in scientific notation with limited precision. This may result in rounding or truncation of the less significant digits when large numbers are converted.

image.png

void main(){
    byte b = 10; // (byte <= int) Narrowing primitive conversion

    //Widening primitive conversion
    short s = b; // short <= byte
    int i = b; // int <= byte
    long l = b; // long <= byte
    float f = b; // float <= byte
    double d = b; // double <= byte
    l = i; // long <= int
    d = f; // double <= float
    i = 'c'; // int <= char
    f = 'c'; // float <= char

    //char c = b;
    //char c = s;

    int i2 = 555544552;
    float f2 = i2;
    double d2 = i2;
    System.out.println(f2);
    System.out.println(d2);

}

Narrowing primitive conversion

image.png

void main(){
    
    byte b = 10; // byte <= int Narrowing primitive conversion
    short s = b; // short <= byte Narrowing primitive conversion
    char c = 10; // char <= int Narrowing primitive conversion
    byte b2 = -129+1; // byte <= int Narrowing primitive conversion
    //char c2 = -10; // char <= int cant assign negative values inside of a char
    float f = 25f; // float <== float identity conversion
    //char c3 = s;  // char <= short //cant do narrowing primitive conversion due to s isn't compile time constant 
}

Widening and Narrowing Primitive Conversion ( byte to char )

image.png

1000041032.jpg

Widening Reference Conversion

image.png