Title: Casting.java
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Casting.java


class Casting {
public static void main(String args[])
{
    double d1=1.0, d2=2.0;
    float  f1=1.0f, f2=2.0f;
    long   long1=1, long2=2;
    int    int1=1, int2=2;
    short  s1=1, s2=2;
    char   c1=1, c2=2;
    byte   b1=1, b2=2;

    // Automatic Casting occurs
    d1 = f1;
    f1 = long1;
    long1 = int1;
    int1 = s1;

    // Note that char conversion is a little different.
    // No automatic conversion without a caste
    s1 = (short)c1;
    c1 =(char)b1;

    // Need to tell the compiler that it is OK with a Caste
    b1 = (byte)c1;
    c1 = (char)s1;
    s1 =(short)int1;
    int1 = (int)long1;
    long1 = (long)f1;
    f1 = (float)d1;


// Since an arithmetic result is an int, we need to caste the result to store
// it into a short.

    s1 = (short)(s1 * s2);
    s1 = (short)(s1 / s1);
    s1++;

 // Since an arithmetic result is an int, we need to caste the result to store
// it into a byte.
    b1 = (byte)(b1* b2);
    b1++;

  // Since an arithmetic result is an int, we need to caste the result to store
// it into a char.
    c1 = (char)(c1 * c2);
    c1++;

 // Booleans act very different than numbers
 // The commented out lines are illegal in Java

     boolean bool1=false, bool2=true;

    // bool1 = bool1 * bool2;
    //! bool1++;

    // if (bool1 < bool2) System.out.println("Can't do");

    if (bool1 && bool1) System.out.println("Can do this");
  }
}


Last Updated: September 2, 2002 4:21 PM