Variables
Programming Languages · Java Basics · 10 min
Store numbers, text and true/false values in variables, and change them.
Whole numbers: int
A variable is a labelled box that holds a value. In Java you say what kind of value goes in the box first. int means a whole number.
int age = 30;
System.out.println(age); // prints 30
No quotes around age in println: you want the value inside the box, not the word.
Create an
intvariable calledscoreset to10.Print
score.
Decimals and true/false
double holds a number with a decimal point. boolean holds just true or false, perfect for yes/no facts.
double height = 1.75;
boolean isRaining = false;
Create a
doublecalledpriceset to4.99, then print it.Create a
booleancalledinStockset totrue, then print it.
Letters and text: char and String
char holds a single character in single quotes. String holds text of any length in double quotes. Note the capital S in String.
char initial = 'Z';
String city = "Paris";
Create a
charcalledgradeset to'A', then print it.Create a
Stringcallednameset to"Ada", then print it.
Changing a variable
You can put a new value in a variable any time. Leave out the type the second time: the box already exists.
You can even use the old value to make the new one:
int coins = 5;
coins = coins + 2; // now 7
Below the first print, take 1 away from
livesusinglivesitself.Print
livesagain.
Values that never change: final
Put final in front of a variable and Java won't let anyone change it later. Use it for fixed values. By habit, their names are in CAPITALS.
final int MAX_PLAYERS = 4;
// MAX_PLAYERS = 5; would not compile
Create a
final doublecalledPIset to3.14.Print
PI * 2.
Put it together: level up
Let's build a tiny game character. Store the player's name and level, level them up, then show both.
Create a
Stringcalledplayerset to"Ada"and anintcalledlevelset to1.Level up: add 1 to
levelusinglevelitself.Print
player, thenlevel, on separate lines.
More in Java Basics
Previous: Hello, World! · Next: Strings