Data types are very important in Java because it is a strongly typed language. All operations are type-checked by the compiler for type compatibility. Strong type checking helps prevent errors. All variables, expressions, and values have a type.
Java contains two general categories of built-in data types:
- Object-oriented
- Primitive (non-object-oriented)
Object-oriented types are defined by classes (will be discussed later).
Primitive types are not objects in an object-oriented sense, but rather, normal binary values.
There are 8 primitive types.
Integers
Java defines four integer types which are byte, short, int, and long. All of the integer types are signed positive and negative values. Java does not support unsigned (positive-only) integers.
Type | Width in Bits | Range |
byte | 8 | –128 to 127 |
short | 16 | –32,768 to 32,767 |
int | 32 | –2,147,483,648 to 2,147,483,647 |
long | 64 | –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
1 2 3 4 5 6 7 8 9 10 11 |
public class RectangleSquare { public static void main(String[] args) { int a = 10; int b = 20; int c; c = a * b; System.out.println("Rectangle square is " + c); } } |
Floating-Point
The floating-point types represents numbers that have fractional part.
There are 2 floating types – float and double.
Type | Width in Bits | Precision |
Float | 32 | single-precision numbers |
Double | 64 | double-precision numbers |
1 2 3 4 5 6 7 8 9 |
public class FloatExample { public static void main(String[] args) { double distance; distance = 10.5 * 200.5; System.out.println("Distance is " + distance); } } |
Characters
In Java characters use Unicode.
Type | Width in Bits | Range |
Characters | Unsigned 16 | 0 to 65,536 |
Since char is an unsigned 16-bit type, character variables can be handled like integers and it is possible to perform various arithmetic manipulations on a char variable.
1 2 3 4 5 6 7 8 9 10 11 |
public class CharExample { public static void main(String[] args) { char ch = 'A'; System.out.println("ch is " + ch); // Increment ch ch++; System.out.println("ch now is " + ch); } } |
The Boolean Type
The boolean type represents true/false values. Java defines the values true and false using the reserved words true and false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class BooleanExample { public static void main(String args[]) { boolean b; b = false; System.out.println("b is " + b); b = true; System.out.println("b is " + b); // a boolean value can control the if statement if (b) System.out.println("This is executed."); b = false; if (b) System.out.println("This is not executed."); // Outcome of a relational operator is a boolean value System.out.println("5 < 10 is " + (5 < 10)); } } |