06.09.2021 Views

Java with BlueJ, 2016a

Java with BlueJ, 2016a

Java with BlueJ, 2016a

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.

20 CHAPTER 2. BASICS<br />

memory that holds a value that a program can use and change as it executes.<br />

primitive types<br />

The <strong>Java</strong> programming language requires us to declare the type of data to be<br />

associated <strong>with</strong> a variable. <strong>Java</strong> makes a distinction between primitive data<br />

types and other data types defined via classes. In the <strong>Java</strong> class libraries<br />

there are many pre-defined classes, for example: String and System. The<br />

<strong>Java</strong> language contains eight primitive data types: byte, short, int, long,<br />

float, double, char and boolean:<br />

• byte, short, int, andlong are used for cases where the data is to be<br />

treated as whole numbers (numbers <strong>with</strong>out a fractional component).<br />

For example, 33, 498, -100 are whole numbers. These data types differ<br />

<strong>with</strong> regards to the magnitude of number they can represent.<br />

• float and double are used for cases where the data is numeric and<br />

where one expects values to have a fractional component such as:<br />

101.5, 26.334, -55.5. When written we show them <strong>with</strong> a decimal<br />

point. Again, these two types differ <strong>with</strong> regards to size in terms of<br />

the number of significant digits and in the magnitude of the number<br />

they can represent.<br />

• char is used when there are individual characters to be handled. Examples<br />

of individual characters are ’a’, ’b’, ’q’, ’$’. Values are<br />

enclosed in single quotes.<br />

• boolean is used when the situation requires one to work <strong>with</strong> logical<br />

values of true and false. In a <strong>Java</strong> program these values are written<br />

just as we do in English: true, false.<br />

A <strong>Java</strong> programmer declares a variable in a declaration statement, and then<br />

uses the variable name later in a program to assign a value, to alter the<br />

current value, and to reference the value currently stored. Two example<br />

programs follow; in Listing 2.1 the program defines and uses a variable, and<br />

in Listing 2.2 the program alters the value stored in a variable.<br />

In Listing 2.1 note the following:<br />

• In line 10 an int variable named i is declared,<br />

• In line 11 the value 14 is assigned to i (that is, the value 14 is stored<br />

in the memory location reserved for i),<br />

• Line 12 displays the value of i

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

Saved successfully!

Ooh no, something went wrong!