New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Java› Variables and Data Types

Variables and Data Types

💻 Java

Store numbers, text and truth values with the right Java types.

Lesson 2 of 9 Tutorial
0 of 9 completed

Java requires every variable to have a type. This catches mistakes at compile time instead of at runtime.

By the end of this lesson you can:
  • 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 fraction

Constants

Use final for values that must not change. Name constants in uppercase with underscores.

final double VAT_RATE = 0.075;
Warning Use BigDecimal for money. double cannot represent 0.10 exactly, which causes rounding errors in totals.

Practice

  1. Declare variables for a student name, age and average score.
  2. Convert an int to a double and back.
  3. 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

Exercise 1. Student profile Easy
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.
Java exercise-1.java
Expected Output
Name: Bola Ade
Age: 15
Average: 78.5

Lesson Nav

Lesson sections