Variables & Types
A variable is a labelled box that stores a value — and in Java every box has a type.
What you will learn
- Create variables of different types
- Choose between int, double, boolean and String
- Print variables together with text
A variable stores a value
A variable is a named place to keep a value so you can use it later. In Java you must say what type of value it holds. This is called being statically typed — the box knows what shape it is.
| Type | Holds | Example value |
|---|---|---|
int | A whole number | 25 |
double | A number with decimals | 19.99 |
boolean | True or false | true |
String | Text (in double quotes) | "Asha" |
Declaring variables
You write the type, then a name, then = and the value. Here is a small profile:
int age = 25;
double price = 19.99;
boolean isStudent = true;
String name = "Asha";
System.out.println(name + " is " + age + " years old.");
System.out.println("Student? " + isStudent);
System.out.println("Price: " + price);Note: Output:
Asha is 25 years old.
Student? true
Price: 19.99
The + sign joins (concatenates) text and values into one line. When a number meets text with +, Java turns the number into text automatically.
A few rules
Stringstarts with a capital S. The number types (int,double) are lowercase.- Text values go in double quotes
"like this". Single quotes are only for one character (char). - Variable names usually start lowercase and use camelCase:
firstName,isStudent. - You can change a variable later:
age = 26;(no type needed the second time).
Watch out: Types are strict. int age = 19.99; will NOT compile, because 19.99 is not a whole number. Use double for decimals.
Tip: If a value should never change, mark it final: final double PI = 3.14159;. Java then stops you from accidentally changing it later.
Q. Which type best stores a product price like 19.99?
double is correct. int only holds whole numbers, and a price is a number, not text or true/false.✍️ Practice
- Create variables for a book: a
Stringtitle, anintnumber of pages, and adoubleprice. Print them in one sentence. - Make a
booleancalledisAvailableand print it.
🏠 Homework
- Create a small profile of yourself using one variable of each type (int, double, boolean, String) and print a tidy summary.