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
  • PrintPrint
Share this Page URL
Help

3. Primitives and References: Know Your ... > You really don’t want to spill that....

You really don’t want to spill that...

Be sure the value can fit into the variable.

image with no caption

You can’t put a large value into a small cup.

Well, OK, you can, but you’ll lose some. You’ll get, as we say, spillage. The compiler tries to help prevent this if it can tell from your code that something’s not going to fit in the container (variable/cup) you’re using.

For example, you can’t pour an int-full of stuff into a byte-sized container, as follows:

int x = 24;
byte b = x;
//won't work!!

Why doesn’t this work, you ask? After all, the value of x is 24, and 24 is definitely small enough to fit into a byte. You know that, and we know that, but all the compiler cares about is that you’re trying to put a big thing into a small thing, and there’s the possibility of spilling. Don’t expect the compiler to know what the value of x is, even if you happen to be able to see it literally in your code.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

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

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint