Java is a statically typed language, which means that every variable or expression has a specific data type. In this section, we will explain each Java data type with an example in detail.
- byte: The byte data type is an 8-bit signed integer that can represent values from -128 to 127. It is often used to save memory in large arrays, where the memory savings actually matters. Here is an example:
byte b = 100;
- short: The short data type is a 16-bit signed integer that can represent values from -32,768 to 32,767. It is often used when memory is not a critical issue, but range is. Here is an example:
short s = 30000;
- int: The int data type is a 32-bit signed integer that can represent values from -2,147,483,648 to 2,147,483,647. It is the most commonly used data type for representing whole numbers in Java. Here is an example:
int i = 2147483647;
- long: The long data type is a 64-bit signed integer that can represent values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It is used when you need a range of values that exceeds those provided by int. Here is an example:
long l = 9223372036854775807L;
Note that we need to append an ‘L’ at the end of the value to indicate that it is a long value.
- float: The float data type is a 32-bit single-precision floating-point number. It is used when you need to save memory in large arrays of floating-point numbers.
float myFloat = 3.14159f;
- double: The double data type is a 64-bit double-precision floating-point number. It is the default choice for decimal numbers in Java. It is used for general-purpose floating-point arithmetic.
double myDouble = 3.14159265359;
- boolean: The boolean data type has only two possible values: true and false. It is used for logical expressions and control statements.
boolean myBoolean = true;
- char: The char data type is a single 16-bit Unicode character. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive). It is used to store individual characters.
char myChar = 'A';