13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.2 Fundamental Language Elements533.2.1 Scalar TypesJava has a number of built-in scalar (in this c<strong>on</strong>text, n<strong>on</strong>object) types. Wediscuss these below.3.2.1.1 Integer TypesJava defines four integer types—byte, short, int, and l<strong>on</strong>g. Unlike somelanguages, Java defines the precisi<strong>on</strong>, that is, the bit size, of these types.• byte: 8 bits• short: 16 bits• int: 32 bits• l<strong>on</strong>g: 64 bitsFor Java, the goal is “compile <strong>on</strong>ce, run anywhere.” Defining that intmeans 32 bits—everywhere—helps to achieve this goal. By c<strong>on</strong>trast, when Clanguage was first defined, its goal was different: to be available quickly <strong>on</strong> avariety of architectures, not to produce object code that would be portable betweenarchitectures. Thus, for C, the choice was up to the compiler developerto choose a size that was most “natural” (i.e., c<strong>on</strong>venient) for that particulararchitecture. 2 This would make it easiest <strong>on</strong> the compiler writer. Itsucceeded—C was an easy language to implement, and it spread widely.Back to Java. Note that all these values are signed. Java has no“unsigned” type.Note also that byte is listed here. It can be treated as a numeric value, andcalculati<strong>on</strong>s performed <strong>on</strong> it. Note especially that it is a signed number (i.e.,values range from –128 to 127 and not from 0 to 255). Be careful when promotinga byte to an int (or other numeric value). Java will sign-extend <strong>on</strong> thepromoti<strong>on</strong>. If the value in the byte variable was a character (e.g., an ASCIIvalue) then you really wanted it treated like an unsigned value. To assign sucha value to an int you’ll need to mask off the upper bits, as in Example 3.1.You may never encounter such a situati<strong>on</strong>, but if you are ever workingwith bytes (e.g., byte arrays) and start to mess with the individual bytes, d<strong>on</strong>’tsay we didn’t warn you.2. In fact, C’s <strong>on</strong>ly rule is that a short int will not be l<strong>on</strong>ger than an int and a l<strong>on</strong>g willnot be shorter than an int. It is both ANSI and K&R compatible for all integer types in a Ccompiler to be the same size!

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!