Click here to Skip to main content
15,890,186 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a code for converting data types in Java.. I expect the code to through an error but it is not throwing.. The exception I expect is cannot be converted type exception at run time.. Here is the code..

class Abc {

    public static void main(String args[] ) throws Exception {

        try{
            short s = 24000;
            byte b = (byte) s;
            System.out.println(b);
        }

        catch(Exception e){
            System.out.println("Bad Conversion!");
            e.printStackTrace();
        }
    }
}


Is there any exception to prevent this type of conversion as byte cannot be initialized with value 24000 as it is its out of range.. What I am getting on my console is "-64"

What I have tried:

I tried to catch exception for type conversion in Java..
Posted
Updated 31-Jan-18 4:56am

1 solution

You are explicitly casting the value. This tells the compiler that you (hopefully) know what you are doing and omit any out of range checks. It will for your example just assign the lower byte of the short.

The value 24000 decimal is 5DC0 hex. The lower byte is C0 hex which is -64 decimal because byte is a signed type.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900