Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

Casting primitives

image with no caption

In Chapter 3 we talked about the sizes of the various primitives, and how you can’t shove a big thing directly into a small thing:

long y = 42;
int x = y;     // won't compile

A long is bigger than an int and the compiler can’t be sure where that long has been. It might have been out drinking with the other longs, and taking on really big values. To force the compiler to jam the value of a bigger primitive variable into a smaller one, you can use the cast operator. It looks like this:

long y = 42;          // so far so good
int x = (int) y;      // x = 42 cool!

Putting in the cast tells the compiler to take the value of y, chop it down to int size, and set x equal to whatever is left. If the value of y was bigger than the maximum value of x, then what’s left will be a weird (but calculable[5]) number:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial