Variables and Data Types
💻 JavaStore numbers, text and truth values with the right Java types.
Java requires every variable to have a type. This catches mistakes at compile time instead of at runtime.
- Declare primitive and reference variables.
- Convert between types.
- Use constants.
Primitive Types
Java has eight primitives. The most common are int, double, boolean and char.
int age = 16;
double price = 2500.50;
boolean isStudent = true;
char grade = 'A';Text with String
String is a reference type, not a primitive. Strings are immutable: methods return a new string rather than changing the old one.
String name = "Amina";
String greeting = "Hello, " + name;
System.out.println(greeting.length());
System.out.println(name.toUpperCase());Casting
Widening conversions happen automatically. Narrowing needs an explicit cast and can lose data.
int whole = 10;
double decimal = whole; // automatic
int back = (int) 10.75; // 10, loses the fractionConstants
Use final for values that must not change. Name constants in uppercase with underscores.
final double VAT_RATE = 0.075;Practice
- Declare variables for a student name, age and average score.
- Convert an int to a double and back.
- Declare a constant for the number of weeks in a term.
Hands-on exercise
Write a class StudentProfile that:
1. Stores a name, age and average score.
2. Prints each on its own line.
3. Prints the score rounded to one decimal place with String.format.
Recap
Java types are explicit. Strings are immutable and BigDecimal is the right choice for money.
Example
int age = 16;
double price = 2500.50;
boolean isStudent = true;
char grade = 'A';
Exercises
1. Stores a name, age and average score.
2. Prints each on its own line.
3. Prints the score rounded to one decimal place with String.format.
Expected Output
Name: Bola Ade
Age: 15
Average: 78.5
Lesson Nav
Java Course
0/9 lessons completed
- 1 Getting Started with Java Tutorial
- 2 Variables and Data Types Tutorial
- 3 Conditions and Loops Tutorial
- 4 Methods and Parameters Tutorial
- 5 Arrays and ArrayLists Tutorial
- 6 Classes and Objects Tutorial
- 7 Inheritance, Interfaces and Polymorphism Tutorial
- 8 Exceptions and Files Tutorial
- 9 Project: A Console Grade Book Project