Core elements of programs - Variables

Introduction

Computers operate a little bit like people. They do things. But, in order to do useful things, they also need to remember things. Variables are computers ways to remember things. Imagine a big storing wall. The wall has lots of boxes, all labelled. When you have an object, you can go store it in a certain box. Later you can go get the object back out of the box.

Each box is like a variable. Each variable has a name, and you address it by it’s name. You can store values in varibles, and retrieve and do things with that value.

Types of variables

Here are some common types of variables:

Name Description Example
int Stores whole numbers 1, 5, -8, 4613
float Stores decimal numbers 1.2, 8.5, -3.1415926
boolean Stores true/false value true, false
String Stores words/sentences “I am Mr.Potato”, “Bork bork bork”, “We are number one”

Note that capitalisation is important. Objects (e.g. Strings) must be capitalised, primtives (int/float/boolean) shouldn’t be.

Making variables

When creating variables there are three parts:

  1. The type of variables
  2. The name of the variable
  3. The value of the variable

Convention for variable names is to be lowerCamelCase - start of each word capitalized, except for the first word.

Java is a strongly typed language. This means that every variable has a type which can’t be changed. Other (hipster) languages like Python aren’t strongly typed - anything can go in any variable at any time. But this means you have to be very careful with what you’re doing.

Here’s an example of creating several variables.

int teamNumber = 4613;
float pi = 3.141592653589793;
boolean isBorkGod = true;
String bestestName = "Dean Borkman";

Accesing variables.

This is pretty easy. Just write the name! for example:

System.out.println(bestestName);

Outputs: Dean Borkman

Changing variable values.

Also pretty easy. Similar to making the variable, but you don’t need to assert the type again.

int potatoCounter = 2;
System.out.println(potatoCounter);
potatoCounter = 54;
System.out.println(potatoCounter);

would give:

2
54

Scope

This will be a bit confusing intill you’ve laernt some more stuff. We’ll cover it again later, but for now don’t worry if you don’t understand it. Scope is just what parts of the program can see what other parts. For now, most code will all be simple, straight forward and all in the one file. But later, you’ll create objects, have code & variables and in many many files. For now, the two places variables can be is inside functions, and in the class. variables in a function can only be seen by other code in the function. So if you declare a variables inside the curly brakcets “{ and }” of public static void main blah blah then only code inside that function will be able to see and use that variable. Variables declared outside that area can be seen by all code in the class (file).

So, for example:

public class Output
{
	static String imAVariable = "I am Mister Variable";
	
	public static void main(String[] args) {
		String iTooAmAVariable = "Yes I am!";
		
		System.out.println("im A Variable: " + imAVariable); //Works
		System.out.println("i Too Am A Variable: " + iTooAmAVariable); //Works
		thisIsAFunction(); //runs code in thisIsAFunction()
	}
	
	public static void thisIsAFunction() {
		System.out.println("im A Variable: " + imAVariable); //Works
		System.out.println("i Too Am A Variable: " + iTooAmAVariable); //Uh-oh!
	}

}

the first three are good. the last one is out of scope! (oh noes.) The console output is:

im A Variable: I am Mister Variable
i Too Am A Variable: Yes I am!
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	iTooAmAVariable cannot be resolved to a variable

	at main.Output.thisIsAFunction(Output.java:17)
	at main.Output.main(Output.java:12)

Don’t stress too hard about understanding this, it’s not really important right now, and you’ll understand it more once we cover OOP and other stuff.

Modifiers

You might notice that in the variable declaration for “imAVariable” there’s the word “static” in front of it. What’s up with that??? Well static is a modifier. Like a lot of things this becomes a more important concern later on, after OOP and more variable stuff, but its important to understand it a bit now.

Modifiers make variables behave slightly differently.

Aside from the final modifier, all modifiers can only be put on variables declared at the class level, not at the function level

Some common modifiers are below:

Name what it does
public Makes it visible to all other bits of the program (expands its scope).
private Makes it visible to only the current class (internal to the current file)
protected Makes it visible to only itself, things in the same package, and subclasses
static A big OOP thing. Makes it the same between instances of the object… we’ll cover this one later
final Makes the variable unable to change - also makes it more efficient, and the code run faster.

final at first seems a bit silly. Howeer, it can be very useful to manage magic numbers - magic numbers are random constants that otherwise get spread thorughout your code. Lets say you really like the number 8, and times all the numbers you use in code by 8. All is good, intill you decide you hate the number 8 and actually like 4. Now you need to go through and change all 8s to 4s… oh dear that sounds super painful. A better solution would be to have a final variable at the beginning of your file, that everything uses, making everything nice and easy to change frequently. (an IRL (and sane) example is motor ports on the robot - these are all kept as final variables on the robot.)

Laziness

Often you’ll need to add a value to a variable, say add 3 to the variable importantNumber. you could write this out as

importantNumber = importantNumber + 3;

but that’s a trek to right out all the time. Programmers got lazy and added fancy syntax to modify variables to themselves. This can be re-written as:

importantNumber += 3

Here’s the full fancy list below: (actually its not all of them but its all the useful ones.)

Operator Description
+= Add amount to variable
-= Subtract amount to variable
*= times variable by amount
/= divide variable by amount
%= Modulus operator. Divides variable by a number, and sets variable to the remainder. (e.g. 10 % 3 = 1)
++ Add one to variable (e.g. aNumber++;)
Subtract one to a variable (e.g. aNumber–;)

Activities

  1. Print out some variables
  2. Add and subtract various variables. Throw in some brackets. Does it follow BODMAS?
  3. Can you add strings together?
  4. Can you add strings and numbers together?
  5. for two given side lengths, output the hypotenuse (You will need to google to find out how to get the square root of a number)
  6. What is the maximum size an int can be?
  7. Print out the sum of two floats. (hint: sum two numbers that aren’t powers of 2)