Variables & Data Types
Variables are containers that store data in your program. Java is a strongly-typed language, which means every variable must have a specific data type. Let's learn how to create and use variables. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
40 min•By Priygop Team•Last updated: Feb 2026
What is a Variable?
A variable is like a labeled box that holds a value. You give it a name, specify what type of data it can hold, and then store your data in it. In Java, you must declare the type before using a variable — this helps catch errors early.
Java Data Types
- int — Whole numbers like 1, 42, -100 (most common for counting)
- double — Decimal numbers like 3.14, 99.99 (for precise calculations)
- boolean — true or false (for yes/no decisions)
- char — A single character like 'A', 'z', '9' (always in single quotes)
- String — Text like "Hello" (always in double quotes — note: String is a class, not primitive)
- long — Very large whole numbers (when int isn't big enough)
- float — Decimal numbers with less precision than double (rarely used)
- byte — Small numbers from -128 to 127 (saves memory)
Declaring and Using Variables
Example
public class Variables {
public static void main(String[] args) {
// Declaring variables with different data types
String name = "Alice"; // Text
int age = 25; // Whole number
double salary = 50000.50; // Decimal number
boolean isStudent = true; // True or false
char grade = 'A'; // Single character
// Printing variables
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Student: " + isStudent);
System.out.println("Grade: " + grade);
// You can change variable values
age = 26;
System.out.println("Next year age: " + age);
}
}Try It Yourself: Create Variables
Try It Yourself: Create VariablesJava
Java Editor
✓ ValidTab = 2 spaces
Java|16 lines|530 chars|✓ Valid syntax
UTF-8
Constants with final
Example
public class Constants {
public static void main(String[] args) {
// Use 'final' to make a variable constant (unchangeable)
final double PI = 3.14159;
final String SCHOOL = "Priygop Academy";
System.out.println("PI value: " + PI);
System.out.println("School: " + SCHOOL);
// PI = 3.14; // ERROR! Cannot change a final variable
}
}