Certain
basic data types are built in to Java. These are:
Type |
Description |
bytes |
Range of values |
boolean |
Boolean |
1 |
false, true |
byte |
integers, very small |
1 |
-128 to +127 |
short |
integers, small ones |
2 |
-32768 to +32768 |
int |
integer |
4 |
-2,147,483,648 to 2,147,483,647 |
long |
integer, very big ones |
8 |
+/-9.2*1018 |
float |
floating point number |
4 |
6 or 7 sig figs * 10 to +/- 38 |
double |
floating point number very accurate |
64 |
14 or 15 sig figs * 10 to +/- 38 |
char |
character |
4 |
Unicode character set |
We will initially use just
int
, later
char
,
boolean
and if needed
float
.
String
, which we will also use a lot is a class, not a
primitive type.
Declaring a variable of a primitive data type reserves the appropriate
storage in memory.
int count;
int height, width;
char yearLetter;
Assignment
(all primitive types)
This allows the assignment of a value to a variable
count = 0;
height = 12;
width = height + 10;
yearLetter = 'R';
Arithmetic (numeric types)
The four standard arithmetic operations of addition, subtraction,
multiplication and division are given by the operators
+
,
-
,
*
and
/
The modulus operator
%
gives the remainder of dividing an
integer by an other integer e.g.
29%5
gives 4.
A unary minus
-
can be used to negate a value e.g. if
count
holds 7 then
- count
gives -7.
Post-increment and post-decrement operators
++
and
--
increase and decrease a variable by 1. We will only use this operator
as a statement e.g. if
count
holds 7 then
count++;
is the same as
count = count + 1;
Comparison operators (all primitive types)
The values of primitive types may be compared using the following
operators; the result is always a boolean, either true or false.
operator |
comparison |
example |
== |
is equal to |
count==10 |
!= |
not equal to |
height!=width |
< |
less than |
height<width+10 |
<= |
less than or equal to |
height<=width+10 |
> |
greater than |
yearLetter>'L' |
>= |
greater than or equal to |
yearLetter>='L' |
Logical operators (boolean)
The boolean values and expressions are combined with the boolean
operators:
operator |
meaning |
example |
! |
not |
! ok |
&& |
and |
heightOk && widthOk |
|| |
or (inclusive) |
heightError || widthError |