Question:
What are the primitive data types in Java and give an example of each?
Answer:
- The primitive data types in Java are:
- byte
- short
- int
- long
- float
- double
- char
- boolean
Example of each primitive data type:
- byte:
byte myByte = 10;
- short:
short myShort = 1000;
- int:
int myInt = 100000;
- long:
long myLong = 1000000000L;
- float:
float myFloat = 3.14f;
- double:
double myDouble = 3.14159;
- char:
char myChar = 'a';
- boolean:
boolean myBoolean = true;
Explanation:
- Java provides several primitive data types to store single values. The byte, short, int, and long are used for whole numbers, float and double are used for floating-point numbers, char is used to store single characters, and boolean is used to store true or false values. Each data type occupies a different amount of memory and thus has a different range of values it can represent. In the provided examples, we assign values to variables of each data type using their respective syntax.