Course overview: Introduction to programmingconcepts
• What is a program?
• The Java programming language
• First steps in programming
• Program statements and data
• Designing programs.
This part will give an introduction to general programming
concepts, and to the Java programming language.
1
What is a program?
• A program is a set of instructions which control a computer
(laptop, desktop, tablet, etc)
• Programs can be written for huge variety of tasks: performing
complex computations; financial trading; computer graphics
and games; medical diagnosis and data processing; aircraft
autopilot, etc
• Programs can read data from computer keyboard, mouse
movements and actions, from data files, databases and any
other sensors/data sources on the computer – and from
internet if connected.
• Programs can present information graphically on computer
screen, can write to text files, or update any other device
connected to computer – if permitted to do so.
2
What is a program?
Example of simple program:
read a number X;
read a number Y;
calculate Z = (X + Y) divided by 2;
display Z;
This computes average of two numbers, eg: for X = 203, Y = 1965,
displays 1084.
3
What is a program?
• Another name for programs is software – as opposed to
hardware, the physical computer and devices.
• Programs are written in text files in the format of some
programming language
• The most widely-used programming languages are C, C++,
C# and Java.
• We’ll use Java, as it’s simplest of the popular languages.
• Java was invented in 1995, originally for web browsers and
internet software (eg., to animate web pages). Now in general
use.
4
The Java programming language
• We write Java programs in text files (eg., using WordPad or
JCreator), with .java file extension, eg.: Program1.java
public class Program1
{
public static void main(String[] args)
{ int X = 203;
int Y = 1965;
int Z = (X + Y)/2;
System.out.println("The answer is: " + Z);
}
}
Here, three integer-valued variables X, Y, Z are declared. X and Y
are given values 203 and 1965, then Z is calculated from them, and
then displayed.
5
First steps in programming
• Open the Windows console (Start; All Programs; Accessories;
Command Prompt)
• In the Windows console, cd to the directory cllexamples where
Program1.java is (on memory stick)
• Compile the program with javac, and run it with java:
javac Program1.java
java Program1
Alternatively, open Program1.java with JCreator, or use
https://ideone.com
7
First steps in programming
• A Java program in a file Name.java can have the text
public class Name
{
public static void main(String[] args)
{
// Your program code goes here
}
}
The text between the inner {} brackets can change for different
programs.
• Give programs meaningful names: Average.java would be
better name for our first program.
• Program statements: individual instructions and steps the
computer should take.
9
Eg.: int X = 203; “Introduce an integer variable called X,
and assign the value 203 to it”.
int Z = (X + Y)/2; “Introduce an integer variable called Z,
and assign (X + Y) divided by 2 to it”.
Statements end with a ;
Try changing the values assigned to X, Y, re-compile and re-run.
10
First steps in programming
• Of course, a more useful program is one that can read inputs
from user:
import javax.swing.JOptionPane; // dialog support
public class Average
{
public static void main(String[] args)
{ String xvalue =
JOptionPane.showInputDialog(
"Enter 1st integer value:");
int X = Integer.parseInt(xvalue);
String yvalue =
JOptionPane.showInputDialog(
"Enter 2nd integer value:");
int Y = Integer.parseInt(yvalue);
11
int Z = (X + Y)/2;
System.out.println("Their average is: " + Z);
}
}
The dialogs prompt user for the X, Y values.
Input from user is stored in String variables xvalue, yvalue – these
store pieces of text.
Then converted to numbers by Integer.parseInt. Eg., string “334”
is converted to number 334.
12
First steps in programming
• If we enter some wrong data (not integers), our program
crashes – a professional program should be robust & continue
despite errors
• Dialogs can be used to show results:
JOptionPane.showMessageDialog(null, "The result is:
" + Z);
• The User Interface of a program consists of the visual
components used to exchange data between program and users
– in this case the input/output dialogs. Also called Graphical
User Interface (GUI).
14
First steps in programming
Alternatively, read values from console:
import java.util.Scanner; // input support
class AverageConsole
{ public static void main(String[] args)
{ Scanner input = new Scanner(System.in);
System.out.println("Enter 1st integer value:");
int X = input.nextInt();
System.out.println("Enter 2nd integer value:");
int Y = input.nextInt();
int Z = (X + Y)/2;
System.out.println("Their average is: " + Z);
}
}
15
First steps in programming
Average2.java:
import javax.swing.JOptionPane; // dialog support
public class Average2
{
public static void main(String[] args)
{ String xvalue =
JOptionPane.showInputDialog(
"Enter 1st integer value:");
int X = Integer.parseInt(xvalue);
String yvalue =
JOptionPane.showInputDialog(
"Enter 2nd integer value:");
int Y = Integer.parseInt(yvalue);
int Z = (X + Y)/2;
16
JOptionPane.showMessageDialog(null,
"Their average is: " + Z);
}
}
Try changing program to calculate average of three input values.
17
Program Statements
• Programs consist of program statements – individual processing
instructions, operating on variables
• Assignment statements assign a value to a variable:
X = 530;
Can also declare/introduce the variable:
int X = 530;
• Conditional statements enable decisions to be made: if a
condition is true, one behaviour is executed; if condition is false
another behaviour is executed.
19
Max.java:
import javax.swing.JOptionPane; // dialog support
public class Max
{
public static void main(String[] args)
{ String xvalue =
JOptionPane.showInputDialog(
"Enter 1st integer value:");
int X = Integer.parseInt(xvalue);
String yvalue =
JOptionPane.showInputDialog(
"Enter 2nd integer value:");
int Y = Integer.parseInt(yvalue);
int Z;
if (X < Y)
20
{ Z = Y; }
else
{ Z = X; }
JOptionPane.showMessageDialog(null,
"The largest value is: " + Z);
}
}
21
The statement
if (X < Y)
{ Z = Y; }
else
{ Z = X; }
tests the condition X < Y, (‘is X less than Y?’), if this is true then
the statement Z = Y; is executed, otherwise (if X equals Y or is
larger than Y), the statement Z = X is executed.
Effect is to always set Z to be the larger of X and Y.
22
Console version MaxConsole.java:
import java.util.Scanner; // input support
public class MaxConsole
{
public static void main(String[] args)
{ Scanner input = new Scanner(System.in);
System.out.println("Enter 1st integer value:");
int X = input.nextInt();
System.out.println("Enter 2nd integer value:");
int Y = input.nextInt();
int Z;
if (X < Y)
{ Z = Y; }
else
{ Z = X; }
23
Conditions can be as complex as needed, and multiple conditions
can be tested:
import javax.swing.JOptionPane; // dialog support
public class StudentMarks
{
public static void main(String[] args)
{ String markvalue =
JOptionPane.showInputDialog(
"Enter the student’s mark:");
int mark = Integer.parseInt(markvalue);
String result;
if (mark < 40)
{ result = "Fail"; }
else if (mark >= 40 && mark < 50)
{ result = "Pass -- grade D"; }
25
else if (mark >= 50 && mark < 60)
{ result = "Pass -- grade C"; }
else if (mark >= 60 && mark < 70)
{ result = "Pass -- grade B"; }
else
{ result = "Pass -- grade A"; }
JOptionPane.showMessageDialog(null,
"The student’s result is: " + result);
}
}
The symbols && mean “and”.
result is a String variable – it stores a piece of text.
26
Conditional Statements
Examples of different cases:
Input Output
10 “Fail”
42 “Pass – grade D”
55 “Pass – grade C”
67 “Pass – grade B”
70 “Pass – grade A”
Try executing StudentMarks with other example input values.
27
Loop Statements
• Loop statements repeat some instructions over & over again
until a task is completed
• for statements loop for a fixed number of times:
for (int i = a; i <= b; i++)
{ statements }
means ‘execute the statements with i = a, then with i = a+1, i
= a+2, ..., then with i = b’
• If a > b, does nothing
• If a equals b, just one iteration, for x = a.
28
Loop Statements
import javax.swing.JOptionPane; // dialog support
public class SumNumbers
{
public static void main(String[] args)
{ String nvalue =
JOptionPane.showInputDialog(
"Enter the number to sum:");
int n = Integer.parseInt(nvalue);
int sum = 0;
for (int i = 1; i <= n; i++)
{ sum = sum + i; }
JOptionPane.showMessageDialog(null,
"The sum is: " + sum);
}
29
Graphics/drawing example:
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel; // drawing support
public class Drawings extends JPanel
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
for (int i = 0; i < 10; i++)
{ if (i % 2 == 0)
{ g.setColor(Color.PINK);
g.drawOval(10 + i*10, 10 + i*10,
50 + i*10, 50 + i*10);
}
else
32
{ g.setColor(Color.GREEN);
g.drawRect(10 + i*10, 10 + i*10,
50 + i*10, 50 + i*10);
}
}
}
public static void main(String[] args)
{ JFrame app = new JFrame();
app.add(new Drawings());
app.setSize(300, 300);
app.setVisible(true);
}
}
drawOval(x , y ,X ,Y ) draws an oval at x, y position, of size X, Y.
33
Drawing example
Notice that y=0 is at top: y increases from top to bottom, x
increases from left to right.
The condition
if (i % 2 == 0)
is true if i is an even integer (0, 2, 4, 8) – in this case a pink oval is
drawn at position (10 + i ∗ 10, 10 + i ∗ 10).
Condition is false if i is odd (1, 3, 5, 7, 9) – in this case a green
rectangle is drawn at (10 + i ∗ 10, 10 + i ∗ 10).
Try changing the positions & sizes to see the effect.
35
Graphics/drawing example:
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel; // drawing support
public class Drawings2 extends JPanel
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
for (int i = 0; i < 10; i++)
{ if (i % 2 == 0)
{ g.setColor(Color.PINK);
g.fillOval(10 + i*10, 10 + i*10,
50 + i*10, 50 + i*10);
}
else
36
{ g.setColor(Color.GREEN);
g.fillRect(10 + i*10, 10 + i*10,
50 + i*10, 50 + i*10);
}
}
}
public static void main(String[] args)
{ JFrame app = new JFrame();
app.add(new Drawings2());
app.setSize(300, 300);
app.setVisible(true);
}
}
fillOval(x , y ,X ,Y ) draws a filled oval at x, y position, with size X,
Y.
37
Drawing spirals:
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel; // drawing support
public class Drawings3 extends JPanel
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
int centerX = getWidth()/2;
int centerY = getHeight()/2;
int radius = 20;
int w = 2*radius;
int h = 2*radius;
g.drawArc(centerX, centerY, w, h, 0, 180);
int radius2 = 30;
39
g.drawArc(centerX - 20, centerY - 10,
2*radius2, 2*radius2, 0, -180);
int radius3 = 40;
g.drawArc(centerX - 20, centerY - 20,
2*radius3, 2*radius3, 0, 180);
int radius4 = 50;
g.drawArc(centerX - 40, centerY - 30,
2*radius4, 2*radius4, 0, -180);
int radius5 = 50;
g.drawArc(centerX - 40, centerY - 40,
2*radius5, 2*radius5, 0, 180);
}
public static void main(String[] args)
40
{ JFrame app = new JFrame();
app.add(new Drawings3());
app.setSize(300, 300);
app.setVisible(true);
}
}
drawArc(x , y ,w , h, 0, 180) draws an anticlockwise semicircle within
the box from x, y position to x+w, y+h.
drawArc(x , y ,w , h, 0,−180) draws a clockwise semicircle.
41
Summary so far
• Simple program structure: public class Program { ... }
• Variables of integer type (int x;) – these can store values of
integers, eg.: -214, 0, 1, 55, 1000, 500000, etc.
• Variables of String type (String s;) – these can store
strings/text, eg.: “Result”, “Enter a value”
• Assignment statements var = value;
• Conditional statements if (Condition) { statement1 }else { statement2 }
• Bounded loops: for (int var = a; condition; var++) {statement }
• Simple graphics code.
43
More advanced Java
• double variables (rational numbers)
• Unbounded loops (while statements)
• What is programming?
• Multiple operations; recursion
• Multiple classes in a program
• Array variables.
44
Calculations with rational numbers
• double variables can store fractional values: 0.5, 2.25, 0.0001,
etc.
• Java provides functions for square root: Math.sqrt(d), x to
power y, etc: Math.pow(x,y)
• These functions return double values in general – but integers
can be used as doubles (1.0, -3.0, etc).
Example: calculate total amount earned if invest deposit (eg, £100)
for n years at interest rate rate (eg. 5%, or 0.05).
45
Calculating compound interest
deposit grows with interest to: total = deposit ∗ (1 + rate)n after n
years at rate rate.
public class Investment
{
public static void main(String[] args)
{ double amount = 100.0; // total money
double deposit = 100.0; // original investment
double rate = 0.05; // interest rate
for (int year = 1; year <= 10; year++)
{ amount = deposit * Math.pow(1.0 + rate, year);
System.out.println(
"After " + year + " years, total is: " + amount);
}
}
46
}
Amounts after n years:
n amount
1 105.0
2 110.25
3 115.763
4 121.551
5 127.628
6 134.01
7 140.71
8 147.746
9 155.133
10 162.889
47
Calculating compound interest
How many years does it take for investment to double?
Need while loop:
public class Investment2
{
public static void main(String[] args)
{ double amount = 100.0; // total money
double deposit = 100.0; // original investment
double rate = 0.05; // interest rate
int year = 1;
while (amount < 2*deposit)
{ amount = deposit * Math.pow(1.0 + rate, year);
System.out.println(
"After " + year + " years, total is: " + amount);
48
year = year + 1;
}
}
}
A while (E) { C } loop repeats C until E is false – but may run
forever!
Here, termination when year = 15.
Try changing the rate and see the effect on the result.
49
What is Programming?
• Given: a problem (“draw a spiral”, “find how many years it
takes to double an investment at 5% interest”)
• First: idea for solution
• Second: plan an algorithm to carry out the solution
• Third: code up algorithm in a programming language (Java)
• Fourth: test/correct your code.
50
What is Programming?
• Problem to “draw a spiral”
• Idea for solution: draw semi-circles of increasing radius, joined
end-to-end
• Algorithm: draw semi-circle 1 with radius 20, centered on
panel center X, Y; draw semi-circle 2 with radius 30, displaced
to X-20, Y-10, etc.
• Code in Java: use drawArc to draw the semi-circles
• Test/correct the code.
Algorithms can be expressed in words before coding.
51
What is Programming?
• Problem to “find number of years until investment doubles”
• Idea for solution: calculate total amount earned for successive
years, stopping when this amount is at least twice the original
deposit
• Algorithm: compute total earned to year by
amount = deposit ∗ (1.0 + rate)year
for year = 1, 2, 3, ... stopping when amount ≥ 2 ∗ deposit
• Code in Java: use while loop to repeat calculation until the
stopping condition is true
• Test with different rates and deposits.
52
Reading data from files
• Programs can read data from files (usually, text files)
• Eg.: to read student marks and classify these into grades
• Idea is that program reads lines of text from file (should be
numbers), and converts each to a grade, until end of file (eof) is
reached.
53
import java.io.*;
public class StudentMarksFile
{
public static void main(String[] args)
{ File file = new File("marks.txt"); /* default input file */
BufferedReader br;
String s = "";
boolean eof = false;
try
{ br = new BufferedReader(new FileReader(file)); }
catch (FileNotFoundException _e)
{ System.out.println("File not found: " + file);
return;
}
while (!eof)
54
{ try { s = br.readLine(); }
catch (IOException _ex)
{ System.out.println("Reading failed.");
return;
}
if (s == null) // the file has ended
{ eof = true;
break;
}
int mark = Integer.parseInt(s);
String result;
if (mark < 0 && mark > 100)
{ result = "Invalid mark " + mark; }
else if (mark < 40)
{ result = "Fail"; }
else if (mark < 50)
55
{ result = "Pass -- grade D"; }
else if (mark < 60)
{ result = "Pass -- grade C"; }
else if (mark < 70)
{ result = "Pass -- grade B"; }
else
{ result = "Pass -- grade A"; }
System.out.println(
"The student’s result is: " + result);
} // ends the while loop over file
}
}
56
Programs with multiple operations/classes
• So far we’ve written all code in main method of one class. This
is method where execution starts.
• Also possible to write several operations in one class, called
from main method: factorial example.
• For larger programs, best to create separate classes + call their
code from main method.
• We’ll show how to do this with lottery example.
57
Calculating factorials
For integer n > 0, its factorial is product: n ∗ (n − 1) ∗ ... ∗ 1.
public class Factorial
{ public static int fact(int n)
{ if (n <= 1) { return 1; }
else
{ return n*fact(n-1); }
}
public static void main(String[] args)
{ for (int n = 1; n <= 14; n++)
{ System.out.println(
"Factorial " + n + "! = " + fact(n));
}
}
}
58
Recursion is another way of looping: fact(5) calls fact(4), which
calls fact(3), etc. return e; ends the call and returns value of e to
the caller.
59
Calculating factorials
Notice that factorials for n > 12 don’t appear correct: the int type
is too small to represent them, need to use long integer type
instead:
public class Factorial
{ public static long fact(int n)
{ if (n <= 1) { return 1; }
else
{ return n*fact(n-1); }
}
public static void main(String[] args)
{ for (int n = 1; n <= 21; n++)
{ System.out.println(
"Factorial " + n + "! = " + fact(n));
}
60
Programs with multiple classes
• Problem to “Carry out lottery with three numbers in range 1
to 30 for user to guess with five guesses”
• Idea for solution: generate random numbers, ask user to guess
these, and count correct guesses
• Algorithm:
Generate 3 random integers in 1..30;
Ask user for 5 guesses;
Count and display the correct guesses
• Code in Java: use Random class, and nextInt(30) + 1 to
generate the random numbers
• Test with different cases of correct/incorrect guesses.
62
import java.util.Random; // to generate random numbers
import javax.swing.JOptionPane; // dialog support
public class Lottery
{ public static void main(String[] args)
{ Random rand = new Random();
int ball1 = 1 + rand.nextInt(30); // first lottery number
int ball2 = 1 + rand.nextInt(30); // second lottery number
int ball3 = 1 + rand.nextInt(30); // third lottery number
int correct = 0;
for (int i = 1; i <= 5; i++)
{ String sguess = JOptionPane.showInputDialog("Enter your guess:");
int guess = Integer.parseInt(sguess);
if (guess == ball1)
{ System.out.println("Correct guess of ball 1");
correct++;
63
}
else if (guess == ball2)
{ System.out.println("Correct guess of ball 2");
correct++;
}
else if (guess == ball3)
{ System.out.println("Correct guess of ball 3");
correct++;
}
else
{ System.out.println("Sorry, wrong guess!"); }
}
System.out.println("You guessed " + correct + " correct");
}
}
Random is a built-in class, rand is an instance of Random which we
use in our program.
64
Random rand = new Random();
declares rand as variable storing an instance of Random, and
assigns a new instance of Random to rand .
rand .nextInt(30) generates a random integer in the range 0 to 29.
65
Array variables
• So far, we’ve seen variables that store single items – an
individual integer, rational, string, or class instance
• Sometimes useful to have one variable storing group of items –
such as the 3 balls in lottery game
• Array variables store group of items of same kind. Eg.:
int[] balls = new int[3];
declares balls as an array of 3 integers.
• Individual items are written as balls[0], balls[1], balls[2].
66
Lottery with array
import java.util.Random; // to generate random numbers
import javax.swing.JOptionPane; // dialog support
public class Lottery2
{ public static void main(String[] args)
{ Random rand = new Random();
int[] balls = new int[3]; // 3 lottery balls
for (int i = 0; i < 3; i++)
{ balls[i] = 1 + rand.nextInt(30); }
int correct = 0;
for (int j = 1; j <= 5; j++)
{ String sguess = JOptionPane.showInputDialog("Enter your guess:");
int guess = Integer.parseInt(sguess);
68
for (int k = 0; k < 3; k++)
{ if (guess == balls[k])
{ System.out.println("Correct guess of ball " + (k+1));
correct++;
} // end of if
} // end of inner for-loop
} // end of outer for-loop
System.out.println("You guessed " + correct + " correct");
}
}
A loop of form
for (int i = 0; i < n; i++)
{ ... code for array[i] ... }
is often used to process array of size n. Notice that numbering starts
from 0!
Array lottery version has fewer lines of code. Also, easy to change
number of balls.
69
Summary
• Program structure, class definitions
• Variables of integer, rational, string, class instance types
• Array variables
• Assignment, conditional, loop statements
• Simple graphics code.
70
Further resources
We hope you have enjoyed this course. The following are useful for
further study:
• Java JDK can be downloaded from:
oracle.com/technetwork/java/javase/downloads/ Choose
the JDK option, this will provide the javac compiler and java
execution tool.
• JCreator is a visual tool for creating and running Java
programs, download from jcreator.com
• Java library information is here:
https://docs.oracle.com/javase/7/docs/api/
71