简体   繁体   中英

Type Casting doesn't work for my variable

Hello I am fairly new to java. I really struggle to solve this error and I can't finde anything on the inte.net: if I do: long test = (long) (2147483647 + 1); it sets test to an int even though I used long. why?

I tryed it using max int value but still it doesn't worked. long test = (long) (Integer.MAX_VALUE + 1);

cast then add

long test = (long) (2147483647) + 1;
System.out.println(test);

2147483648

Otherwise you are adding two ints then casting

long test = (long) (2147483647+ 1);

Let's analyze it.

Java evaluates the expression in specific order. Addition is evaluated first on right side expression. As you have not defined the data type for "2147483647" explicitly, java saves it as integer implicitly. same for 1. Now since you are adding int data type variables, so result is int. ie -1.

Problem here is that java implicitly calculates the datatype.

Solution in such case where you know we need bigger datatype. Please explicitly inform java about it.

In this case we can easy do it by a small change as below:-

long test = (long) (2147483647 L + 1);

Even you don't need long casting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM