lecture1_4up.pdf
Document Details
Uploaded by PreferableSard
The University of Sheffield
2023
Tags
Full Transcript
Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1a Your First Java Program COM1003 Java Programming • This lecture assumes – You know nothing about programming • This lecture will – Introduce the Java programming language Dr Siobhán North – Explain how to write a simple program that...
Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1a Your First Java Program COM1003 Java Programming • This lecture assumes – You know nothing about programming • This lecture will – Introduce the Java programming language Dr Siobhán North – Explain how to write a simple program that prints something out Department of Computer Science The University of Sheffield Computers and programming A Computer Program • A computer is a machine with, amongst other things, a microprocessor and a memory store • The computer program’s instructions are written in a language called a • A computer program is a set of instructions a computer that it can follow in order to carry out a task • You are going to learn a language called • Computers only understand instructions in the form of binary numbers © The University of Sheffield programming language Java • Writing programs is what this course is all about 1 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1a Algorithms • Computer programs are written to solve problems • To solve a programming problem, we need a step-by-step specification of how to get to the solution • This specification is called an algorithm Example algorithm This algorithm for grocery shopping is written in English-like ‘pseudocode’ 1. Get a trolley 2. While there are still items on the shopping list 2.1 Get an item from the shelf 2.2 Put the item in the trolley 2.3 Cross the item off the shopping list 3. Pay at the checkout Is this algorithm correct? Is it unambiguous? How might it fail? © The University of Sheffield Algorithms • An algorithm specifies what the program should do but it isn’t the program • It may be expressed in English, or in a more formal language • But it should produce the right answer, only the right answer and then stop High-level programming languages • An algorithm is written in psudocode • Computers only understand binary numbers • A program, based on an algorithm, is written in a high-level language • Programs must be converted to machine code, made up of 0s and 1s before they can be executed (obeyed) 2 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1a Converting Algorithms to Programs Algorithm Programmer This isn’t quite how Java works but it is a reasonable approximation for the moment /* A simple Java program Written by: Siobhan */ public class Simple { High level program code public static void main(String[] args) { System.out.println("Hello"); System.out.println("World!"); } Machine code Compiler } This is the whole point Obeyed by a computer The Class /* A simple Java program Written by: Siobhan */ public class Simple { A simple Java program This program would be written using a text editor and saved in a file with the name Simple.java The main method The name of a class The start of the class /* A simple Java program Written by: Siobhan */ public class Simple { public static void main(String[] args) { System.out.println("Hello"); System.out.println("World!"); } } The end of the class The simplest Java program consists of a single class saved in a file called by the name of the class with the suffix .java © The University of Sheffield A method called main public static void main(String[] args) { System.out.println("Hello"); System.out.println("World!"); } } The end of the method The start of the method Statements The simplest Java program consists of a single public class with a single method which is always called main 3 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1a The statements The statements public class Simple { public static void main(String[] args) { System.out.println ("Hello"); System.out.println ("World!"); } } public class Simple { public static void main(String[] args) { System.out.println ("Hello "); System.out.println ("World!"); } } • Text in red in the program above is standard to all programs • Statements normally end with a semicolon and are normally obeyed in order, top to bottom • The statements dictate what the program does and in what order Two println statement System.out.println ("Hello "); System.out.println ("World"); Hello World! The println method All character strings start and end with double quotes Hello World! • The println method is called twice with different parameters • It always prints something followed by a line break but what it prints depends on the parameter between the brackets System.out.println(); • This prints a blank line © The University of Sheffield • The output is Method name Character string System.out. println ("Hello"); An object name Method parameter (or argument) Invokes a method of the object All method calls are followed by a pair of brackets containing any parameter(s) 4 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1a Two “Identical” Programs /* A simple Java program Written by: Siobhan */ public class Simple { Comments /* A simple Java program Written by: Siobhan */ public class Simple { public static void main(String[] args) { public static void main(String[] args) { System.out.println("Hello"); System.out.println("World!"); } System.out.println("Hello"); System.out.println("World!"); } public class Simple { public static void main(String[]args) { System.out.println ("Hello "); System.out.println ("World!"); } } } Comments • Comments are either – enclosed between the symbols /* and */ or } • Comments are for human readers only; they are ignored by the compiler Layout matters /* A simple Java program Written by: Siobhan */ public class Simple { • They are important © The University of Sheffield Two more identical programs public static void main(String[] args) { System.out.println("Hello"); System.out.println("World!"); } – follow the symbol // on the same line and end when the line ends • A good program should be human readable A comment } public class Simple{public static void main(String[] args){System.out.println("Hello");System.out.println( "World!");}} 5 Dr Siobhán North Human readable Java programs COM1003 Java programming 2023/4 Lecture 1a Compiling and running java • Lines between matching { and } should be indented • Write your program in a text editor and save it with the right file name • Blank lines and spaces (except in the middle of words, numbers or character strings) are also ignored but help readability • Compile it using the Java Development Kit (JDK) U:…>javac Simple.java • Readability helps avoid errors • If nothing goes wrong, a file called Simple.class will be created • Readability improves marks • To run it type Errors • Most of the details described above matter; if you get them wrong your program will not compile – it will not be transformed into something the computer can obey • Layout matters too but won’t cause errors though it will cost you marks • Even if your program compiles it can still give the wrong answer © The University of Sheffield U:…>java Simple Dealing with errors • If we remove the semicolon at the end of line 7 of our program, the compiler stops with the following error message: It tells you what line it spotted the error on What it thinks is the problem U:…> javac Simple.java Simple.java:7: error: ';' expected System.out.println("Hello") ^ 1 error And points to the first character it thinks is wrong 6 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1a Dealing with errors • Sometimes compiler messages are not so clear. If we remove the first quote from line 7 we get this U:…>javac Simple.java Simple.java:7: error: unclosed string literal System.out.println(Hello"); ^ 1 error When you get multiple errors always correct the first one first © The University of Sheffield Summary of key points • The simplest Java program consists of a class containing a main method which contains statements to be obeyed in order and is stored in a file with a name that matches that of the class • It must be compiled before it can run and if it can’t run it is useless • Nevertheless human readability is important 7 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1b Variables, identifiers and types • This lecture assumes Variables – You have already been through the Introduction to the Module slides • Computer programs store and manipulate information such as numbers and words – You have written and run your first Java program • A Variable acts as a named storage box for a particular piece of information • This lecture will – Introduce variables – Explain Java identifiers and two basic types Variable declarations • Values can be put into the box (variable) and retrieved when necessary Java Identifiers • Every variable a program uses has to be declared • Java identifiers are a string of characters starting with a letter • A Variable Declaration • The identifiers can only contain – Creates space to store the variable’s value (a storage box) – Gives it (the box) a name – an identifier – Restricts the type of information that can be stored in the metaphorical box © The University of Sheffield – Upper and lower case letters – Digits – Two other characters; “_” and “$” • They never contain spaces • They are case sensitive 8 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1b Java Conventions Variable Identifiers • There are rules and there are guidelines and you must observe both • Variable identifiers start with a lower case letter • The guidelines mean that you can tell what sort of thing an identifier identifies just from how it is written • Contain only letters and digits • Are written in camel case • But the most important guideline is that identifiers should be meaningful Camel Case Variable Types • Variable identifiers must be meaningful • Every variable has a type, the type of the value it holds • Often meaningful identifiers consist of more than one word • Words other than the first start with a capital letter e.g. – numberOfBooks – distanceInMiles – dayOfMonth © The University of Sheffield • For instance numbers can be – integers (whole numbers such as 42) – real numbers (contain a decimal point, such as 3.141592) • In Java we use int for integers and double for real numbers 9 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1b Variable declarations Assignment • This declares the variable heightInInches • Once the variable has been declared this sets its value to 72 int heightInInches; • It creates space to store an integer and associates the identifier heightInInches with the storage space • It is not the same as heightinInches Declaration and assignment heightInInches = 72; An Assignment • And then this will print out 72 System.out.println(heightInInches); because we refer to a variable’s value by its identifier Declaration and assignment • A variable is only declared once, although its value can be changed many times • We can assign values to variables as we declare them double length = 4.5; • Variable values are changed by assignment as often as we need to • And declare multiple variables of the same type at once • The assignment operator is =, which should be read as ‘takes the value of’ int heightInInches, heightInCms; • With initial values Note comma int heightInInches=72, heightInCms=183; © The University of Sheffield 10 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1b Example - the area of a field Variable & Class Identifiers class names start public class CropArea { with an upper public static void main(String[] args) { case letter //The dimensions of the field double width = 3.2; double length = 7.8; Multiplication sign // compute the area double area = width * length; Like println but without the line break afterwards // write the result System.out.print("Your field has an area of "); System.out.print(area); System.out.println(" metres squared."); } } Your field has an area of 24.96 metres squared. Reserved words • Both must be meaningful • Both can only contain letters and digits • Both use upper case letters to indicate the start of a new word • Variables names start with a lower case letter • Class names start with an upper case letter Summary of key points These words cannot be used as identifiers – jEdit can help you recognise them • Variables can be thought of as named boxes that can contain values of a specific type abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, double, do, else, enum, extends, false, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while • The two types we have seen are int and double © The University of Sheffield • Variable identifiers are alphanumeric, start with a lower case letter and are in camel case • Class identifiers are the same but start with a capital letter 11 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1c Arithmetic Assignments and Expressions • This lecture assumes • This statement (proceeded by a comment) – You have already been through the Introduction to the Module slides – You have written and run your first Java program – You can declare and use a variable • This lecture will // compute the area double area = width*length; is a declaration and an assignment but the value assigned is calculated • The assignment operator can have complicated arithmetic expressions on its right but it always has a single variable name on the left – Show you how to do arithmetic Expressions and arithmetic operators Integer division • We form expressions using arithmetic operators: • The / operator gives different behaviour for int and double: int int int int int int y a b c d e = = = = = = 10; y+2; y-3; y*4; y/5; y%6; % //afterwards //afterwards //afterwards //afterwards //afterwards a b c d e is is is is is 12 7 40 2 4 operator works out the modulo • The (remainder) © The University of Sheffield int count = 17; double size = 17.0; System.out.println(count / 2); //prints out 8 System.out.println(size / 2); //prints out 8.5 • Integer division truncates the result System.out.println(count / 9); //prints out 1 • Integer division only happens if there is an integer on both sides of the / 12 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1c Example - wall paper and carpet public class WallPaper { Example - wall paper and carpet again public class WallPaper { public static void main(String[] args) { int length=2, width=4, height=5; int length=2, width=4, height=5; int carpetSize, wallpaperSize; int carpetSize, wallpaperSize; // do the calculations // do the calculations carpetSize = length*width; wallpaperSize = 2*height*(length+width); carpetSize = length*width; // print the result wallpaperSize = 2*height*(length+width); System.out.print("Your room needs "); // print the result System.out.print(carpetSize); System.out.println("Your room needs " + carpetSize + System.out.println(" square metres of carpet and"); " square metres of carpet and"); System.out.print(wallpaperSize); System.out.println(wallpaperSize + " square metres of wallpaper"); System.out.println(" square metres of wallpaper"); } } The + sign behaves differently if there is a character string on either side too; it concatenates instead of adding public static void main(String[] args) { Your room needs 8 square metres of carpet and 60 square metres of wallpaper } } Your room needs 8 square metres of carpet and 60 square metres of wallpaper Precedence rules Some Examples • Java decides the order in which operations are carried out within calculations according to Pause the lecture now if you want to test yourself because the answers are on the next slide precedence 1. Anything in brackets 2. Multiplication, division and modulo 3. Addition and subtraction • Where operators have the same precedence (e.g. *, / , %) it works left to right • When in doubt, use extra brackets! © The University of Sheffield int a=3, b=4, c=5; one = 2*a+b; two = 2*((a+b)*-c+2); three = -a*b/c*a; double x=2.0, y=1.2; four = -x*y/x*y; 13 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1c Some Examples Short form notation int a=3, b=4, c=5; one = 2*a+b; one = 10 because 2*3= 6, 6+4=10 two = 2*((a+b)*-c+2); two = -66 because 3+4=7, 7*-5=-35, -35+2=-33, 2*-33=-66 three = -a*b/c*a; three = -6 because -3*4=-12, -12/5=-2, -2*3=-6 double x=2.0, y=1.2; four = -x*y/x*y; four = -1.44 because -2.0*1.2=-2.4, -2.4/2.0=-1.2, -1.2*1.2=-1.44 • A variable can appear on both sides of an assignment because Java works out the value on the right of the assignment before assigning it to the variable on the left • So this means before sum = sum+2; sum becomes 2 more than it was • There is a short form meaning the same thing sum += 2; Short form notation Summary of short form notation • To add one to a variable, we can write Long form Short form x = x + 3; x += 3; x = x - 7; x -= 7; x = x * 2; x *= 2; x = x / 4; x /= 4; x = x % 6; x %= 6; x = x + 1; x++; x = x - 1; x--; count++; • Similarly, to subtract one from a variable: count--; © The University of Sheffield 14 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1c Numeric Types Numeric Types • The type of a variable is important in arithmetic expressions • The type of a variable is important in arithmetic expressions int i=14; // i takes the value 14 i=i/5; // i takes the value 2 double d=14; // d takes the value 14.0 d=d/5; // d takes the value 2.8 • So is the type of a literal value – a number which appears directly in the program int i=14/5; double d=14/5; double e=14/5.0; // i takes the value 2 // d takes the value 2.0 // e takes the value 2.8 • If the number has a decimal point it is a double otherwise it is an int Mixing types Changing types • Care is needed when using expressions with mixed types: • We can explicitly change the type of an expression using a cast int first=12, second=9; double average = (first+second)/2; puts 10.0 in average because of integer division. • To fix this, we can force real division: double average = (first+(double)second)/2; • A type name in brackets before an expression changes its value into the named type • These would work just as well double average = ((double)first+second)/2; double average = (first+second)/2.0; double average = (double)(first+second)/2; © The University of Sheffield 15 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1c Truncation and Rounding Summary of key points • When a real number is assigned to an integer it is truncated – its decimal part is removed • Java can do arithmetic using +, -, *, / and % • If you want to round it to the nearest integer use Math.round(..) • But be careful of precedence and use brackets if you need to • Division and addition behave differently depending the type of their operands int a; double d = 2.9; a = (int)d; //d is truncated; a is 2 a = (int)Math.round(d); //d is rounded; a is 3 • We will come back to © The University of Sheffield • % means modulo or remainder Math later • Literal numbers become doubles if they have a decimal point and ints otherwise • You can change types with a cast 16 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1d Constants Constants v. Variables • This lecture assumes • Values that can never change should be named and declared as constants not variables – You have already been through the Introduction to the Module slides – You have written and run your first Java program – You can declare and use a variable – You know how to use the arithmetic operators in Java • This lecture will – Introduce constants Declaring constants • Constant declarations are preceded by the reserved word final • Their identifiers (as always meaningful) use upper case letters, digits and the underscore character starting with an upper case letter; the underscore is used to indicate gaps between words final double FEET_TO_METRES = 0.3048; … widthInMetres = widthInFeet * FEET_TO_METRES; © The University of Sheffield final double FEET_TO_METRES = 0.3048; … widthInMetres = widthInFeet * FEET_TO_METRES; • The ratio of feet to metres is never going to be any different to its value today so it is a constant Example – using constants public class FeetInches { public static void main(String[] args) { final double CM_PER_INCH = 2.54; final int INCHES_PER_FOOT = 12; int numFeet = 3; int numInches = 2; double numCm = CM_PER_INCH * (numInches + numFeet*INCHES_PER_FOOT); System.out.println(numFeet + " feet and " + numInches + " inches is " + numCm + " cm"); } } 3 feet and 2 inches is 96.52 cm 17 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1d Constants aid readability Constants help avoid errors • A meaningful identifier makes the program more readable • You only have to type a long number once final double FEET_TO_METRES = 0.3048; … width = originalWidth * FEET_TO_METRES; height = originalHeight * FEET_TO_METRES; • Rather than width = originalWidth * 0.3048; height = originalHeight * 0.3048; final double FEET_TO_METRES = 0.3048; however often you use it • Which can be important final int THE_SPEED_OF_LIGHT = 299792458; final double PI = 3.14159265358979323846264338327950288419716939935 ; final int DISTANCE_TO_MOON = 384402; But is increasing.. Constants can change but.. Variables do change • Only use them for values that change rarely or slowly and not within a run of the program • But so far ours haven’t changed much • The VAT rate does change but not often and double taxPayable = price*VAT_RATE; is more understandable than double taxPayable = price*0.20; • A program that works out what 3’ 2’’ is in cms isn’t very useful • One that works for any combination of feet and inches might be better • But for that we need to read values in and that is what next week is about but… • You can use VAT_RATE multiple times and if it does change you only need to change one, easily recognized, line of your program © The University of Sheffield 18 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1d Input from a GUI Running the program • We won’t look at graphical user interfaces properly until next term but this approach is too useful to omit import javax.swing.JOptionPane; public class PintsToLitres { public static void main(String[] args) { final double PINTS_TO_LITRES = 0.568261; int pints = Integer.valueOf( JOptionPane.showInputDialog("How many pints?")); double litres = pints * PINTS_TO_LITRES; System.out.println(pints +" pints is " + litres +" litres"); } } Using JOptionPane Using JOptionPane for doubles • There are two important lines in this program; • We still need this at the start • The first line, even before the class name must be import javax.swing.JOptionPane; import javax.swing.JOptionPane; • And then the line that reads in the value is • And then the line that reads in the value is double distance = Double.valueOf( JOptionPane.showInputDialog("How many miles?")); int pints = Integer.valueOf( JOptionPane.showInputDialog("How many pints?")); The question to ask © The University of Sheffield Double instead of Integer The capital letters are important 19 Dr Siobhán North COM1003 Java programming 2023/4 Lecture 1d Summary of key points • Constants do not change their value (or only change rarely and then because the world has changed) and are the same for every run of the program • Constants are identified by names which are made up of capital letters, digits and the underscore character starting with a letter • Their declaration starts with the word final • You can set the value of a variable by asking the user its new value using a JOptionPane © The University of Sheffield 20