04Java Data Types
04Java Data Types
In this tutorial, we will learn about all 8 primitive data types in Java with the
help of examples.
int speed;
Here, speed is a variable, and the data type of the variable is int .
The int data type determines that the speed variable can only contain
integers.
There are 8 data types predefined in Java, known as primitive data types.
Note: In addition to primitive data types, there are also referenced types
(object type).
• The boolean data type has two possible values, either true or false .
2. byte type
• The byte data type can have values from -128 to 127 (8-bit signed two's
complement integer).
• If it's certain that the value of a variable will be within -128 to 127, then it is
used instead of int to save memory.
• Default value: 0
byte range;
range = 124;
System.out.println(range); // prints 124
}
}
Run Code
3. short type
• The short data type in Java can have values from -32768 to 32767 (16-bit
signed two's complement integer).
• If it's certain that the value of a variable will be within -32768 and 32767,
then it is used instead of other integer data types ( int , long ).
• Default value: 0
short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}
Run Code
4. int type
• The int data type can have values from -231 to 231-1 (32-bit signed two's
complement integer).
• If you are using Java 8 or later, you can use an unsigned 32-bit integer.
This will have a minimum value of 0 and a maximum value of 232-1. To
learn more, visit How to use the unsigned integer in java 8?
• Default value: 0
• The long data type can have values from -263 to 263-1 (64-bit signed two's
complement integer).
• If you are using Java 8 or later, you can use an unsigned 64-bit integer with
a minimum value of 0 and a maximum value of 264-1.
• Default value: 0
Notice, the use of L at the end of -42332200000 . This represents that it's an
integer of the long type.
6. double type
7. float type
Notice that we have used -42.3f instead of -42.3 in the above program. It's
because -42.3 is a double literal.
To tell the compiler to treat -42.3 as float rather than double , you need to
use f or F .
If you want to know about single-precision and double-precision, visit Java
single-precision and double-precision floating-point.
8. char type
class Main {
public static void main(String[] args) {
}
}
Run Code
String type
Java also provides support for character strings via java.lang.String class.
Strings in Java are not primitive types. Instead, they are objects. For
example,
Here, myString is an object of the String class. To learn more, visit Java
Strings.