Variables, types, and input/output
Storing values with a fixed type, and the difference between static typing here and Python.
Finished reading?
Mark this session so you can track where you are.
Storing values with a fixed type, and the difference between static typing here and Python.
Finished reading?
Mark this session so you can track where you are.
A program is mostly just values being remembered and moved around: a name, an age, a price. To remember a value, you give it a name and put it in a box. In Java that box comes with one extra rule that Python never asked of you, and that rule turns out to shape everything.
println and print, and join text with +.public class Main with a main method inside it, and System.out.println(...) to print a line. That is all you need today. Everything new here happens on the lines between the braces of main.A variable is a name that points at a stored value. You met this idea in Python: you wrote x = 5 and from then on x stood for 5. Java has the same idea, with one difference you cannot skip. When you first create the box, you must say what type of value it will hold.
x = 5. No type is stated.int x = 5;. The type int comes first.x = "hi" is fine.x is an int, it can only ever hold whole numbers.;.That word typejust means “what kind of value”: a whole number, a decimal, a true/false, a single letter, some text. In Java the type is written down, by you, the moment the box is born. The computer then holds you to it.
In Python this is allowed, and many beginners lean on it:
# This is Python, shown only to compare.x = 5print(x)x = "hi" # x happily becomes textprint(x)5 hi
The same name x held a number, then held text. Python decides the type freshly each time you assign, while the program is running. That is called dynamic typing: the type is decided dynamically, as you go.
Java does the opposite. You declare int x, and from that point on x is an int forever. Trying to put text into it is not a mistake the program discovers later; it is rejected before the program is even allowed to run. This is static typing: “static” meaning fixed, unchanging. The type is fixed at the moment you write the code, not at the moment the code runs.
public class Main { public static void main(String[] args) { int x = 5; System.out.println(x); x = 10; System.out.println(x); }}5 10
Notice you can change the value in the box as often as you like: x went from 5 to 10. What you cannot change is its type. The box stays an int box. Writing x = "hi"; after that line would not run at all; Java refuses it.
In 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 language holds you to that promise for the rest of the program.
int x = 5; is doing two things at once: declaring the box (creating an int named x) and initializing it (putting 5 inside). You can also split them, which we look at just below.Java has a small set of built-in basic types called primitives. “Primitive” here just means foundational, the simplest building blocks, not made out of anything smaller. Here are the ones you will use constantly. Read the list once; you do not need to memorize the exact number ranges, only the rough idea of each.
int holds a whole number with no decimal point, like 0, 12, or -7. It comfortably covers anything up to about two billion in either direction. This is your default for counting things.long is the same idea as int but for much bigger whole numbers, far beyond two billion. You reach for it when a count could get truly large, like nanoseconds in a day. You write the value with an L on the end: long big = 9000000000L;.double holds a number with a decimal point, like 4.5, 3.14159, or -0.001. This is your default whenever fractions are involved.float is a smaller, less precise decimal type. You will rarely need it early on; prefer double unless something specifically asks for a float. Its values are written with an f on the end: 3.5f.boolean holds exactly one of two values: true or false. Nothing else. It is the type of a yes/no answer, and it becomes the heart of decisions later.char holds a single character, written in single quotes: 'A', '7', '?'. Note the single quotes, not double. One character, no more.'A' with single quotes is a char: one character. "A" with double quotes is a String: a piece of text that happens to be one character long. They are different types. Mixing up the quotes is one of the most common early errors, so slow down on this one.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; it is a built-in class, which is a richer kind of type we explore much later. For now, just treat it as the type for text and do not worry about that distinction.
String starts with a capital letter while int, double, and the rest are lowercase. That capital is a quiet signal that String is a class, not a primitive. The full meaning of that lands in why objects?. No need to act on it yet.intlongL.doublefloatf.booleantrue or false.char'A'.StringA 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 actual value; the variable is just the box you put it in. Java has a few families of literal worth knowing.
42 or -7. Java also lets you write them in other bases: octal with a leading 0 (045), hexadecimal with 0x (0x1F), and binary with 0b (0b1010). You will almost always use plain decimal.3.14, or in exponent form like 1.2e3 (meaning 1.2 times 10 to the power 3). Add f for a float and d (optional) for a double.'a' or '%'."Hello".true and false.null, marks a variable that points at no object yet. It can only be used with non-primitive types like String, never with an int or a double.int million = 1_000_000; reads more easily than 1000000, and the underscores are ignored by the compiler. Just do not start or end a number with one.Some characters are hard to type directly inside a string, like a new line or a quotation mark. For these, Java uses an escape sequence: a backslash \ followed by a letter that stands for the special character. The most useful ones are \n for a new line, \t for a tab, \" for a double quote inside a string, and \\ for a literal backslash.
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."); }}Line one Line two Name: Mira She said "hello" to me.
"She said \"hi\"". Without the backslashes, Java would think the string ended early and would report an error. This is the classic escape-sequence trap.You do not have to fill the box on the same line you create it. You can declare a variable first and assign a value to it on a later line. Once declared, the name already 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); }}100
The first line makes the box, the second line fills it. Note that the assignment line is just score = 100; with no int in front. Repeating the type would be trying to declare a second box with the same name, which Java will not allow.
Here is one program that declares one 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 reassignment 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); }}Mira is 12 Price: 4.5 Student? true Grade: A Mira is now 13
That program prints:
Mira is 12Price: 4.5Student? trueGrade: AMira is now 13The line age = age + 1; reads the current value of age (which is 12), adds 1 to get 13, and stores that back in the same box. The value moved; the type stayed int. This is the same value-changes-but-type-does-not idea from before, now in action.
You already have System.out.println(...). The ln on the end means line: after printing, it moves to a fresh line. Its sibling System.out.print(...) does the same thing but does not move to a new line, so the next thing printed continues right after it on the same line.
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"); }}Hello, world! Next line
The first three calls all land on one line because the two print calls do not break the line; only the println at the end of them does. So the output is:
Hello, world!Next lineInside 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 them together. This is called concatenation, which is 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"); }}Mira is 12 years old
That prints Mira is 12 years old. The number 12 was an int, but because it sat next to String pieces joined by +, Java wrote it out as the text 12 and glued everything together. Mind the spaces inside your quotes: " is " has a space on each side on purpose, so the words do not run together.
name + age would print Mira12 with no gap. If you want a gap, put it inside a string: name + " " + age.Try each one yourself first, then open the answer.
System.out.println("Total: " + 3 + 4);int called count without a value, then on the next line assign it 5. 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?Take these away. They continue exactly what we just did.
int, double, boolean, char, and a String) describing yourself: an age, a height in metres, 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);.int variable you made, print it, then on a new line reassign it to its value plus 10 using x = x + 10;, and print it again. Write a one-sentence note saying which changed, the value or the type, and why.System.out.println(1 + 2 + " apples"); and (b) System.out.println("apples: " + 1 + 2);. Explain in one or two sentences why the two results differ, using the left-to-right rule.int age = 12; and then on a later line age = "twelve"; in the playground. Read the error Java gives you, then write one sentence explaining how this error is exactly the static typing rule from this session doing its job.