Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Casting Primitive Values

Greenhorn
Posts: 4
Short y= (short)1921222; // stored as 20678

To the above code, the explanation is as follows: the value 1921222 is too large to be stored as short, so numeric overflow occurs and it becomes 20678.

why 20678? why not other other value ?

Bartender
Posts: 1639
233
• 1
When an int is converted to a short all but the lowest 16 bits are discarded.

Decimal      Hex                   Binary
1921222   001D50C6   0000000000111010101000011000110
20678       50C6                  0101000011000110

Ranch Hand
Posts: 175
17
Overflows and underflows are cyclic, for example, since the byte range is between -128 and +127,

A value of +128 overflows by 1, so you’ll get -128 + 0 = -128

A value of +129 overflows by 2, so you’ll get -128 + 1 = -127
A value of +130 overflows by 3, so you’ll get -128 + 2 = -126
A value of +131 overflows by 4, so you’ll get -128 + 3 = -125

Ron McLeod
Bartender
Posts: 1639
233
Both Short y= (short)1921222 and byte x = (byte)128 are examples of narrowing primitive conversion, not overflows.

krish keerthi
Greenhorn
Posts: 4
I got it ! Thank you guys

Joe Bishara
Ranch Hand
Posts: 175
17

Ron McLeod wrote:Both Short y= (short)1921222 and byte x = (byte)128 are examples of narrowing primitive conversion, not overflows.

Overflows and underflows occur when we exceed the upper limit or lower limit of a primitive datatype.

In the previous example, an overflow occurs because the upper limit of the short datatype is 32767 but we are assigning a value of 1921222. We use a cast to force the assignment i.e. we use a cast to ensure that the compiler doesn't complain when the overflow occurs.

 For my next feat, I will require a volunteer from the audience! Perhaps this tiny ad? The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS