Question? Leave a message!




Lecture Notes in Java Programming

how to learn java programming easily and how java programming works pdf free download
DanialOrton Profile Pic
DanialOrton,Hawaii,Professional
Published Date:09-07-2017
Website URL
Comment
Textbooks Lecture 1 : Introduction to Programming in Java No textbook is required. For programming beginners: Java Software Solutions: Foundations of Program Lecturer : Susan Eisenbach Design, John Lewis and William Loftus, Publisher: Addison Wesley, 2002. This is the 1st lecture on Java For experienced programmers: programming.This course is primarily – Learning the Java™ Language at about writing imperative programs using http://java.sun.com/docs/books/tutorial/ the Kenya system. – Thinking in Java, Bruce Eckel, Prentice Hall Next term you will learn to write object oriented Java programs. 2 Susan Eisenbach 1 Functional versus Software is required imperative languages Functional languages are ideal for expressing the functional (the problem to be solved) component of any http://www.doc.ic.ac.uk/kenya/ problem however... download Java onto your home machine at least 50% of all programs deal with input/output rather than a problem and functional languages aren’t follow the instructions to install it very good at input/output. then follow the instructions to install Think of the programs you use now: editor either Kenya or KenyaEclipse mail language translator (Haskell or Java) web browser Functional programming should have taught you to appreciate concise elegant programs. 3 4 A statement written in Java print() and println() println("Write this in Haskell"); Text can be printed on the screen using print() or println(). Commented version Using println(" ") puts a carriage / Susan Eisenbach return on the end of the line. every statement is 12 November 2007 print( "73" ); terminated with a ; a bit of bravado println( "=" ); println( 7 3 ); / This code prints: 73= String exclaim = "Write this in Haskell"; 21 println(exclaim); 5 6 Concatenating output with + Comments String drink = "slammers"; There are two ways of commenting code. // comments are terminated by the end of line print("I like "); println(drink); // Susan Eisenbach This code prints: I like slammers // 12 November 2007 println("I like Tequila " + drink); // a bit of bravado This code prints: I like Tequila slammers / comments in Java are also terminated by / println / Susan Eisenbach 12 November 2007 ("6/9 = " + 6/9 + " or " + 6.0/9.0); a bit of bravado This code prints: / good to make several 6/9 = 0 or 0.6666666666666666 lines of comments stand out in your program 7 8A function written in Haskell A function written in Haskell bigger :: Int - Int - Int bigger :: Int - Int - Int post: returns the larger of two numbers post: returns the larger of two numbers bigger a bab = a argument types bigger a bab = a result type otherwise = b otherwise = b arguments Same method written in Java Same method written in Java int bigger(int a, int b) int bigger(int a, int b) //post: returns the larger of the 2 values //post: returns the larger of the 2 values if (a b) return a; if (a b) return a; else return b; else return b; 9 10 Returning from a method and A function written in Haskell conditionals bigger :: Int - Int - Int int bigger(int a, int b) post: returns the larger of two numbers //post: returns the larger of the 2 values bigger a bab = a predicate (test) must be in brackets() otherwise = b results have then and else if (a b) return a; to be returned branches are using the keyword else return b; surrounded by Same method written in Java return int bigger(int a, int b) //post: returns the larger of the 2 values if (a b) return a; else return b; conditionals - using the keywordsif and optionallyelse method bodies are surrounded by 11 12 A Java program must contain a A function written in Haskell main method biggest :: Int - Int - Int - Int It is the main method that starts the execution post: returns the largest of 3 numbers of a program off. biggest a b c = bigger a (bigger b c) It doesn’t return anything. The return type of a method that does not return anything is void. The first statement can be made into a program Same function written in Java as follows: void main() int biggest(int a, int b, int c) println("Write this in Haskell"); //post: returns the largest of the 3 values return bigger(a, bigger(b,c)); By custom the main method is the first method in the program. 13 14 /Susan Eisenbach 12 November 2007 chooses the largest of 3 numbers Variable declarations / void main() Variables are names of storage locations. Variables can be print("Type in your 3 numbers - "); declared of the following types: println(biggest(readInt(),readInt(),readInt())); int double boolean char String They must be declared before they are used. int bigger(int a, int b) int j; //post: returns the larger of the 2 values double cost; if (a b) return a; String firstname; String surname; else return b; Variables can be initialised in declarations int total = 0; int biggest(int a, int b, int c) char answer = 'y'; double start = 0; //post: returns the largest of the 3 values double sum = 0.0; return bigger(a, bigger(b,c)); boolean finish = false; 15 16 Assignment - don't use too many The assignment statement variables superfluous to requirements Initialisation is a form of assignment. Assignment gives a variable (named storage Poor style Better style location) a value. int i = 6; int i =6; variables can have their values changed throughout a program. int j = 5; int j = 5; total = total + 1; int k; println(i+j); total = total / 2; k = i+j; answer = 'n'; println(k); Haskell does not have such a low level feature. 17 18 Summary The syntax of the Java programming language is introduced in this course for coding solutions to the problems set. Lecture 2: Recursion We have seen – methods (Haskell functions) with – statement terminators - ; –variables Lecturer : Susan Eisenbach – conditionals – if (predicate) … else … For extra material read parts of –assignments chapters 1,3 and 11 – input/output –main method of – complete Java program Java Software Solutions 19 Susan Eisenbach 20 Revision from Haskell Haskell program - Java method divisor :: Int - Int - Int Define the base case(s) pre: the arguments are both Define the recursive case(s) integers 0 – Split the problem into subproblems – Solve the subproblems post: returns the greatest common divisor – Combine the results to give required answer divisor a b a==b = a ab = divisor b (a-b) ab = divisor a (b-a) 21 22 becomes: What does assert do? int divisor (int a, int b) assert (a 0 && b 0): assert (a 0 && b 0): "divisor must be given arguments 0"; "divisor must be given arguments 0"; //post: returns the gcd of a and b evaluates the predicate if (a == b) return a; true? – continue to execute the code else if (a b) return divisor (b, a - b); else return divisor (a, b - a); false? – print the string on the screen and stop the program Do not execute code which you know may crash or loop forever. 23 24 When should you have an assertion? Haskell program - Java method fact :: Int - Int If you write a method that expects something special pre: n= 0 of its inputs then you need to put as a precondition post: returns n whatever needs to be true before the code can be run. fact 0 = 1 The precondition should be coded (if possible) as an fact (n+1) = (n+1) fact n assertion. becomes : Assertions can also be written without the String int fact( int n ) message. In this case, if the assertion fails then your assert (n= 0 && n 17): program stops with an AssertionError. "factorial must be given an argument = 0"; If the user has given a method arguments that meet //post: returns n the precondition and the code is correct then the if (n==0) return 1; postcondition to the method will hold. Postconditions else return nfact(n-1); are written as comments at the top of the method after the word post. 25 26 Java method - Java program Methods void main() Haskell has functions that return results. print("Factorial number that you want? "); println("Answer = " + fact(readInt())); Java has methods that return results (just like Haskell) int fact( int n ) Java has methods that don't return any values, assert (n= 0): they just execute some code. "factorial must be given an argument = 0"; //post: returns n – their return type is void. if (n==0) return 1; – they frequently consume input and/or produce else return nfact(n-1); output –The special main method must be void. Rewrite this program with a more efficient fact Both types of methods can be recursive. method. Java programs can never be recursive. 27 28 Menu method processMenu method void processMenu(int reply) void menu() assert (0= reply && reply =4); curly brackets are switch (reply) //post: 5 lines of text appear on the screen used for each case case 0: println("Bye"); break; println( "Enter 0 to quit" ); case 1: println(readInt()+readInt()); break; println( "Enter 1 to add" ); case 2: println( "Enter 2 to subtract" ); case 3: case 4: println(" not yet implemented"); break; println( "Enter 3 to multiply" ); default: println("not possible"); println( "Enter 4 to divide" ); 29 30 int used to choose the case to execute, chars can also be used switch Question switch (reply) Rewrite processMenu changing it in two ways. case 0: println("Bye"); break; – remove the precondition case 1: a = readInt(); b = readInt(); – produce the correct answer on the screen for each println(a+b); break; of the operations break prevents cases case 2: Notes falling through case 3: –only read in the numbers once case 4: println(" not yet implemented"); break; –you can put ifs and switches inside each other or default:println("not possible"); themselves – tell the user there is an error if reply 0 or reply 4 if integer does not match any case not required 31 32 Developing a Java program to Input reverse a string There are a huge number of ways of reading Specification: input into Java programs. – The program should accept a line of text and print it out in reverse order. Whitespace means what you get when you hit Remember: the space bar or the enter keys. – A program cannot be recursive only a method can. We are using the Kenya system which contains: The main program just calls the method reverse – readInt() –ignores whitespaces, stops after the last digit reverse: – readDouble() –ignores whitespaces, stops after the last Read a character //progress- one char closer to CR digit If CR not yet reached //guard the recursive call – readString() –ignores whitespaces, stops on the first then whitespace after the string reverse – readChar()–ignores whitespace, then reads one character print Character. – read() – reads the next character (even if it is whitespace) readSomething() consumes the carriage return 33 34 character. The program IMPORTANT void main() Guard your recursive calls. print("type in your word to reverse -"); reverse(); Not guarding your recursive calls can lead to infinite recursion. void reverse() Make sure there is progress towards the //post: reads in a string (terminated by ENTER '\n') terminating condition between // and prints it out in reverse order invocations of the recursive routine. char ch; ch = read(); //progress- one char closer to CR Comment both the guard and the if (ch = '\n') progression. reverse(); print(ch); 35 36 Program Input cod Output d oc Summary reverse(); A routine that calls itself is called recursive. reverse() Methods can be recursive, programs cannot. ch ='c' Recursive methods that produce a single result are just like reverse() void reverse() Haskell functions. ch='o' char ch; Void methods are used when the same operation is to be reverse() performed on different data and the result wanted is ch = read(); ch='d' output on the screen. if (ch = '\n') reverse() In order that the repetition may be finite, within every ch='\n' recursive method there must appear a terminating condition reverse(); print(ch) to guard the recursive call and a progression to print(ch); distinguish one call from another. print(ch) Switch statements are used rather than conditionals when print(ch) there are several choices based on an integer or character. 37 38 What is an array? for problems which deal with large quantities of data perform the same, operations on the individual items Lecture 3 : Arrays and For Loops elements of an array are all of the same type and Lecturer : Susan Eisenbach referred to by an index arrays can be one or more dimensional arrays are called vectors and matrices by non- For extra material read parts of chapters 3 computing people and 6 of Java Software Solutions. comparison with Haskell lists – every element can be accessed with equal ease This is the 3rd lecture on Java in which arrays and for loops are examined. – multi-dimensional arrays are easy to access 40 Susan Eisenbach 39 Example of an array variable Another example of an array declarations variable declaration double vec = new double10; If we want to store the sentence “Tom is not my friend” we would use: get space to String words = new String5; hold 10 doubles its an array “Tom” the name of the array is vec “is” each element is a double “not” “my” “friend” 41 42 Examples of array variable Arrays can be initialised at declarations declaration intmat = new int54; String names = “Bradley","Eisenbach", "Gillies","Field", "Hodkinson"; double vector = 0.1, 1.2, 0.0, 34.6, This is an -3.0, 34.1, 0.0, array of arrays 0.4, 0.8, 0.1; 43 44 Examples of array variable Getting the size of an array declarations (cont.) To get the size(no. of elements) of an array, you write arrayname.length How do you declare and initialise a data structure for the following? The length of the array is determined by the number of values provided between . Susan Eisenbach for example if Antony John Field boolean answers = true, false, true, true, false; Christopher John Hogger then answers.length is 5 String fullNames = Note that length is not a method and so does not "Susan","","Eisenbach", have ( ). It is built into Java. "Antony","John","Field", Once created, the size of the array cannot change. “Christopher",“John","Hogger" ; The length of the array must be specified when it is 45 46 created. Referencing array elements Using arrays: each array element is referenced by means of the array You can pass arrays as arguments to methods: identifier followed by an index expression which uniquely void printNames(String names) indexes that element You can return arrays as results from methods: the first element of an array is at 0, the last at length – 1 example array references: String copy(String names) firstName = fullNames21; Do not assign complete arrays: secondYears = firstYears vec1 = mat10+mat11+mat12+ mat13+mat14; since any change to firstYears will happen to secondYears as well (more if (i==j) matij = 1; later on this). else mat ij = 0; 47 48 on each loop iteration i=i+1 Bounded iteration Bounded iteration arrays exist in order to hold a large number of elements of the for (int i = lowerbound; i upperbound; i++) same type loop body frequently the same operation is performed on each array value traversing all the elements of an array can be achieved by means first value of i usually 0 of a control construct known as the for loop. Using a for statement is called looping or iteration and causes repetitive execution for (int i = upperbound-1; i = lowerbound; i) for (int i = lowerbound; i upperbound ; i++) loop body loop body for (int i = upperbound - 1; i = lowerbound; i) on each loop iteration stops executing the loop when loop body i=i-1 i hits this value 49 50 Tracing the execution of some A for loop example code for loops are ideal for traversing arrays - each iteration of the loop accesses an element of the array a program to calculate the mean of an array of doubles: When trying to understand what some void main() piece of Haskell code does, you use double vec = 1,0,3,0,5,0,7,-2,9,10; println( mean(vec) ); rewrites: double mean(double v) fact 4 = 4fact 3 = 43fact 2 = //post:returns the average of the elements in v 432fact 1 = 4321= 24 double total = 0; for (int i =0; i v.length; i++) total = total + vi; return total/v.length; 51 52 When trying to understand what some piece of Java When trying to understand what some piece of Java code does you hand execute all the code working out code does you hand execute all the code working out what the values of the variables are: what the values of the variables are: mean total i v0 v1 v2 v3 v4 mean total i v0 v1 v2 v3 v4 void main() void main() double vec = 1,0,3,1,5; 1 0 3 1 5 1 0 3 1 5 double vec = 1,0,3,1,5; println( mean(vec) ); 0 println( mean(vec) ); double mean(double v) 1 0 double mean(double v) int i; 1 1 int i; double total = 0.0; double total = 0.0; 4 2 for (int i =0;iv.length;i++) for (int i =0;iv.length;i++) 5 3 total = total + vi; 10 4 total = total + vi; ; 5 ; return total/v.length; 2 return total/v.length; 53 54 What is the value of names.length? For each i, what is the value of namesi.length? Nested for loops a 2-dimensional array requires 2 for loops to traverse void main() it: String students = int sum(int m) "BSc", "Homer", "Marge", "Bart", "Lisa", "Maggie", "MSci", "Moss", "Jen", "Roy", //post: returns the sum of the elements of m "BEng", "Peter", "Lois", "Meg", "Brian", "Stewie",, int theSum = 0; "MEng", “Harry", "Adam", "Ros", "Malcolm","Zafar","Connie" ; for (int i = 0; im.length; i++) printNames( students ); for (int j = 0; jmi.length; j++) theSum = theSum + mij; void printNames(String names) for (int i = 0; i names.length; i++) print(namesi0 + ": "); for (int j = 1; j namesi.length; j++) return theSum; print(namesij + " "); println(); an n-dimensional array requires n for loops to traverse If int mat50100 is passed to sum, what is the value of m.length? For each i, what is the value of 55 56 mi.length? Summary Summary Arrays are data structures suitable for problems Arrays have a type associated with them: the dealing with large quantities of identically typed type of the elements. The index is always a non- data where similar operations need to be negative integer. performed on every element. Space has to be allocated explicitly for arrays. Elements of an array are accessible through their Either they are initialised with values and then index values. Arrays using a single index are the right amount of space is allocated or the keyword new is used to specify the allocation of called vectors, those using n indices are n- dimensional arrays. A two dimensional array is space. really an array of arrays, a 3-dim., an array of Repetition of the same operation is called arrays of arrays, etc. iteration or looping. A for loop can be used to do the same operation to every element of an array. 57 58 Consider a game to play noughts and crosses Assuming that each space on the board can have a 'X', an 'O' or a ' ', write an array declaration to hold a board, initialising it all to empty. Lecture 4 : Using Arrays char board = ' ',' ',' ', ' ',' ',' ', ' ',' ',' '; Lecturer : Susan Eisenbach Write a statement that puts a 'X' into the For extra material read parts of chapters 3 and 6 in Java Software Solutions. middle square This is the 4th lecture in which code is developed that board11 = 'X'; uses arrays and parameter passing mechanism is examined in some detail. 60 Susan Eisenbach 59O O O Write a predicate isFull which returns true iff Write a method initBoard which there are no empty spaces on the board. returns a new board filled with spaces. boolean isFull(char b) for (int r = 0; r 3; r++) char initBoard() for (int c = 0; c 3; c++) char b = ' ',' ',' ', if (brc == ' ') return false; ' ',' ',' ', ' ',' ',' ' X X O ; return true; O O X return b; X X 61 62 Write a predicate isDiagonal that takes as arguments an X or O and a board and returns true iff Checking for a winner one of the diagonals is filled with the piece. boolean isDiagonal(char ch, char b) After each move a check has to be made assert (ch='X' ch='O'); whether the current player has won. return b00== ch && A player has won if their piece fills one b11== ch && of the diagonals, one of the rows or one b22== ch of the columns. b02== ch && X X O b11== ch && X X O b20== ch; O O O X X X X 63 64O O O O Write a predicate hasFullRow that takes as Write a predicate hasFullCol that takes as arguments an X or O and a board and returns true arguments an X or O and a board and returns true iff one of the rows is filled with the piece. iff one of the columns is filled with the piece. boolean hasFullCol(char ch, char b) X X O X X O boolean hasFullRow(char ch, char b) assert: ch='X' ch='O'; assert (ch='X' ch='O'); boolean found; O O X O O X boolean found; for (int c = 0; c 3; c++) for (int r = 0; r 3; r++) X X X X found = true; found = true; for (int r = 0; r 3; r++) for (int c = 0; c 3; c++) found = found && brc == ch; found = found && brc == ch; if (found) return true; if (found) return true; return false; return false; 65 66 Put them together to produce a Exercises to do yourself: predicate isWinner Write the predicate hasFullCol that takes as boolean isWinner(char ch, char b) arguments an X or O and a board and returns assert: ch='X' ch='O'; true iff one of the columns is filled with the return isDiagonal(ch,b) piece using only one loop. hasFullRow(ch,b) Rewrite the code in the slides with hasFullCol(ch,b); the board as a one dimensional array. X X O How much harder is it to write the X X X X X O O O X predicates? O O X O O O X X X X 67 68O How do you get which square You need to know if the character the the next player wants? user typed in is for a row or a column Write a predicate IsRow which takes as an You could (mouse) click on the square on the screen and the argument a character and returns true iff the coordinates could be converted into the appropriate argument is an'a', a'b' or a 'c'. noughts and crosses index. boolean isRow(char c) This requires very sophisticated input routines. Simpler would be to read in from the keyboard chess return 'a' = c && c = 'c'; notation for the square and then convert it to the appropriate array indices. Write a predicate IsCol which takes as an So if a user wants the middle square, it is b2 or 2b X X O argument a character and returns true iff the and the bottom lefthand corner is c1 or 1c a argument is an'1', a'2' or a '3'. O O X b boolean isCol(char c) X X return '1' = c && c = '3'; c 1 2 3 69 70 Convert the input characters into numbers that can be used for array indices Arguments to methods We have been passing arguments to methods. Write a method convert that takes a character that is a valid row or column and returns the Java's argument passing is slightly more appropriate number to use for the row index or restrictive than Haskell's – you can pass column index. So if '2' is passed as an argument anything to a Java method, except another to convert it returns 1. method. int convert(char c) In Java methods, arguments are passed by value. When invoked, the method receives the assert (isRow(c) isCol(c)); value of the variable passed in, creates a local if (c=='1' c=='a') return 0; copy, works on it and then discards it when the if (c=='2' c=='b') return 1; method is left. return 2; This means that a method cannot change the value of its arguments. 71 72 What happens when you pass a variable to a What happens when you pass a variable to a method and change its value within the method? method and change its value within the method? void main() void main() int a = 1; int a = 1; a = 1 int b = 2; int b = 2; b = 2 println("a & b = " + a + b); println println("a & b = " + a + b); swap(a,b); println("after swap " + a + b); swap(a,b); temp = 1 println("after swap " + a + b); void swap(int a, int b) a = 2 //post: this method does very little void swap(int a, int b) int temp = a; b = 1 a = b; //post: this method does very little println b = temp; int temp = a; println("inside swap " + a + b); println a = b; a & b = 1 2 b = temp; inside swap 2 1 println("inside swap " + a + b); 73 after swap 1 2 74 When a method is called the runtime system of Summary any language holds method data in a stack A predicate is a method that returns a boolean a = 1 result. b = 2 It is sensible to name predicates starting with is, println are, can or some other similar word. temp = 1 We have developed a variety of methods that are necessary if one is writing a noughts and crosses a = 2 game. 2 1 Aa = 1 , b = 2 , temp = 1 push pop b = 1 In Java methods, arguments are passed by value. println push When invoked, the method receives the value of Aa = 1, b = 2 the variable passed in, creates a local copy, works println on it and then discards it when the method is left. This means that a method cannot change the value 75 76 of its arguments. Tutorial questions int power(int x, int n) 1. Translate the following Haskell functions into Java functions. assert (n = 0); //post: xn power :: Int - Int - Int if (n==0) return 1; pre: the second argument is a non-negative integer else return x power(x, n-1); post: computes first arg to power of second arg power x n n==0 = 1 otherwise = x power x (n-1) 77 78 int power1(int x, int n) assert (n 0); power1 :: Int - Int - Int //post: xn pre: the second arg is a non-negative integer post: computes first arg to power of second arg if (n==0) return 1; power1 x n n==0 = 1 else n==1 = x if (n==1) return x; n `mod` 2 == 0 = zz else otherwise int z = power1 (x, n / 2); = zzx if ((n%2) == 0) return zz; where z = power1 x (n `div` 2) else return zzx; In Java `div` is / and `mod` is % 79 80