Java BasicsCore· 30 min read

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.

TypeHoldsExample value
intA whole number25
doubleA number with decimals19.99
booleanTrue or falsetrue
StringText (in double quotes)"Asha"

Declaring variables

You write the type, then a name, then = and the value. Here is a small profile:

Four common variable types
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

  • String starts 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?

Answer: Prices have decimals, so double is correct. int only holds whole numbers, and a price is a number, not text or true/false.

✍️ Practice

  1. Create variables for a book: a String title, an int number of pages, and a double price. Print them in one sentence.
  2. Make a boolean called isAvailable and print it.

🏠 Homework

  1. Create a small profile of yourself using one variable of each type (int, double, boolean, String) and print a tidy summary.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →