Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting Primitive Values  RSS feed

 
krish keerthi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?


Thanks in advance
 
Ron McLeod
Saloon Keeper
Posts: 1600
232
Android Angular Framework Eclipse IDE Java Linux MySQL Database Redhat TypeScript
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Joe Bishara
Ranch Hand
Posts: 175
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Saloon Keeper
Posts: 1600
232
Android Angular Framework Eclipse IDE Java Linux MySQL Database Redhat TypeScript
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both Short y= (short)1921222 and byte x = (byte)128 are examples of narrowing primitive conversion, not overflows.
 
krish keerthi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it ! Thank you guys
 
Joe Bishara
Ranch Hand
Posts: 175
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!