int and double
- Java course
- Beginner
- Lesson 7/116
- 4 min
Learn numeric variables with int and double.
int and double
Java has two main types for numbers: int and double.
int holds 32-bit integers: between -2 billion and +2 billion. It does not allow decimals.
double holds 64-bit decimal numbers. The dot (.) separates the decimal part: 3.14.
int age = 25;
double height = 1.78;Which one you pick depends on the value: int for whole numbers, double for decimals.
double decimals
double holds numbers with a fractional part. The dot is the decimal separator. Scientific notation is supported: 1.5e3 = 1500.0.
double pi = 3.14;
double distance = 1.5e3;
System.out.println(pi);Dividing two doubles gives a decimal result: 7.0 / 2.0 = 3.5. But 7 / 2 (int division) = 3.
Avoid using double for money; rounding errors may occur. BigDecimal is safer for that.
Practice Define int and double and print them
Write a Main class with a main method. Assign 30 to int age and 1.75 to double height. Print both with println.
Sample solution
public class Main {
public static void main(String[] args) {
int age = 30;
double height = 1.75;
System.out.println(age);
System.out.println(height);
}
}Expected output
30 1.75
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is an int value?
- 42 Correct answer
- 3.14
- "number"
- true
Explanation: 42 is an integer and is written as an int.
2 Assign a value to an int variable
int age = ____;
int age = 25;
Explanation: An int is assigned without quotes.
3 Match the types
| Term | Meaning |
|---|---|
int |
Integer |
double |
Decimal |
42 |
Int literal |
3.14 |
Double literal |