What is a variable?
A variable is a named box that holds a value, so you can use it later.
Think of it like this: Imagine a box with a label. The label says age and inside is the number 21. In Java the box also has a type printed on it, like “whole numbers only”. You can't put anything else in that box.
Creating a variable
In Java you write the type, then the name, then = and the value:
public class Main {
public static void main(String[] args) {
int age = 21;
String name = "Asha";
System.out.println(name);
System.out.println(age);
}
}Output
Asha 21
intmeans the box holds a whole number.Stringmeans the box holds text. (Notice the capital S.)
= does not mean “equals” like in maths. It means “put this value in the box”. This is called assigning.
Joining text and variables
Use + to stick text and variables together in one line:
public class Main {
public static void main(String[] args) {
String city = "Pune";
int temperature = 31;
System.out.println("It is " + temperature + " degrees in " + city);
}
}Output
It is 31 degrees in Pune
Changing a variable
Once a box exists, you can put a new value in it. Don't write the type again:
public class Main {
public static void main(String[] args) {
int score = 10;
System.out.println(score);
score = 25;
System.out.println(score);
score = score + 5;
System.out.println(score);
}
}Output
10 25 30
In score = score + 5, Java first works out the right side (25 + 5 = 30), then stores 30 in the box.
The type can't change
An int box only takes whole numbers. Putting text in it is a compile error:
public class Main {
public static void main(String[] args) {
int age = 21;
age = "twenty";
}
}Output (the program does not compile)
Main.java:4: error: incompatible types: String cannot be converted to int
age = "twenty";
^Naming rules
| Allowed | Not allowed | Why |
|---|---|---|
userName | user name | No spaces |
score2 | 2score | A name can't start with a digit |
total | total-price | Only letters, digits, _ and $ |
myClass | class | Java's own keywords are reserved |
Tip: Java programmers write names in camelCase: start small, and give every new word a capital letter, like
totalPriceornumberOfStudents.