Wednesday 24 February 2016

Java Tutorial 4 - Variables

Last Time
Last time we looked at basic arithmetic with the print command

This Tutorial
In this tutorial we'll be looking at saving values so we can use them later

What is a variable
In a computer program, sometimes we need to save information which we can retrieve later. In Java there are a few different types of variables

int - This is an integer and is a whole number, eg 5
String - This is a collections of characters eg "Hello World"
float - This is a number with a decimal part, eg 5.39
boolean - This is true or false

Using variables
To create a variable in Java, we can use a line like the following

int age = 21;


This creates a variable called age. The variable has a value of 21. The type is int, because it is a whole number.
Now if we wanted to access the value of this variable, we could simply refer to age like so:

System.out.println(age);


Note that there aren't any speech marks around age. That is because we don't want to literally print the word "age" but rather the value of age, which is 21. If you now run the program, you should get output "21" as below



From now on, whenever we refer to age it will know to use the value 21. So if we were to make a new variable, called birthday, and give it the value 2016 - age it should give us our birthday.

int age = 21;
int birthday = 2016 - age;

System.out.println(birthday);

This will print out the value of birthday. The value of birthday is 2016 - the value of age. The value of age is 21. So our result should be 2016 - 21 which is 1995. Sure enough, that's exactly what we get


As you might expect, we can also use - * and / with variables as we can with numbers, as long as the variable is a number (int or float)

Using Strings
A String is a collection of characters or words. We can make a String the same way we make an int except we use the word String at the start rather than int.

String name = "Joe Bloggs";

Notice that you always need speech marks for a String. Also note that Java is case-sensitive and String has a capital S. We could then print this String as usual:

System.out.println(name);

And we should get an output of "Joe Bloggs". We can also add Strings together to join them

String firstName = "Joe ";
String lastName = "Bloggs";
String fullName = firstName + lastName;
System.out.println(fullName);

This assigns the word "Joe " to the variable firstName, the word "Bloggs" to the variable lastName and then adds them together and stores the result in the variable fullName. It then prints fullName which should print "Joe Bloggs".

We will look at floats and boolean in a later tutorial

No comments:

Post a Comment