Java Variables and Data Types
A variable is a named box that stores a value your program can use and change.
Creating Variables
To create a variable, write its type, its name, an equals sign and a value:
Example
public class Main {
public static void main(String[] args) {
String name = "Ali";
int age = 19;
double fee = 3500.50;
System.out.println(name);
System.out.println(age);
System.out.println(fee);
}
}Ali 19 3500.5
You can change a variable later by giving it a new value:
Example
int marks = 70;
marks = 85; // marks is now 85Primitive Data Types
Java has eight basic (primitive) types. These are the ones you will use most:
| Type | Stores | Example |
|---|---|---|
int | Whole numbers | int students = 30; |
long | Very large whole numbers | long population = 20000000L; |
double | Decimal numbers | double price = 99.99; |
float | Decimal numbers, less precise | float rate = 2.5f; |
char | One character, in single quotes | char grade = 'A'; |
boolean | true or false | boolean passed = true; |
byte and short also exist for small whole numbers, but they are used less often.
The String Type
String holds text in double quotes. It is not a primitive type; it is a class, which is why it starts with a capital S. You will learn more in the Strings chapter.
Joining Text and Variables
Use + to join text and variables in one line:
Example
public class Main {
public static void main(String[] args) {
String student = "Ayesha";
int marks = 92;
char grade = 'A';
boolean passed = true;
System.out.println(student + " got " + marks + " marks");
System.out.println("Grade: " + grade + ", Passed: " + passed);
}
}Ayesha got 92 marks Grade: A, Passed: true
Naming Rules
- Names can contain letters, digits,
_and$, but cannot start with a digit - Names are case sensitive:
totalandTotalare different - You cannot use Java keywords like
intorclassas names - Use camelCase for variables:
totalPrice,studentName
Constants with final
Add final when a value must never change:
Example
final int DAYS_IN_WEEK = 7;
// DAYS_IN_WEEK = 8; would cause an errorThe var Keyword
Since Java 10, var lets Java work out the type from the value:
Example
var city = "Karachi"; // Java knows this is a String
var count = 12; // Java knows this is an intType Casting
Casting changes a value from one type to another.
- Widening (small to big) happens automatically:
inttodouble - Narrowing (big to small) must be written by hand with
(type)
Example
public class Main {
public static void main(String[] args) {
int items = 9;
double asDouble = items; // automatic
double average = 7.8;
int rounded = (int) average; // manual, the decimal part is cut off
System.out.println(asDouble);
System.out.println(rounded);
}
}9.0 7
Casting a double to int does not round the number. It simply removes everything after the decimal point, so 7.8 becomes 7.
Exercise
Exercise
Which data type should you use to store the value 'B'?
