Numeric Data Types | Heaton Research

Numeric Data Types

Get the entire book!
Java for the Beginning Programmer

Numeric data types are used to hold numbers. Within the numeric data types there are two subgroups:

  • Integer Data Types
  • Floating Point Data Types

Integer data types cannot have decimal places. If you try to assign a number, with decimal places, to an integer data type, the decimal places will drop off, no rounding will occur. Floating point data types can hold decimal places.

Java defines two integer data types: int and long. The only difference between int and long are the size of numbers they can hold. Usually you will use int, unless you need to hold a really large number. The sizes of all data types are summarized later in this section.

Java defines two floating point data types: float and double. The only difference between float and double are the size of numbers they can hold. Usually you will use double, as it can be handled most efficiently by Java. The sizes of all data types are summarized later in this section.

The following code block defines an int and assigned a value of 10 to the int.

int i;
i = 10;

The above code demonstrates how a variable of any data type can be defined. First, the data type, in this case int is specified. Secondly, the name of the variable, in this case “i” is specified. Finally, a semicolon ends the line. The above two lines can also be combined as follows:

int i = 10;

To print out a numeric data type use the println method, as follows:

System.out.println("The value of i is " + i );

Mathematical operations can easily be performed on numerical data types. The symbols + and - are used to add and subtract. The symbols / and * are used to multiply and divide. For example, to add five to ”i” you would use the following code.

i = i + 1;

There are also two shortcut operators ++ and - - that both add and subtract one. For example, to increase “i” by one use the following code:

i++;

The shortcuts += and -= can also be used to add and subtract a number from a variable. For example, to increase “i” by five use the following code.

i+=5;
Copyright 2005-2008 by Heaton Research, Inc.