Academic Java    Java Tutorial  >  Basics  >  primitive types

primitive types Example

This program shows the use of each of the eight primitive types: int byte short long float double char boolean. Each type defines a range of values.

The primitives, apart from boolean, are numeric types. That is they can be used in arithmetic expressions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class PrimitiveTypesExample {

   public static void main(String[] args) {

      int i = 16;

      byte bt = 123;

      short s = 77;

      long l = 12345L;

      float f = 1.48F;

      double d = 2.7e-123;

      char c = 'h';

      boolean b = true;

   }

}

5 Each of the initialization statements in this program are similar to this one.
To the left of the = is a type (such as int) followed by a variable name. On the right before the semicolon is a literal value, that is, the value itself.
The variable is of the type specified. The literal values (apart from 123 and 77 which are int) are also of the specified type.
An int holds an integer in 32 bits and is in the range -231-1 to 231.
That is -2,147,483,648 to 2,147,483,647.

7 A byte holds an integer in 8 bits and is in the range -128 to 127.
The literal value 123 is, by default, an int.

9 A short holds an integer in 16 bits and is in the range -32768 to 32767.
The literal value 77 is, by default, an int.

11 A long holds an integer in 64 bits and is in the range -263-1 to 263. That is a number in the approximate range +-1018.
Numbers such as 12345 are treated as int by default. To enforce such a number to be a long the number must be followed by L.

13 A float holds a single-precision floating point value in 32 bits in the range +-1.45E-45 to +-3.4028235E+38.
Values, such as 1.48, are treated as double by default. To enforce a number to be a float the number must be followed by f or F.

15 A double holds a double-precision floating point value in 64 bits.
That is a number in the range +-4.9E-324 to +-1.7976931348623157E+308.

17 A char represents a Unicode character in 16 bits.
This includes all the alphabetic and numeric characters, and many more.

19 A boolean is a truth value held in one bit and holds one of two values: true or false.