A Crash Course in Programming

Note: The particular programming language I use here (as concrete examples of theory) is in Java, but much of the syntax (i.e. the way the code is written) is very similar, and often identical, to how it can be expressed in other languages such as C++, C#, etc.

Contents

Getting Started

Software you will probably find very helpful

A ‘Hello World’ Program

Running your Program

Part A - Primitive Types and Statements

Statements

Primitive Types revisited

Operations on primitive types

More statements

If Statements

While loops

Turning this into a runnable program.

Rewriting the program using a ‘for’ loop

One Final Note: The ‘Scope’ of Variables

Section Review

Check your knowledge

Part B - Methods

Some basic pre-written methods you should know about

String

Math

How to find out the methods a class has in Eclipse

Part C – Converting between types

Casting

Part D – Arrays

Some Quick Basics

Cycling through an array’s values using a ‘for loop’

Example program: Finding the factors of a number

Test Your Knowledge

Answers

Another Example: Roman Numerals

Object Orientation

Fraction Example

toString methods

Getting Started

We’re going to start from absolute scratch! We’ll be introducing the basic concepts involved in creating a basic program before working up to gradually complex stuff, as well as describing how we can use some of the tools to write, test and ‘debug’ our programs. My philosophy to learning programming is to learn by example, but that some basic ‘scaffolding’, i.e. programming theory, is essential also to becoming an effective coder. Without the latter, there is a danger to ‘hack stuff together’ in an undisciplined way.

Coding is a mixture of problem solving, engineering, creativity and scientific rigour. It involves approaching some potentially high-level problem, perhaps found in maths or science (such as generating a driving route based on a road map), and engineering a solution that translates that problem to a workable program.

Software you will probably find very helpful

We recommend a program called Eclipse to write your programs. You can find it at There’s lots of versions, but the one we’ll be using her is “Eclipse IDE for Java Developers” (there’s a similar one called “...for Java EE Developers” – you probably don’t need this one for the moment).There’s versions for Windows, Mac and Linux based operating systems.

Eclipse is known as an IDE or Integrated Development Environment. This helps you in a number of ways when coding:

  • For many languages, such as Java, it’ll let you know about incorrectly written code immediately. While most ‘bugs’ in your code (i.e. unexpected behaviour) it won’t be able to detect, it will underline code that has been written correctly according to the Java language, just as a word processor might underline incorrectly spelled words.
  • It’ll ‘compile’ and run your code at the click of a button. Compiling is the process of taking your code and converting it into a more basic form that the computer can directly read and run.
  • It’ll make managing your code much easier, if for example if you want to rename variables, move code about and other changes.

You can of course write your code in a basic text editor (e.g. Notepad!), and it’s useful knowing how to compile and run code yourself without the assistance of an IDE. But if you insist on using a basic text editor (which I did myself for many years before seeing the light!) you’ll miss all the advantages that IDEs bring, and waste much more time on the less important parts of coding.

When you’ve downloaded Eclipse, double click on the icon of the main Eclipse program (probably named eclipse.exe). You’ll be asked to select a workspace:

Your workspace is where you can create your various coding projects. Just name it anything you like, put it somewhere on your hard drive you can easily find, then click OK.

This will take you to the main welcome screen, which will look different depending on what version you downloaded. Click the arrow icon labelled ‘Workbench’ (pictured here on the top-right). This will bring up the workbench that you’ll be working from. It may seem somewhat intimating at first, but getting a basic program going is not too difficult.

From the File menu, select ‘New Project’, then ‘Java Project’ (since we’ll be coding in Java). If for some reason Java Project doesn’t appear in the list, select ‘Project’, and then choose ‘Java Project’ from the list provided there. You should see a dialog something like this:

Enter an appropriate project name (e.g. “TestProject”), and then click Finish. Now, your should have a new empty project to start coding in!

Hover your mouse over the tab named ‘Package Explorer’, i.e. where the ‘TestProject’ item is. You’ll see a small arrow appear next to the label. Click it to expand the contents of the project, and you should see something like this:

There’s two things here. The src folder is where all your ‘source code’ is going to go. Source code is code that you write, whereas binaries are compiled code that the computer runs. The latter goes in a directory called ‘bin’ which is hidden from view. Don’t worry about the ‘JRE System Library’ for now. This contains various ‘libraries’ (i.e. prewritten code that you can refer to from your own) that you might use.

A ‘Hello World’ Program

Many people who start learning a programming language start with a ‘Hello World’ program. This is the simplest program you can imagine: just printing out the words “Hello World!” and then ending. It’s obviously not a particularly useful program, but it’s quite useful to get over the initial program of writing some code in the new unfamiliar language, and getting used to the start-to-finish process of compiling and running the code.

Right click the src folder in TestProject, and select ‘New -> Class’ (see screenshot below).

We’ll be looking at ‘classes’ later, but for now, think of it as a place where we can store items and behaviour associated with one thing in particular (e.g. computing a route on a map, or dealing with a transaction from a customer). You’ll get this dialog:

There’s lots of options here, most of which won’t make sense yet. But there’s information you’ll have to fill out to create the class.

  1. In Name, put the name of your class. For the moment, put ‘MyTestProgram’.
  2. Click the checkbox that says “public static void main” under ‘create method stubs’.

Definition:A ‘main method’ is where the computer looks for code when you ‘point’ it at a particular class. So if you ran MyTestClass, the program would start at the main method, and run whatever code is inside it.

Click ‘Finish’ and abracadabra! You’ll now have a workspace that looks something like this:

What have we got here? Towards the middle of the workspace we have a tab where we can modify the code for our class. On the left in the Package Explorer, we can see our class listed under ‘default package’. We won’t see ‘packages’ till later, but they allow us to group classes with similar behaviour together. Since we didn’t specify a package name, it doesn’t have an assigned package, so appears as ‘default package’.

Let’s just concentrate on the code in our class now. We can see the ‘main method’ inside the class. Most of the line starting “public static void” won’t make much sense at the moment. But the overall effect of this line is to say we have some ‘method’ called ‘main’. Our code goes between the curly braces, i.e. { }.

Starting a line using “//” indicates that the line of code is a comment. Comments allow us to explain what our code is doing, and these lines will be ignored when the program is compiled/run. Comments can span multiple lines, using “/* Your comment here */”. Here, the IDE has put a comment starting ‘TODO’. This comment is just to say that the method has been automatically generated, and we need to insert our code there, because it currently doesn’t do anything.

Remove the comment, and type the following into the code area:

And that’s all folks! We now have a fully-functioning program that we can immediately run.

Running your Program

We want to compile and run your program. Towards the top of the workspace, you’ll see an icon like this: . Click on it, and voila, the IDE will do the work for you. Towards the bottom of the workspace, you’ll see the following very exciting message:

If you see this, it means you program has run successfully. So what is the ‘console’? It’s more or less somewhere where you print text to. You may have heard of the ‘command line’ (known in Windows as the ‘command prompt’), where you can type commands and navigate your file and directories for example. If you were to run your program from the command line rather than in the IDE, you’d see your ‘Hello world!’ message printed there. For the moment, think of it as somewhere were you can show text you want to display. Otherwise, you might display your text in more advanced ways, such as on a user interface, or transmitting it across a network to a display device somewhere else.

At this point, giving our salutary success in greeting the world, we’re going to give the practical side of things a bit of a breather and get some basic programming theory that underpins many programming languages (not just Java!). Once that’s done, we’ll be able to write some actual useful programs!

Part A - Primitive Types and Statements

In computer programs, we can store values in placeholders, called ‘variables’,in exactly the same way as we use variables in mathematics. In maths, these values can usually just be numerical figures. In programming however, we have a number of different types. We say a variable has a particular type, to mean that it holds particular types of values.

Here are the main ‘primitive types’:

Name / Explanation / Example / Length
int / An integer, i.e. holds around number. / -3 / 4 bytes
char / A single ‘character’, i.e. symbol. / ‘e’, ‘!’ (notice the single quotes) / 4 bytes
bool / A ‘boolean’, which is a truth value. / true, false (and nothing else) / 4 bytes
float / Any decimal number (i.e. not necessarily whole) / 1.42f, -6.0f (the ‘f’ at the end is to distinguish it from a double type below) / 4 bytes
double / Again, any decimal number, but we can store double as many digits. / 5.3, 7.4 / 8 bytes
long / Not used as often, but allows us to store very large integer numbers. / 132458l (notice the ‘l’ at the end, to distinguish it from an integer) / 8 bytes

We’ll see some examples of how we can use these in a short while, as well as what we mean by the ‘length’ column in the table.

Statements

A statement in programming simply represents some kind of ‘action’. Such actions might be prompting some procedure to launch a missile, or much simpler things like assigning a value to a variable. You may also have heard of ‘if’, ‘for’ and ‘while’ statements which we’ll get onto later, along with all the other possible actions we might have.

The simplest action is an assignment. This is the process of assigning a variable a value. The ‘syntax’ is this:

typevariableName = value;

Let’s dissect this.

  • The type is whatever type we want the variable to be. e.gint, bool.
  • The variable name can be anything. Convention however (at least for the moment) is that the variable name starts with a lower case letter. A popular convention for naming variables is camel case. This involves capitalising all but the first word in the name. e.g. “stockPriceValue”. Make sure your variable name is descriptive of the value being stored in it, so people reading you code know what it represents. Avoid using numbers, symbols, and you’re not allowed a space.
  • The = in this case does not mean equality. It means whatever is on the right of the equals is assigned to the variable on the left. We’ll see later how we can express equality in the mathematical sense. In many programming languages, assignment is instead written as “:=”, with a colon, so we might have “x:= 2”.
  • Finally we have the value we want to assign to the variable.

In many languages (including Java), we need to put a “;” at the end of the statement to say we’ve finished the particular statement. In other languages (such as Python), the program reading your code can work it out without the semicolon.

Some examples:

  • int x = 4;
  • boolisPresent = true;
  • float stockValue = 4756.35f;

Primitive Types revisited

When you assign a variable, the computer needs somewhere to store the value. We’ll see later that there’s different types of places the computer might store the value.

All variables are assigned either 4 bytes or 8 bytes. 1 byte = 32 bits, where a bit is a 0 or 1 (these are known as binary values). Therefore integers and floats for example are stored using 32 bits. A ‘double’ and ‘long’ variable however is stored using 64 bits, allowing us to store twice as much information. You may wish to read up on what a ‘binary representation’ is to understand this more.

Definition: PRIMITIVE TYPE

A primitive type is one where the value is directly stored in the space assigned for it. This means for example that an int, say 432, can be converted to binary (i.e. 0s and 1s), and this value is put in the 4 byte slot allocated to it.

A ‘String’ is a type that is not primitive. A ‘string’ is simply a sequence of characters, e.g. “hello Bob” to represent some textual value. Just like other variables, we assign 4 bytes to hold the value. However, the string might be very long (e.g. an essay!), so it wouldn’t be possible to store it with just 32 bits. Instead therefore, we store a numerical address (which can think of for example as a house number), which ‘points’ to where the value of the string is actually stored. This therefore is why a String is not a primitive type, because we don’t actually store the value itself in the slot in memory allotted to it.

You might at this point be thinking “Why do we restrict the value of the slots to 4 or 8 bytes? Why not make the slots bit enough to hold the value depending on how long it is? We’ll see the reason when we come on to arrays.

So where are these ‘slots’ to hold values? These are stored on the stack.

While this stuff might seem like very technical detail, there are reasons why it will be important later, when for example we consider equality of non-primitive types.

Operations on primitive types

We can use a number of different ‘operators’ on primitive values. An ‘operator’ is just a symbol used to represent function which takes two arguments. For example, + is obviously an operator which takes two arguments and adds the values together. + is an infix operator because the operator appears between the two arguments (i.e. 3 + 2, not + 3 2).

Some examples:

  • 2 + 3: just addition on integers. Obviously also works on floats and doubles.
  • 2 * 3 and 8 / 4: Multiplication and division. Important note: If you use / on integers, the result is actually the whole number of times the divisor goes into the dividend. e.g. 7 / 3 will give you 2.
  • 7 % 3: The ‘modulus’ operator, which finds the remainder after the divison. In this case, the result will be 1.
  • true & false: The & operator means ‘and’, and is usually applied to Boolean values. The result is true if both the first and second argument is true, and false otherwise. We’ll see how this can be used later.
  • true || false: As above, but represents ‘or’. Gives true if either the first or the second value are true.
  • == This is equality! It takes the two arguments, and give the Boolean ‘true’ if they’re equal, and false otherwise. So 3==4 evaluates (i.e. simplifies) to ‘false’. We’ll revisit equality later.

You might wonder if we can mix operands (i.e. the arguments of the operator) of different types. What do you think happens if we evaluate this:

charmyValue = ‘c’ + 2;

The answer, curiously, is that myValue now holds the value ‘e’. This is because primitive types are ultimately just stored as a ‘number’ (represented in binary). ‘c’ happens to have the numerical value 99 (you will find the corresponding numbers for characters by looking up an ASCII table). 99 + 2 = 101. And since myValue has the specified type ‘char’, it will be interpreted as a character. Conveniently, the numbers representing each of the letters of the alphabet are in order, so 101 gives us ‘e’. So we can perform arithmetic using characters as well as numbers! We’ll see an example program later where we want to print to the screen all the 26 letters of the alphabet using a loop and character arithmetic.

There are some type combos that we are not allowed to combine. For example true + 5is both meaningless and will give us a code error. 2 * 4.03 though (where we’ve combined an integer and a double) is meaningful, and gives us back 8.06 (a double).

More statements

We’ve previously only seen ‘assignment’ as a type of statement. What value does y store at the end of this program?

int x = 3;

x = x + 1;

int y = x * 2;

The answer is 8. On the second line, the assignment first evaluates x+1 using the existing value of x, then updates the value of x with the result of that expression. In this case, we’ve reassigned the value of x. Notice we didn’t have to specify the type of x again on the second line, because we’ve already declared it on the first. Technically speaking, the first line is a declaration (with assignment) where we’re announcing the creation of x, whereas the second line is an assignment.