Data Types in Java
In Java, a data type specifies what kind of data a variable can hold. Data types are important because they define the size and layout of the variable’s memory, the range of values that can be stored, and the set of operations that can be applied to the variable.
1- Primitive Data Types: Built-in data types provided by the language.
2- Reference Data Types: Objects and arrays.
Basic Example of a variable with data type:
Commonly Used Data Types Example:
Data Type | What It Holds | Example | Precision |
---|---|---|---|
int | Whole numbers (no decimals) |
int weight1 = 55; // Valid: Assigning an integer value directly int weight2 = 55.5; // Invalid: Attempting to assign a decimal value to an integer |
N/A (Integer) |
float | It only gives output with 7-digit numbers with a decimal point or less than 7 if the number of digits is 7 it will round the last number otherwise not |
float Amount = 46.12345678910111213141516171819f; the output will be – 46.12346 float Amount = 46.1234f; the output will be – 46.1234 |
7 digits |
double | It only gives output with 15-digit numbers with a decimal point or less than 15 |
double Amount = 46.12345678910111213141516171819; the output will be – 46.1234567891011 double Amount = 46.1234567891; the output will be – 46.1234567891 |
15 digits |
char | A single character (like a letter) |
char grade1 = ‘A’; // Valid: Single character enclosed in single quotes char grade2 = ‘A+’; // Invalid: Attempting to assign more than one character |
1 character |
string | A sequence of characters (like words) |
string name1 = “Emily”; // Valid: String enclosed in double quotes string name2 = Emily; // Invalid: Missing double quotes for string literal |
N/A (Depends on string length) |
bool | True or false values. It cannot take any other value beside true or false |
bool isValid1 = true; // Valid: Assigned the Boolean value ‘true’ bool isValid2 = 23; // Invalid: Attempting to assign an integer value |
1bit (True/False) |
Question:
Write a Java program that declares the following variables with appropriate data types:
- An integer variable age with the value 25.
- A floating-point variable price with the value 12.75.
- A double variable largeAmount with the value 123456789.1234567.
- A character variable initial with the value ‘D’.
- A string variable name with the value “John”.
- A boolean variable isStudent with the value false.
Print each variable on a new line in the output as you can see in image.