Header Ads

  • Breaking Now

    Explain Java Type Conversion and Casting?

    The converting of one datatype to another type is called type casting.Java type conversions occur automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign: byte -> short -> int -> long -> float -> double The -> symbol used here should be interpreted as "to a".
    long testLongValue;
    int testIntegerValue;
    testLongValue =testIntegerValue; //automatic promotion of int to long value.
    Explicit Conversion:
    The example given above will not work other way round.We can not automatically convert a long value into an integer value automatically as long value requires more storage than integer value and this may result in loss of data.
    Such kind of conversion can be forced and compiler will understand that only when it is done explicitly.
    int testValFromLongToInt = (int)testLongValue;

    Post Top Ad

    Post Bottom Ad