15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

148<br />

Using Different Data Types<br />

Using Different Data Types<br />

Defining a specific data type makes it easy to<br />

✦ Know the type of data a variable can hold (either numbers or text).<br />

✦ Restrict the range of data the variable can hold.<br />

✦ Identify whether a variable can hold a number or text can keep your<br />

program from trying to add or multiply a number by a word, which<br />

doesn’t work. Figure 2-3 shows the different categories of data types<br />

within most <strong>programming</strong> languages.<br />

Common Programming Data Types<br />

Data Types<br />

Figure 2-3:<br />

Different<br />

data types<br />

that can<br />

hold a range<br />

of values.<br />

Boolean<br />

(0 or 1)<br />

Integer<br />

(Whole numbers)<br />

Byte<br />

(0–255)<br />

Integer<br />

(-32,768–<br />

32,767)<br />

Long<br />

(-2.147e9–<br />

2.127e9)<br />

Numbers<br />

Real<br />

(Decimal numbers)<br />

Single<br />

(-3.403e38–<br />

2.147e9)<br />

Double<br />

(-1.798e308–<br />

1.798e308<br />

Character<br />

(1 character)<br />

Text<br />

String<br />

(0 to 2 billion characters<br />

Defining the range of data can prevent a variable from storing incorrect data.<br />

For example, if your program asks the user to type in his age, invalid data<br />

would include negative numbers, zero, and extremely large numbers, such<br />

as 259.<br />

The range of numbers listed <strong>for</strong> Long, Single, and Double data types are<br />

listed as exponential numbers (that’s the little e). So the Long data type can<br />

store a number as large as 2.147 with the decimal place moved nine places to<br />

the right or approximately 2,147,000,000.<br />

Every <strong>programming</strong> language offers different data types, so use Figure 2-3 as<br />

a guideline rather than a strict reference.<br />

For example, if you want to store a person’s age in a variable, you probably<br />

want to store it as a whole number (such as 45) rather than a real number<br />

(such as 45.029).<br />

Next, you want to choose a data type that contains the range of values a<br />

person’s age might be. From Figure 2-3, you can see that a Boolean data

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

Saved successfully!

Ooh no, something went wrong!