Lesson 2Phase 1: First steps
Variables, types, and input/output
Storing values in variables with a fixed type, and why Java checks types before the program even runs.
By BasithUpdated 55 min
- int
- double
- boolean
- char
- String
- declaration
A program spends most of its time remembering values and moving them around: a name, an age, a price. To remember a value, you give it a name and put it in a box called a variable. Java adds one rule to that box. You say up front what kind of value it will hold, and Java holds you to it. This lesson is about that rule, the kinds of value Java offers, and how a program prints values and reads what a person types.
- Declare a variable with a type and a value, and change its value later.
- Explain what static typing means: a variable's type is fixed, and Java checks it before the program runs.
- Choose between
int,double,boolean,charandStringfor a value, and write a literal of each. - Predict what happens to a variable that was copied from another one.
- Print values with
printlnandprint, and join text and values with+. - Read a line the user types with
IO.readln.
public class Main with a main method inside it, and System.out.println(...) to print a line. You also met the IO class, whose readln method this lesson puts to work. Everything new happens on the lines between the braces of main.A variable is a named box#
A variableis a named place in the computer's memory that holds a value. Picture a box with a label: the label is the variable's name, and the box holds one value at a time. In Java, the box has one more thing written on it, the type of value it may hold. Here is a variable being created:
public class Main { public static void main(String[] args) { int age = 12; System.out.println(age); }}Read the line int age = 12; from left to right:
intis the type. This box holds a whole number.ageis the name. You use it to reach the box later, asprintln(age)does.= 12puts the value 12 in the box. In Java, a single=means “store this”; it does not ask whether two things are equal.- The semicolon ends the statement.
That word typemeans “what kind of value”: a whole number, a number with a decimal point, true or false, a single letter, some text. You write the type when you create the box. Step through the program above and watch age appear, holding 12, as its line runs.
x = 5 with no type, and the same name can later hold text. In Java you write int x = 5;: the type comes first, x can only ever hold whole numbers, and the statement ends with a semicolon.Static typing: the type is fixed for life#
Once you declare int x, the name x holds whole numbers for the rest of the program. You can change which number is in the box as often as you like:
public class Main { public static void main(String[] args) { int x = 5; System.out.println(x); x = 10; System.out.println(x); }}It prints 5 and then 10. The value changed. The type did not: the box is still an int box. Add the line x = "hi"; at the end of main, compile it, and Java refuses to build the program at all:
$ javac Main.javaMain.java:7: error: incompatible types: String cannot be converted to int x = "hi"; ^1 errorThis is static typing. “Static” means fixed: each variable's type is settled when you write the code, and the compiler checks every line against it before the program is allowed to run. A line that puts text in a number box never reaches anyone using your program.
Key ideaIn Java the value in a variable can change, but its type cannot. You commit to the type once, when you declare the variable, and the compiler checks every use of it before the program runs.
x = "hi"; without complaint. To see Java reject a line like that, compile it with javac or type it into JShell, as in your first Java program. The type check lab further down this page shows javac's verdicts too.int x = 5; does two things at once: it declares the variable (creates an int box named x) and initializes it (puts 5 inside). You can also do them on separate lines, as you will see below.int x = 5;. Which of these later lines does Java accept?The types you will reach for#
Java has a small set of built-in basic types called primitive types. Primitive here means the simplest building blocks, not made out of anything smaller. These are the ones you will use all the time. Read the list once; you only need the rough idea of each, not the exact limits.
intholds a whole number with no decimal point, like0,12or-7. It covers anything up to about two billion in either direction, and it is your default for counting things.longalso holds whole numbers, but far beyond two billion, such as the number of nanoseconds in a day. Alongvalue is written with anLon the end:long big = 9000000000L;. Without theL, Java reads the number as anint, finds it too large for one, and refuses to compile the line.doubleholds a number with a decimal point, like4.5,3.14159or-0.001. It is your default whenever fractions are involved.floatis a smaller, less precise decimal type. You will rarely need it; preferdouble. Its values end inf:3.5f.booleanholds exactly one of two values,trueorfalse. It is the type of a yes-or-no answer, and every decision a program makes comes down to one.charholds a single character, written in single quotes:'A','7','?'.
'A' in single quotes is a char: one character. "A" in double quotes is a String: a piece of text that happens to be one character long. They are different types, and mixing up the quotes is one of the most common early errors.And then there is String
For text of any length, a word or a whole sentence, you use String, written with double quotes: String name = "Mira";. Strictly speaking String is not a primitive type. It is a class, a richer kind of type that comes with its own methods, which you explore in strings. For now, treat it as the type for text.
String starts with a capital letter while int, double and the rest are lowercase. That capital is a quiet sign that String is a class rather than a primitive type. What that means arrives with objects; nothing to act on yet.Writing values directly: literals#
A literal is a value written straight into your code, like the 5 in int x = 5; or the "Mira" in a string. The literal is the value itself; the variable is the box you put it in. Java has a few families of literal:
- Integer literals are whole numbers such as
42or-7. You can also write them in hexadecimal with0x(0x1F), in binary with0b(0b1010), and in octal with a leading0(045). Plain decimal is what you will use almost always. - Floating-point literals are numbers with a decimal point such as
3.14, or in exponent form such as1.2e3(1.2 times 10 to the power 3). Anfon the end makes afloat; without it you get adouble. - Character literals are one character in single quotes, like
'a'or'%'. - String literals are text in double quotes, like
"Hello". - Boolean literals are the two words
trueandfalse. - The null literal,
null, means “no object at all”. It fits only types that hold objects, such asString, neverintordouble.
public class Main { public static void main(String[] args) { int million = 1_000_000; int hex = 0x1F; int binary = 0b1010; int octal = 010; long big = 9_000_000_000L; double sci = 1.2e3; float small = 3.5f; System.out.println(million); System.out.println(hex); System.out.println(binary); System.out.println(octal); System.out.println(big); System.out.println(sci); System.out.println(small); }}It prints 1000000, 31, 10, 8, 9000000000, 1200.0 and 3.5. However you write a number, Java keeps only its value, and println shows that value in ordinary decimal. Look at octal: 010 printed 8, because the leading zero made it an octal number. Never pad a number with zeros to line it up.
1_000_000 is easier to read than 1000000, and the compiler ignores the underscores. They may only go between digits, so a number cannot start or end with one.Escape sequences: special characters inside text
Some characters are hard to type directly inside a string, such as a line break or a double quote. For these, Java uses an escape sequence: a backslash \ followed by a letter that stands for the special character. The ones you will use most are \n for a new line, \t for a tab, \" for a double quote inside a string, and \\ for a backslash itself.
public class Main { public static void main(String[] args) { System.out.println("Line one\nLine two"); System.out.println("Name:\tMira"); System.out.println("She said \"hello\" to me."); }}"She said \"hi\"". Without the backslashes, Java thinks the string ended early and reports an error.Which values fit which types?
Now put the types and the literals together. The lab below puts a value into a variable of each type and shows what javac says about it. Guess each verdict before you pick it.
Pick a value and a variable type. The verdicts are what the real javac compiler says.
int x = 65;✓ Compiles
System.out.println(x) prints 65
65 is already an int value, so it fits its own box exactly.
Once you have tried a few, look at the grid. A number moves into a wider number type on its own, an int into a long or a double, but never into a narrower one, because it might lose something on the way. Text and true or false fit only their own type. The one surprise, char x = 65;, comes from a char being a number underneath, which the end of this page shows.
Declaring, then assigning#
You do not have to fill the box on the same line you create it. You can declare a variable first and assign it a value on a later line. Once declared, the name exists, so the second line does not repeat the type.
public class Main { public static void main(String[] args) { int score; // declare: an int box named score, still empty score = 100; // assign: now put 100 in it, no type word here System.out.println(score); }}The first line makes the box, and the second fills it. Step through it: after the first line the memory view shows score with no value yet, and the next line stores 100 in it. The assignment line is just score = 100; with no int in front. Writing the type again would try to declare a second box with the same name, which Java does not allow.
Assignment copies the value
When you write b = a, Java copies the value that is in a right now into b. After that, the two boxes are separate. Decide what this program prints before you run it.
public class Main { public static void main(String[] args) { int a = 5; int b = a; a = 10; System.out.println("a is " + a); System.out.println("b is " + b); }}After a changes to 10, what do the two lines print?
b stays 5. The line int b = a; copied the 5 that was in a at that moment. It did not tie the two names together, so changing a afterwards leaves b alone. Step through it in the playground and watch the two boxes in the memory view.
That rule makes a classic job, swapping the values of two variables, a little puzzle. If you write left = right; first, the old value of left is gone. The fix is a third, temporary variable that keeps a copy.
coffee tea. The variable temp keeps a copy of one value while the other moves.Tap a line, then tap where it should go. Or use the arrows.
age, totalPrice or isStudent. Pick names that say what the value is. price tells the next reader far more than p or x2.var instead of the type: var age = 12; creates an int, because 12 is an int. The type is still fixed, so a later age = "twelve"; is still refused. This course mostly writes types out, because seeing them helps while you learn. Modern Java syntax covers var in full.All the types, side by side, running#
Here is one program that declares a variable of each kind and prints them. Press Run and step through it. Watch each box appear with its value as its line runs, and watch the last assignment change age from 12 to 13.
public class Main { public static void main(String[] args) { int age = 12; double price = 4.5; boolean isStudent = true; char grade = 'A'; String name = "Mira"; System.out.println(name + " is " + age); System.out.println("Price: " + price); System.out.println("Student? " + isStudent); System.out.println("Grade: " + grade); age = age + 1; System.out.println(name + " is now " + age); }}That program prints:
Mira is 12Price: 4.5Student? trueGrade: AMira is now 13
The line age = age + 1; reads the current value of age (12), adds 1 to get 13, and stores that back in the same box. The right-hand side is worked out first, using the old value, and only then does the result go into the box.
Printing: println, print, and joining with +#
You already have System.out.println(...). The ln on the end stands for line: after printing, it moves to a fresh line. Its sibling System.out.print(...) prints the same way but stays on the current line, so whatever is printed next continues right after it.
public class Main { public static void main(String[] args) { System.out.print("Hello, "); System.out.print("world"); System.out.println("!"); System.out.println("Next line"); }}The first three calls land on one line, because the two print calls do not end the line; only the println after them does. So the output is Hello, world! and then Next line. A println() with nothing in the parentheses prints no text at all, only the line break, which is a handy way to finish a line that print started.
Joining values with the + sign
Inside the parentheses you can stitch pieces together with +. When at least one side of a + is a String, Java treats the +as “join into text”: it turns the other side into text and glues the two together. This is called concatenation, a long word for joining strings end to end.
public class Main { public static void main(String[] args) { String name = "Mira"; int age = 12; System.out.println(name + " is " + age + " years old"); }}That prints Mira is 12 years old. The number 12 is an int, but because it sits next to String pieces joined by +, Java writes it out as the text 12. Mind the spaces inside the quotes: " is " has a space on each side on purpose, so the words do not run together.
name + age prints Mira12 with no gap. If you want a gap, put it inside a string: name + " " + age.The same + also adds numbers, and Java works through a line of them from left to right. So what a + does depends on what is to its left at that moment. Try this one before you run it.
public class Main { public static void main(String[] args) { System.out.println(1 + 2 + " apples and " + 1 + 2 + " pears"); }}The same 1 and 2 appear twice. What does the line print?
It prints 3 apples and 12 pears. Working from the left, 1 + 2 are both numbers, so they add up to 3. Then 3 + " apples and " has text on one side, so it joins, and from then on the left side is always text. The second 1 and 2 are joined one after the other as the characters 1 and 2. To add them as numbers inside a sentence, put them in parentheses: "total " + (1 + 2) gives total 3.
Key idea
+adds when both sides are numbers and joins when either side is aString. Java reads the chain from left to right, and once text appears, every+after it joins.
Mirais12years old. Fix the spaces so the first line reads Mira is 12 years old, then add a second line that prints Mira lives in Lisbon using the variables.Reading what the user types#
Printing is output: the program telling the person something. Input goes the other way, with the program reading what the person types. The IO class from your first program has a method for it. IO.readln("What is your name? ") prints the question, waits for the user to type a line and press Enter, and hands back what they typed as a String, which you can store in a variable.
public class Main { public static void main(String[] args) { String name = IO.readln("What is your name? "); String city = IO.readln("Where do you live? "); System.out.println("Hello, " + name + " from " + city + "!"); }}The box labelled Keyboard input holds what the user types, one line for each press of Enter. Here the user types Mira and then Lisbon, and the program prints Hello, Mira from Lisbon!. Change the input and run it again: the same program now greets someone else. That is what variables are for. The program does not know the name in advance; it keeps a box for it.
IO.readln(prompt) does the job of Python's input(prompt).IO.readln always hands back text. If the user types 12, you get the String "12", not the number. Reading numbers takes one more step, which you meet in making decisions, and Scanner and console applications covers keyboard input in full.Mira likes mangoes. The tests type different answers, so build the sentence from the variables.Try it
Answer each one in your head or on paper first, then open the answer.
System.out.println("Total: " + 3 + 4);int called count without a value, then assign it 5 on the next line. Why is there no int on the second line?char c = "A"; and Java refuses it. What is wrong, and how do you fix it?int x = 3;, int y = x; and y = y + 1;, what are x and y?Practice
Work through these on your own. Each one builds on this page.
int, double, boolean, char and String) describing yourself: an age, a height in meters, whether you like Java so far, a favorite letter, and your name. Print each one on its own line with a label, like System.out.println("Age: " + age);.IO.readln (a name, a city and a hobby) and prints a small profile card: a line of dashes, three labelled lines such as Name: Mira, and the line of dashes again. Run it with different input, then once with an empty line for the hobby. What does the card show for it?int a = 1; and int b = 2;. Swap their values using a third variable, print both, and check that you get 2 1. Then explain in one sentence why writing a = b; followed by b = a; does not work.int age = 12 into JShell, then age = "twelve". Read the error it gives you, then write one sentence explaining how this error is the static typing rule from this lesson doing its job.Further reading#
- Creating variables and naming them, on dev.java, the official Java learning site
- Primitive types on dev.java, with every literal form and the default values
- Types, values and variables, chapter 4 of the Java Language Specification for Java SE 25
- The IO class in the Java SE 25 API documentation, including readln
Spotted a mistake, or a part that did not make sense? Report it by email