2. 0010 - Variables
What’s the Point?
-
Know how to select a data type
-
Write code to declare variables and assign values
-
Do some basic math
Source code examples from this chapter and associated videos are available on GitHub.
It’s fun to create programs that display stuff on the screen, but that’s pretty limited. To start doing things that are more interesting—and useful—we’ll need to keep track of some information. In computer programming, a piece of information is called data.
In broad terms, there are two kinds of data:
- constant
-
A piece of data that can’t change during program execution.
- variable
-
A piece of data that may change (or "vary") during program execution.
In our Hello World
code, the letters and characters we output are constant data.
HelloWorld
in Java1
2
3
4
5
6
7
8
9
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!"); (1)
}
}
1 | The string literal "Hello World" |
The only way to change what’s output is by editing that constant—in the quotation marks—in our source code, before we run the program.
The string literal in our Hello World code is just one kind of constant. We’ll learn about others later.
|
In order for our programs to be flexible and responsive, we’ll need variables. I encourage beginning students to think of a variable like a container, such as a cup.

The container can hold one thing at a time. We can put coffee in it, or we can put water in it—but we can’t put both. If we start with coffee and decide we want to put water in there, the coffee gets dumped out and is gone forever. That’s fine, but we better make sure we don’t want the coffee anymore before we put something else in the mug.
A variable works the same way. It can hold one value, and that value can vary—remember, that’s where the name comes from—but once it’s changed, that old value is lost.
I guess we could mix coffee and water, but then that’s really a new substance and we can’t get back our plain coffee (or our water). If we want to store coffee and water, we can do that by using two different containers.
From a programming perspective—rather than a coffee perspective—a variable is a location in the computer’s memory where we can store a value. In order to use that value, we have to know where to find it, so we give the memory location a name, technically called an identifier.

And the computer will need to know how much memory to set aside for that variable, which depends on the kinds of values we want to store. Storing the number 7 doesn’t take very much space; storing a picture of John Elway takes a lot more space (but it’s worth it). The type of data we can store in a variable is called its
…drumroll, please…
data type.
Reserving a memory location by specifying a data type and identifier is known as declaring a variable. Placing data in that variable is referred to as assigning a value to a variable.
If you have programming experience in Python or JavaScript, the idea of a data type might be new to you. In those languages, the interpreter determines the data type for you—so you don’t have to specify it. It’s one reason I prefer to teach beginners using Java or C#, which teaches you how data types work. |
2.1. Java Identifiers
Variable names (more properly called variable identifiers) are the character sequences that identify a variable. There are a few rules that determine whether or not an identifier is valid:
-
Can contain letters (upper or lower case), digits (0 - 9), underscores (_), and/or dollar signs ($)
-
The first character can’t be a digit.
-
Can’t contain whitespaces (tab, space, etc.) or special characters (like #, @, !, etc.) except the underscore and dollar sign.
-
Can’t be a Java keyword or reserved word (words that are used in the Java language, like
double
orpublic
)
In addition to those technical rules about identifier names, the convention in Java is to use descriptive names in "camel case" format, as described in the preceding video.
Single-letter variable names, like x
for a number, are fine in your math class, but are generally not okay when you’re coding.
The expectation in my course is that your code will align with those conventions—because that’s what industry people expect—and you will lose points if you don’t.
2.2. Numeric Data Types
Variables for storing numbers come in two flavors: integers and floating-point numbers. As you may remember from your math class, an integer is a whole number; that is, a number that doesn’t include any decimal places or fractional values. 5 is an integer, -824 is an integer, while 3.14 and 7 1/2 are not.
A floating-point number includes decimals, so 3.14 can be stored as a floating-point number. 7 1/2 can also be stored as a floating-point number, but only as a decimal (i.e., 7.5).
The most common numeric data types in Java are int
for integers and double
for floating-point numbers.
You can get pretty far in programming just using those two, and in courses I teach you won’t need to use any other numeric data types—but others do exist.
Other data types for integers are byte
, short
, and long
.
These different types exist because they use different amounts of memory. byte
and short
are smaller than int
, while long
is larger.
The impact of these different memory sizes (or memory allocations) is that the types can store values of different sizes.
For example, a byte
uses 8 bits of memory and can store a number between -128 and 127 (inclusive), while an int
takes 32 bits and can store a value between -2,147,483,648 and 2,147,483,647 (inclusive).
The other floating-point data type in Java is called float
.
It’s called "single" in some programming languages, which helps understand where the name double
comes from: double
uses twice as much memory (64 bits) as a float
or "single" (32 bits)--and therefore its range of values is twice as big. Be aware that to make a float
number in Java, you have to add the letter F (in capital or lowercase form) at the end of the number.
1
2
3
int myAge = 21;
float myGPA = 3.75f; (1)
double myFriendsGPA = 3.54;
1 | The f suffix denotes that the value 3.75 is a float rather than a double . |
2.2.1. Who Cares About Variable Size?
The general rule in programming is to be as efficient with your resources (memory, storage, processing speed, network bandwidth, etc.) as possible.
If you’re storing a person’s age, you don’t really need an int
; nobody is going to be two million years old!
A byte
has plenty of room (up to 127) to store even the oldest person’s age, and it uses a fraction of the memory—8 bits instead of 32.
So I should be telling you to use a byte
in this case.
But I don’t worry about that with beginning programmers for two reasons.
First, it’s hard enough for a beginner to write programs that work—so instead of asking you to deal with all of the numeric types, I just have you use int
whenever you need a whole number, and double
when you need something with a decimal.
Second, these days even the wimpiest computer has waaaaaay more RAM than is needed by even the most complex program a beginner will write, so we don’t need to worry about it.
But understand that this attitude is only a teaching and learning aid. It’s like saying we shouldn’t worry about the price of groceries because we have plenty of money. That might be true, but it’s good to be careful with your money—and it’s irresponsible of me to tell you to just waste your money.
As you get more comfortable with programming, use your memory resources efficiently. While you’re learning, just worry about getting your code to work.
There’s another bad data type practice that I use with beginners.
Floating-point numbers aren’t 100% precise, for reasons that are too nerdy even for us right now.
Because of that precision problem, we should never use float or double for something like money/currency. Instead, Java has something called BigDecimal .
But this is another place where I value simplicity for beginners, so we just use double for stuff like prices and account balances in our code.
Just know that you’ll get fired if you do that at your job with the bank.
|
2.3. boolean
Data Type (and Boolean Logic)
A boolean
variable has only two possible values: true
and false
.
It’s useful for tracking information that is only one thing or the other.
Am I passing this class?
The answer to that is either true
or false
--there is no other possibility.
Does Julia own a car?
Again, only two possible answers to that question; she either owns one or she doesn’t.
The best practice is to name a boolean
variable in a way that expresses this either/or state.
That is to say, we usually name our boolean
variables using words like is, has, can, and so on.
1
2
boolean isPassing = true;
boolean hasCar = false;
boolean
variables go hand-in-hand with Boolean expressions which are statements that evaluate to be either true
or false
, like those questions above.
We’ll look at this "Boolean logic" in the chapter on decisions.
2.4. char
Data Type
If we want to store a single character, like a student’s letter grade or their first initial, we can use the char
data type.
Char literals are created by putting a character in single quotes, and that character can be a letter, number, punctuation mark or symbol—or some other weird stuff, too.
1
2
char myLetterGrade = 'A';
char firstInitial = 'T';
Some people pronounce the char data type like the word "chart" without the "t". And some people pronounce it like the word "care". Either is okay.
|
Also, I pronounce it "char" like "chart" without the "t" and firmly believe that only a sociopath would say it like the word "care". |
A char
is really just an integer, but the number it holds conforms to a standard list of character values called ASCII (with the fun pronunciation "Ass key").
In this standard, the number 65 is a capital 'A', 66 is 'B', and so on.
Lowercase letters are considered different characters, so 97 is 'a' and 98 is 'b'. Check out the complete ASCII table if you’re curious.
2.5. Strings
A char
is pretty limited since it can only hold a single character.
If we want to put a collection of characters together to make words and sentences, we need multiple char
s grouped into a single variable.
That data type is called String
, because it strings together a bunch of char
s, like a string of holiday lights.

String
variable is multiple char
s strung together like a set of lights.A String
is different from the other data types we’ve looked at so far.
The types we’ve seen so far are primitive data types, and String
is what’s called a reference data type (though some folks might prefer the more generic "non-primitive data type").
Primitives are stored differently in memory, and they are not objects--which we’ll learn more about later.
For now, a really important thing to notice and remember is that primitive types start with a lowercase letter (int
, double
, etc.) and reference types start with a capital letter: so you have to remember to type String
with a capital S.
String
literals are denoted with double quotation marks.
String
variable declarations in JavaString address = "3000 N. Dysart Road";
String bestClass = "CIS150AB";
Strings are really important and there’s all kinds of fun and useful stuff we can do with them, but we’ll need to save all of that for later while we stay focused on the basics.
Always remember that, in Java, single quotes mean a char and double quotes mean a String . It’s easy to get them mixed up—especially if you’re used to Python, where they are interchangeable—but your code won’t compile if you mix them up.
|
2.6. Declaring Constants
A constant is similar to a variable, with two rules:
-
A value must be assigned when the constant is declared.
-
The assigned value can’t change during program execution.
To create a constant, add the keyword final
at the start of your statement, followed by the rest of a declaration and assignment statement you’d use for a variable.
So that people looking at your code can easily tell it’s a constant rather than a variable, it should be named with all capital letters, using the underscore character to separate words.
final double SALES_TAX_RATE = 8.7;
final int MINIMUM_AGE = 18;
final String FAVORITE_CLASS = "CIS150AB";
There are a few different reasons to use constants in your code. For now: * Constants improve readability—they identify the purpose of a value within your code. * Constants prevent writing code that accidentally changes a value that shouldn’t change. * Constants make code easier to maintain/update. * In some situations, constants are more efficient than variables.
2.7. Outputting Variable (and Constant) Values
Assigning a value to a variable or constant does not produce any output.
If we want to display the output of a variable—or a constant—we just put the identifier in a print()
or println()
statement without any quotation marks:
print()
statements1
2
3
4
5
6
String artistName = "Sam Cooke";
int birthYear = 1931;
System.out.print(artistName);
System.out.print(" was born in ");
System.out.println(birthYear);
This code output Sam Cooke was born in 1931
.
We can combine output into one statement by creating a string with multiple pieces using the +
symbol.
1
2
3
4
String artistName = "Sam Cooke";
int birthYear = 1931;
System.out.println(artistName + " was born in " + birthYear);
Creating a String
using the ` symbol is called _concatenating_.
Be thoughtful when concatenating, because the `
symbol is also used to do addition with numbers, as you’ll see.
For our purposes, there’s no difference between outputting using separate print()
statements or concatenating everything in one statement; you can use whichever approach you prefer (and we’ll learn other ways to output values, too).
2.8. Math Calculations
To start doing some calculations, we’ll use operators.
You can think of an operator as a symbol that performs a calculation or other action.
You’ve been using an operator already: the assignment operator, which uses the =
symbol.
The action it completes is assigning the value on the right of the =
symbol to the variable on the left.
Arithmetic operations work in a similar way.
In Java, there are five basic arithmetic operators:
Operator |
Description |
|
Addition |
|
Subtraction |
|
Multiplication |
|
Division (quotient) |
|
Modulo (remainder) |
The arithmetic operators work pretty much the way you’d expect, except maybe modulo--which might be a term you’ve never heard before. Each operator acts on the value to either side:
1
2
int sum = 5 + 7; (1)
int difference = sum - 2; (2)
1 | The value of sum will be 12 |
2 | The value of difference will be 10 (i.e., 10 - 2) |
2.8.1. Order of Operations
Early on in your math studies you learned about order of operations when an arithmetic expression has more than one calculation, and it works the same in Java. We call this operator precedence, and here are the guidlines:
-
Any operations enclosed in parentheses are evaluated first, following the rest of the rules here.
-
Multiplication, division, and modulus are evaluated next: the
*
,/
, and%
operators. If there are more than one of these operations in the expression, they are evaluated from left to right. -
Addition and subtraction are evaluated last. As above, if the expression contains more than one
+
or-
operator, they evaluate from left to right.
Consider the following examples:
int result1 = 17 - 4 * 6 / 3; (1)
int result2 = 17 - 4 / 2 + 2; (2)
int result3 = 17 - 4 / (2 + 2); (3)
1 | result1 is 9: 4 * 6 is 24, then 24 / 3 is 8, and then 17 - 8 is 9. |
2 | result2 is 17: 4 / 2 is 2, then 17 - 2 is 15, and then 15 + 2 is 17. |
3 | result3 is 16: (2 + 2) is 4, then 4 / 4 is 1, and then 17 - 1 is 16. |
2.8.2. More Arithmetic with Less Typing!
There’s a pretty consistent rule of thumb in coding that says programmers want to type as little as possible, so programming languages often provide shorthand ways of writing code that’s used frequently.
Compound assignment operators (also called shorthand operators) simplify the syntax when you need to change a variable’s value relative to it’s existing value.
For example, if we want to add 10 to a weight
variable that already has the value 145
, we could use the following:
weight = weight + 10;
Java starts on the right side of the assignment expression and retrieves the current value of weight
, which is 145, adds 10 to that value, and stores the result back in weight
.
We can combine the addition operator (`) with the assignment operator (`=`) to make a compound addition operator: `=
, which allows us to rewrite the above line of code as:
weight += 10
;
You can use compound assignment operators for all of the arithmetic operations:
-
+=
adds the value on the right to variable value on the left. -
-=
substracts the value on the right from the variable on the left. -
*=
multiplies the value on the left by the value on the right. -
\=
divides the variable value on the left by the value on the right. -
%=
divides the variable value on the left by value on the right, then assigns the remainder.
An operation we might not use much now, but will start using a lot when we learn to write loops, is incrementing a value, or adding 1 to a value. The increment operator (two plus symbols) gives us a very easy way to do that. On somebody’s birthday, for example, we could write:
age++;
The ++
simply adds 1 to the current value of age
.
The decrement operator is --
, and it subtracts 1 from a variable’s value.
If we’re counting down the number of days until our next birthday, we could execute this expression each morning:
daysRemaining--;
Increment and decrement only require one operand, so we call them unary operators.
There are two forms to the increment and decrement operators: prefix and postfix. These examples use the postfix form, putting the operator after the variable name, whereas a prefix form would have the operator before the variable name: ++age . There’s a subtle difference in how postfix and prefix operations work, but for now you can use them interchangeably. I mention it here only because you might see code examples online using the prefix form.
|
2.9. Getting User Input
Until now, our code hasn’t been interactive—each execution of a program results in the exact same output, and the user never has the chance to input anything.
To produce output, we’ve been using System.out
to send text to the "standard output device"--your monitor.
For input, we’ll need to use the "standard input device" (your keyboard) by accessing System.in
.
We can access that input device using something called the Scanner
class.
The Scanner
class includes a variety methods for working with input "streams" (including input sources other than a keyboard), but the ones you’ll need for our work are shown below.
Method |
Description |
|
Returns a |
|
Returns a |
|
returns an |
|
returns a |
As a reminder, there’s a weird quirk that happens when you get numeric input from a user and then ask for String input using next() or nextLine() . If your program seems to skip that next() or nextLine() , review that part of the video!
|
Check Yourself Before You Wreck Yourself (on the assignments)
Can you answer these questions?
Sample answers provided in Stuff That’s Tacked On The End.