4. Variables

Last section's lessons

In the last section's exercises, we learned a few things about fixing bugs:

Now, let's turn to variables...but before we talk about those, we have to talk about types.

What is a type?

You may not have heard the word "type" before, but if you've coded in Python, you know (at least unconsciously) what a type is. A type is just a kind of data, like strings, integers, decimal numbers, or booleans. When we talk about the type of a variable, we're talking about the kind of data it's holding:

# python
x = 3           # x is type integer because it's holding an integer value
x = "abc"       # now x is type string
x = 5.5555      # now x is type floating point (the type for decimals)
x = True        # now x is type boolean
x = Point(0,0)  # now x is type Point because it's holding a Point object

In Python, types change freely from one line to another; we can put a string in a variable that was previously holding an integer without any trouble.

Types in Java

Java is different. When first making a variable, we have to explicitly declare what type it is.

// java
class VariablesTest {
    public static void main(String[] args) {
        int a = 3;              // a is type int, which stands for integer
        double b = 5.5555555;   // the double type is for decimals
        String c = "abcdef";    // the String type is for strings (note the capital 'S')
        boolean d = true;       // booleans are for true/false values

        // prints all the variable values, separated by spaces
        System.out.println(a + " " + b + " " + c + " " + d);

Declaring a variable's name and type is called, appropriately, declaration. Declaration tells a program to reserve space for a variable of that name and type. Giving a variable its first value is called initialization. We can do these steps separately -

double x;                       // declares a variable named x of type double
x = 123.456;                    // initializes x to 123.456

‐ or together, like we did above:

boolean y = true;               // declares and initializes y in one line

We only have to declare the type the first time we declare a variable. After that, we drop the type and just refer to it by name.

int elephant = 53;              // create an int variable named elephant with value 53
elephant = 1;                   // no "int" necessary, now elephant equals 1
elephant = elephant - 1;        // now elephant equals 0

int elephant = 99;              // BAD - won't compile, elephant is already declared
elephant += "a";                // BAD - can't add a String to an int

Also, types can't change mid-way through a program.

String v = "a";
v = 8;                          // BAD - v is type String, not int
boolean v = true;               // BAD - v was already declared as String

Some of the basic types

Type Example Notes
int helloIAmAnInt = 6284; ints can only hold values between -231 and 231 - 1, exclusive. The long type can store larger integers.
double thisIsADouble = 218481.224; There is another type for decimal values called float, but it's less precise, so you should just use double.
boolean whatABooleanIAm = false; Booleans can only hold two values: true or false. Note that true/false aren't capitalized, unlike in Python.
String stringsAreTheBest = "woo!"; Note that the "s" in String is capitalized. You must use double quotes to make a String, not single quotes (unlike in Python).


We can add +, subtract -, multiply *, divide /, and take the remainder % of doubles/ints, just like in Python. Python's exponentiation operator ** doesn't exist in Java, though.

int g = 3;                  // declare an int variable named g initialized to 3
g = g + 5;
g = 2 * 6;
System.out.println(g)       // prints g, which is now 12

int h = 12 % 4;             // % is remainder operator, h equals 0

g = g**2;                   // BAD - won't compile, Java doesn't have ** operator

Python's and, or, and not boolean operators are replaced in Java by &&, ||, and !.

boolean w = false;          // declare a boolean variable named w initialized to false
boolean x = true;
boolean y = w && x;         // false AND true equals false
boolean z = !y;             // NOT false equals true
z = x && (w || y);          // true AND (false OR true) equals true

We can use + to concatenate Strings just like in Python, but we can't use * to multiply them.

String a = "a";             // declare a String variable named a initialized to "a"
String b = "b";
String c = a + "e " + b;    // c equals "ae b"
System.out.println(c * 3);  // BAD - can't multiply Strings in Java


These will help you practice declaring types and creating variables. You want to get used to seeing types so you don't get confused about which part of a variable declaration is doing what. It's important to practice a lot so the basics won't trip you up in the future.

Remember that your programs will need to be wrapped in a class and have a main method.

  1. Write a program that peforms the following calculations (as separate lines of code - don't just initialize the int to 96.666666667):

    Make an int variable. Initialize it to value 42.
    Subtract 100.
    Add 345.
    Divide by 3.
    Add 1.
    Print the variable.
  2. Google java primitive types. What's the long type I mentioned earlier? What other primitive types are available to you besides int, double, and boolean? Why isn't String a primitive type?

    (Note: it's okay if you don't understand everything you read yet. You'll eventually get to the point where you're more comfortable with the vocabulary. Just keep pushing through until then).

  3. What happens if you print the value of an uninitialized variable, like this:

    int x; // only declared, not initialized

    Do different things happen with different types?

  4. Debug this program.

    String aString = 'apple';
    String aSecondString = 'pie';
    int combined = aString + " " + aSecondString;
    int x = 5;
    int y = 2147483647;
    int x = 5;
    int z = y + 5;
    boolean 110101 = false;
    boolean aTest = True;
    System.out.println(110101 && !aTest);

    When fixed, it should print

    apple pie

    Recompile after every change you make so you can get used to reading the error outputs.

  5. Predict what this program will print, then run it and see if you're right.

    boolean a = true;
    boolean b = false;
    boolean c = (a && b);
    c = b || !c;
  6. Why can we do this

    int x = 5;
    String y = "a";
    System.out.println(x + y);

    but not this?

    int x = 5;
    String y = "a";
    int z = x + y; // won't work

    Google around and give it your best guess.