DEVTOME.COM HOSTING COSTS HAVE BEGUN TO EXCEED 115$ MONTHLY. THE ADMINISTRATION IS NO LONGER ABLE TO HANDLE THE COST WITHOUT ASSISTANCE DUE TO THE RISING COST. THIS HAS BEEN OCCURRING FOR ALMOST A YEAR, BUT WE HAVE BEEN HANDLING IT FROM OUR OWN POCKETS. HOWEVER, WITH LITERALLY NO DONATIONS FOR THE PAST 2+ YEARS IT HAS DEPLETED THE BUDGET IN SHORT ORDER WITH THE INCREASE IN ACTIVITY ON THE SITE IN THE PAST 6 MONTHS. OUR CPU USAGE HAS BECOME TOO HIGH TO REMAIN ON A REASONABLE COSTING PLAN THAT WE COULD MAINTAIN. IF YOU WOULD LIKE TO SUPPORT THE DEVTOME PROJECT AND KEEP THE SITE UP/ALIVE PLEASE DONATE (EVEN IF ITS A SATOSHI) TO OUR DEVCOIN 1M4PCuMXvpWX6LHPkBEf3LJ2z1boZv4EQa OR OUR BTC WALLET 16eqEcqfw4zHUh2znvMcmRzGVwCn7CJLxR TO ALLOW US TO AFFORD THE HOSTING.

THE DEVCOIN AND DEVTOME PROJECTS ARE BOTH VERY IMPORTANT TO THE COMMUNITY. PLEASE CONTRIBUTE TO ITS FURTHER SUCCESS FOR ANOTHER 5 OR MORE YEARS!

Programming – The Basic Concepts

This topic is about introductory programming – what it is, and how to do it. It’s quite likely you have some programming experience already – but you may not have done any before. To get you started, this chapter is about introducing the basic ideas underlying programming. You may feel you can skip this if you know it already (but I don’t promise it won’t form the basis of an exam question).

First…

“Accuracy is the enemy of Pedagogy” – Richard Feynman I’m going to shamelessly “lie” to you sometimes – by that I mean I’m going to skip over some details to make the key concepts clearer. For example, I’m going to tell you that: All Java programs need to be stored in files with the same name as the program. Now this isn’t strictly true – but it’s what in practice you need to do to start with to get things to work. And there will be more cases like this. Sorry – but it’s better than swamping you with all the details right at the start. (And, to be honest, it’s what’s been happening for your entire education so far anyway.) To Be a Programmer You Need to Practice! Programming is a practical skill. You would not expect to be able to read a few books on football (and maybe go to some lectures) and be a good footballer – the same is true about programming. What is a Computer? Tricky – and lots of definitions depend on how a computer works. In practice there are many ways to build a computer (though they are nearly all based on one underlying model these days) so this is unhelpful. But we can step back and think about this more abstractly and consider not how it works but what it does and how you use it.

Computing Devices with One Function

Like this (Q: what is it?) The mechanical calculator of Blaise Pascal (1623 – 1662: the programming language Pascal is named after him) designed in 1642, or even modern non-programmable calculators. These perform a set of predefined functions which you cannot change – not a computer. Computing Devices to Perform one Parameterizable Function Like the mechanical looms of Joseph Jaquard (1752 – 1834) controlled by punched cards which could produce astonishingly complex designs.

General Purpose – Programmable in Hardware

Like ENIAC (1946, University of Pennsylvania) which could in principle perform any task a modern computer can, modulo speed and memory limits. But it was programmed by plugging in cables and manipulating switches – so a computer but not as we understand them today.

General Purpose – Programmable in Software

Modern computers – starting from EDSAC (Cambridge, 1948) – do not require any hardware changes to program them. They are programmed entirely by patterns stored in the memory of the machine – patterns expressed in some language. Initially these languages were very basic – 1s and 0s, followed by other numbers, and then simple symbolic languages (you will see one called PEP-8). Eventually these were replaced by more sophisticated high-level languages which we use today. Java – which we will use – is one of these: specifically it’s an object oriented language (the meaning of this will become clear near the end of the topic). What is a Program?

A program is usually a system that: - Reads in ‘input’ of some form - Performs some computation based on that input and some stored data - Generates ‘output’ of some form - Updates (some of) its stored data We tend to think of programs as running on ‘traditional’ computers, but some of the easiest examples are often not like that. That’s one of the reasons we put ‘input’ and ‘output’ in quotes – they don’t have to be things you type in, or that are read from files.

Pedestrian Crossing Traffic Lights The ‘inputs’ to a pedestrian-controlled traffic crossing are: - The buttons pedestrians can press, on either side of the road - (Optionally) sensors that detect traffic The ‘outputs’ are: - The colours of the traffic lights - The colours of the pedestrian crossing indicators. The stored data is: - The current colour of the traffic lights - The current colour of the pedestrian crossing indicators - The status of the buttons (have they recently been pressed or not) - (Optionally) data on how much traffic has passed the lights recently - (Optionally) how long ago did the lights last change The program that runs the lights reads the inputs and the value of the stored data and, depending on that stored data and any inputs, updates the stored data and (possibly) changes the outputs. For example, in a very simple case: - A set of lights might be generating outputs of: - Traffic lights green - Pedestrian lights red - With stored data showing that the traffic lights are green and the pedestrian lights are red; and that the button has not been pressed. - If the button is pressed, the stored data is updated to reflect that. - The change of stored data – the button being pressed – triggers the program to make other changes - It first changes the traffic light (stored data and output) to Amber (yellow) - Next it changes the traffic light (stored data and ouput) to red - Finally, it changes the pedestrian light (stored data and ouput) to green - At some point in the future, further changes happen to change the lights back to their original outputs.

Vending Machine Another, similar, example is a vending machine. - Inputs are coins and button presses - Stored data is how much money has been entered by the customer - Outputs are goods (drinks, sandwiches etc.) and messages to the customer

Variables and State

The stored data in a program is a key concept – it’s what allows a program to perform actions that not only depend on what is going on now (inputs) but what has happened in the past (previous inputs) – because it allows us to store those inputs (or, more usually, data computed from those inputs). We use the term state to refer to the whole set of stored data a program is dealing with. Most of the time however, we are not dealing with all the stored data (or state) – but just some bits of it. Each individual part of the state of a program is called a variable. The programs we write are sets of rules that tell us how to read inputs and the values of variables, and to generate outputs and update the values of those variables.

Programming Languages

Computer programs are written down using specialized sets of rules called programming languages. There are now thousands of these in existence – though many are very specialized; and many are obsolete. The reason we use specialized programming languages and not just English (or any other natural language) is that natural languages are simply too imprecise to express the rules we need. For example:

I saw a man on a hill with a telescope

Who has the telescope. There’s also:

Time flies like an arrow, fruit flies like a banana

(Not actually ambiguous to humans but probably a bit tricky for machines.) Some of these programming languages are, as said, very specialized and only used for a narrow range of tasks. Others are more general, and some of these are more popular than others.

Java

The language we will use is Java. I don’t intend to go into lots of history about Java – there is plenty available in texts and online. But Java is a good balance between being easy to learn and industrially useful (that is, you can quite happily get a job writing code in Java – something that isn’t true for languages that are meant only for teaching people to program). There are also lots of resources available for Java programming, which is another reason why we picked it. However, you should not think of this topic as being about learning to program in Java; but more about learning to program. At the end of it, you should be able to learn a new programming language pretty quickly (helped by the fact that many of them use very similar notations – or syntax – to Java).

Note: some example programs are from, or based on, examples from Java for Everyone (C Horstmann), the course text.

In this chapter, we’ll look at some of the basic concepts of programming and how they apply to Java. We’ll skip over some details – the point is to get the overall idea. This is the first of several chapters that cover key points.

Programming is about systems that process input data and generate output results. The simplest ones simply read in input data, do something to it, and generate an output. The very simplest ones just generate output. For example, here’s the output of a program that just prints ‘Hello World!’:

Hello World!

(In the examples I show, code and computer input-output will be in the Courier font. Output from computers will be bold; input will be italic.)

The Code: What does this look like in Java?

We’re going to show the code for all the simple examples we introduce. As we move on, we will explain more about what each line means. However for now quite a few bits of the text of the programs we show have to be taken on trust. By the end, you will understand all the terms we use.

class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World!");
	}
}

In this example, the line:

System.out.println("Hello World!");

is the one that actually generates the output. So what do all the others mean? They set up the necessary framework for the program to actually work – and we’ll skip most of the details for now – but see KEY POINT below.

We read out the bit System.out.println “System dot out dot print line” and it prints the data that follows it in brackets to the screen.

  KEY POINT: Program Names & File Names We can ignore most of the meaning of the lines other than:

System.out.println("Hello World!");

for now. But one thing we do need to know is that in the line:

class HelloWorld {

“HelloWorld “ is the name of the program. And this program MUST be saved in a file called HelloWorld.java 

Make sure you know and understand the following points. - You can call a program whatever you want – the computer pays no attention really and does not care. The most important point is that it is meaningful to people. Calling a program “Lemon” will work, but it won’t help someone reading the program to understand it. - There are also some conventions on how you should name things in Java – we’ll get back to this later on. - Case matters - depending on what computer operating system you are using the case of the filename might not have to match the case of the identifier (i.e. you might be able to call your program “HelloWorld” and store it in a file called “helloworld.java” – but it is always safer if they match). - The name HelloWorld is an identifier – see below.

Advanced Aside

Strictly speaking we are naming something called a class here – and later we’ll see that programs can have more than one class (and more than one file containing them). But for now, with our simple programs all in one class (and file) we can just think of this name as the program name. Syntax: Reserved Words, Identifiers, Literals The language we use to write down programs in Java (or any language) is called the language syntax. Each programming language has it’s own syntax and rules (some are quite similar to Java and some are very different). You have to get the syntax of a program exactly correct before you can compile it - turn it into code the computer can run. For example, it matters that there is a “;” on the end of the line:

System.out.println("Hello World!");

And that the “{“…”}” are present in the right place. We’ll get back to the details of how to do this later, but for now we are going to concentrate on three things: - Reserved Words: These are words that form part of the Java language itself, and have specific meanings. In the example above, class, public, static and void are reserved words. You should not try to use these words in any other way (things are unlikely to work if you do) – so, for example, don’t try to call your program “static”, or “void”. (I know we haven’t explained what these particular words mean – we will do this later on.) - Identifiers: These are words that represent, or stand for, something – and which you or some other programmer has chosen. The one we’ve talked about so far is “HelloWord” – but there are others too. For example, “String”, “args”, “main”, “System.out.println” (the last one is actually three separate identifiers but don’t worry about that for now). Of these identifiers, “String” and “System.out.println” are names chosen by the programmers who wrote some of the libraries of code that we can use with our programs; “main” was chosen by the original Java designers; and “args” is something we can actually change if we want to something else (but don’t – everyone uses “args” because it’s a convention). - Literals: The only other piece of text in our program is “Hello World!” – this is not a reserved word or an identifier but a literal. It doesn’t represent anything: it is the sequence of characters (or String) Hello World!. Not all literals appear in “” marks as we’ll see later (for example, numbers).

To sum up, here’s the program again colour-coded to show the different parts:

class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World!");
	}
}

  Indenting and Layout One thing to notice about our program so far is that some of the lines are indented – that is, they don’t start at the left-hand margin.

class HelloWorld {
|----| public static void main(String[] args) {
|----| |----| System.out.println("Hello World!");
|----| }
}

The “{“ and “}” mark the beginning and end of blocks of code and are the way we logically group lines of code together.

In the version above, “|—-|” stands for the tab character: after each “{“ in the program, the lines following start one tab further from the left; after each “}” they start one fewer tab from the left. (Don’t actually type the “|—-|” in – they are just to show were the tabs go.) We do this to make the program more readable to humans. This version would also work perfectly well:

class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

In fact, so would this:

class HelloWorld {public static void main(String[] args) {System.out.println("Hello World!");}}

But it’s very difficult to read. This leads on to an important KEY POINT.

KEY POINT: Programs are Read by People Although we write our programs using a strict syntax and follow strict rules so that they can be understood by computers, the most important readers are people.

This means we must write programs in a readable way – it’s why we use indenting to make the layout clearer (and sometimes put in blank lines too). It’s why we pick meaningful names for identifiers. We also do other things too – as we’ll see as we go along.

KEY POINT: You WILL Forget What Your Code Means… Unless you lay it out properly, pick meaningful names (and do the other things we’ll see later).

It’s not just about other people reading your code – it’s you. I guarantee at some point you will forget what your own code means (after leaving it for a few weeks, usually). This is one of those things nobody seems to believe – we all have to find it out for ourselves. Indenting and Laying-Out Code – A Choice I’ve shown you one style of laying-out code in the example so far, but there is another one. Here is the same program in the two different styles.

 class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World!");
	}
}
class HelloWorld
{
	public static void main(String[] args)
{
		System.out.println("Hello World!");
	}
}

The only difference is where we put the “{“ characters. In the first version: - The “{“ goes at the end of the line before. - The closing “}” goes under the first character of the line above. In the second version: - The “{“ goes on the start of the line above (immediately below the first character on the line above). - The closing “}” goes directly under the matching “{“. Both of these are fine and are allowed by the Java conventions – you can do either (it’s a matter of preference). But choose one and stick to it – don’t mix (at least in the same program).

Depending on how you’ve chosen to run your programs, you may find the software you use does this for you (or you can tell it to). But if it does, make you sure understand how to do it manually (you won’t have software to do it for you in the exam for example).

KEY POINT: Layout and Readability Count! In case you’re thinking “yeah, yeah…” about all this layout, readability and meaningful names stuff – there are real marks for this in the assessment! And employers usually have rules about it too. Running the Program – “Lots of Rules and No Mercy…” (For this section, you need to have chosen a way to run your Java programs, as described in the chapter “Running Java Programs: Your Choices” and the supporting videos.)

Using the software of your choice, type in the “Hello World!” program, and compile and run it.

Sounds simple – but you will probably find that you make mistakes typing it in and get to see compiler errors. For example, if we type in this:

class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World!")
	}
}

(Can you see the mistake?) You’ll get this:

HelloWorld.java:3: error: ';' expected
		System.out.println("Hello World!")
		                                  ^
1 error

And if you type in this:

class HelloWorld {
	public static void main(String[] args) {
		system.out.println("Hello World!");
	}
}

(Again, can you see the mistake?) You’ll get this:

HelloWorld.java:3: error: cannot find symbol
		System.out.Println("Hello World!");
		          ^
  symbol:   method Println(String)
  location: variable out of type PrintStream
1 error

In both cases the errors are small (missing “;” in the first one – a “P” instead of a “p” in the second). You might think these do not matter but they do. Programming languages are very sensitive to syntax errors and you must get it right. So look carefully at what you’ve typed and compare it with the examples in this chapter – and then type them exactly.

(If you are wondering how you will ever remember all this stuff don’t worry – everyone worries about that and the vast majority of people manage it pretty quickly.)

After that you can run the program – in the case of Hello World, it’s very likely to work and the problems you have will mostly be with the syntax. But in most real programs, once you’ve got the hang of the syntax, the problem is that they do run, but don’t output what you expect – which is when you start debugging (more later). Statements Programs in Java (and most languages) are made up of collections of statements – bits of text that mean something in Java. For example,

System.out.println("Hello World!");

is a simple statement in Java. Like most statements in Java, it ends with a “;”. This might seem unnecessary, but it is possible to put more than one statement on a line, and the “;” is a ‘traditional’ end-of-statement character in many languages. Two things: - You Might Forget the “;” – it’s a common error to start with, particularly if you’ve programmed in a language that does not use it (e.g. Visual Basic). - Not all Statements Use It – We’ll see this later on, and it can be a nuisance.

Statements like this are simple statements – a single thing on it’s own. Very commonly we want to group statements together, to make compound statements. We do this by surrounding the statements we want to group with “{“ and “}”. You can examples of this in the Hello World program – it’s not obvious there why you need to group things, but as we get to see more complex programs, it will become clearer.

Some statements in programs tell the computer to actually perform some operation; others tell the system something about the program that it needs to know to build a running program. In the program above, only the line

System.out.println("Hello World!");

actually performs an operation.   EXERCISES • Try changing Hello World so it prints different things. • Try changing it so it prints more than one thing. • Try renaming it and seeing what happens; try fixing it. • Try making mistakes in the syntax (if you didn’t already when you typed it in) and see what the messages look like.

A Program With Input

Obviously “Hello World!” is ridiculously basic – for one thing, it always does the same (not very interesting) thing. How about a program that accepts some input and does something with it?

For example, here’s a simple dialogue with a program that asks you your name and then says hello:

What is your name?

Bob

Hello Bob!

Lets think about the sequence of events going on here – the Algorithm that the program must implement.

1. Step 1 – Print out message “What is your name?” 2. Step 2 – Read in input from user and store it 3. Step 3 – Join user input with “Hello “ and “!” and output result

The KEY POINT for us here is storing data – because we need to do that in this program.

KEY POINT: Variables Computers store data in memory, and computer memory is just a very long list of numbered ‘boxes’ in which you can put that data. But it’s very difficult to deal with memory directly. There are usually billions of these numbered boxes (so dealing with the numbers – or memory addresses – is difficult for humans); and also your program might not end up in the same bit of memory every time it runs (so the numbers can change). We fix this by using names for the data we store, and letting the computer work out which memory ‘boxes’ to put it in. We just worry about the names.

The names we use are another example of identifiers. But this time instead of identifiers that name programs we are talking about identifiers that name stored data – we usually call these identifiers variables.

A Program With Input

Obviously “Hello World!” is ridiculously basic – for one thing, it always does the same (not very interesting) thing. How about a program that accepts some input and does something with it?

For example, here’s a simple dialogue with a program that asks you your name and then says hello:

What is your name?

Bob

Hello Bob!

Lets think about the sequence of events going on here – the Algorithm that the program must implement.

1. Step 1 – Print out message “What is your name?” 2. Step 2 – Read in input from user and store it 3. Step 3 – Join user input with “Hello “ and “!” and output result

The KEY POINT for us here is storing data – because we need to do that in this program.

KEY POINT: Variables Computers store data in memory, and computer memory is just a very long list of numbered ‘boxes’ in which you can put that data. But it’s very difficult to deal with memory directly. There are usually billions of these numbered boxes (so dealing with the numbers – or memory addresses – is difficult for humans); and also your program might not end up in the same bit of memory every time it runs (so the numbers can change). We fix this by using names for the data we store, and letting the computer work out which memory ‘boxes’ to put it in. We just worry about the names.

The names we use are another example of identifiers. But this time instead of identifiers that name programs we are talking about identifiers that name stored data – we usually call these identifiers variables.

Computer Science


QR Code
QR Code programming_basic_concepts_java (generated for current page)
 

Advertise with Anonymous Ads