CSC 1052 Algorithms & Data Structures II

Transcription

CSC 1052 Algorithms & DataStructures IIReview of Java

OVERVIEW OF KEYFEATURES OF JAVA2

The Java Programming LanguageOriginally intended to control consumer devicesspecial-purpose languageSoon changed to a much broader scopegeneral-purpose languageFirst public release: 1995Sun Microsystems was purchased by Oracle in 20103

The Java Programming LanguageKey features when Java was first released:Platform Independence – not tied to one type of computer*Applets – Programs that run in a web browserObject-oriented – A effective programming paradigmGarbage Collection – Java "cleaned up" memory by getting ridof unused objects*Java's slogan: "Write Once, Run Anywhere."4

StringsA character string is a group of ordered charactersCharacter strings are objects in Java, defined by the String classSo a String variable is a reference to an objectThe String class is part of the java.lang package, so does notneed to be imported5

StringsStrings can be created with the new operator, but a doublequoted string literal is already an objectString name new String("James Gosling");String title "Rephactor Java";The plus operator ( ) is used to perform string concatenationSystem.out.println("Without " name ", there would be no " title ".");Without James Gosling, there would be no Rephactor Java.6

StringsStrings are managed so that you can refer to individualcharacters by a numeric index, which starts at 0The String class has many methods to help manage stringsFor example, the length method returns the number ofcharacters in the string (14 in this case)The charAt method returns the character at a particular indexint num title.length();char letter title.charAt(10);7

StringsA String object is immutable, which means you can't change thecharacters in the string once it is createdMany String methods return new String objectsString titleUpper title.toUpperCase();8

StringsThe substring method returns a new String that contains asubset of characters copied from another stringThere are two versions: one that takes one index as anargument and one that takes twostr.substring(5)str.substring(7, 12)If one index is specified, the substring runs from that index tothe end of the stringIf two indexes are specified, the substring runs from the firstindex up to but not including the second index9

StringsString goBig "Go big or go home";String sub1 goBig.substring(10);String sub2 goBig.substring(3, 12);System.out.println("Original string: " goBig);System.out.println("substring(10): " sub1);System.out.println("substring(3, 12): " sub2);10

ArraysAn array is an object that holds a set of valuesEach value can be accessed by a numeric indexAn array of length N is indexed from 0 to N-1The scores array can hold 10 integers, indexed from 0 to 9The name of the array is an object reference variable11

ArraysSquare brackets (the index operator) are used to refer to aspecific element in the arrayint num scores[3];An exception is thrown if you attempt to access an array outsideof the range 0 to N-1This is called a bounds errorEach element of scores can be treated as an individual integerscores[7] 83;12

ArraysThe object reference variable is declared without specifying thesize of the arrayint[] scores;The variable scores can refer to any array of integersThe size of an array is specified when the array object is createdscores new int[10];As with other objects, those two steps may be combinedint[] scores new int[10];13

ArraysIn Java it is valid to associate the brackets with thearray name in a declarationint myList[];However, this is not a good ideaIt is far more readable to associate the brackets with theelement typeint[] myList;Together, they define the type of the variable (an array of int)14

ArraysThe array's element type is the type of values it storesAn array can be declared to hold any primitive or object typeOnly values consistent with the element type can be stored in itint[] widths new int[500];double[] myArray new double[20];boolean[] flags new boolean[80];String[] names new String[150];When an array is created it is filled with the default value forthe element type15

ArraysThe size of an array is stored in a constant called lengthOnce an array has been created, its size cannot changeThe for and for-each loops are often used when processing arraysint[] list new int[15];for (int i 0; i list.length; i )list[i] i * 10;010for (int value : list)System.out.print(value "");201003040506070809011012013014016

ArraysModifying particular elements of that array:list[3] 999;list[0] list[5];list[12] list[13] list[14];for (int value : list)System.out.print(value "501020999405060708090");10011027013014017

ArraysAn array can also be created using an initialization list, which bothcreates the array and fills it with valuesint[] primes {2, 3, 5, 7, 11, 13, 17, 19, 23,29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71};If an initialization list is used, the new operator is notThe array size is determined by the number of elements in thelist18

For StatementA for statement is a loop that works well when you know or cancalculate how many iterations need to be performedThe for loop header contains three sections separated bysemicolonsInitializationConditionIncrementfor (int num 1; num 10; num )System.out.println(num);The control variable is often declared in the initializationsection, but doesn't have to be19

For Statementfor (int num 1; num 10; num )System.out.println(num);System.out.println("Now here.");12345678910Now here.20

For Statement21

For StatementThe for statement is compact and often convenientEquivalent code could always be written as a while loop22

For StatementThe increment section does not have to incrementfor (int i 20; i 0; i--)System.out.print(i " ");System.out.println();System.out.println("Now here.");20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1Now here.23

For StatementPrinting the powers of two less than 1000:for (int num 2; num 1000; num * 2)System.out.print(num " ");System.out.println();System.out.println("Now here.");2 4 8 16 32 64 128 256 512Now here.24

For StatementPrinting a triangle made of asterisks:for (int line 1; line 7; line ){for (int asterisk 1; asterisk line; asterisk ***********************The outerloop's controlvariable25

Common Array AlgorithmsAn array is a sequence of elements containing the same type ofdata. It is created using square brackets ([]) and initialized usingthe new operator. The array can be empty or can contain anynumber of initial items.int[] emptyList;int[] fullList {7, 11, 99, 5, 17, 2, 73, 3, 9};Arrays enable the use of many other common algorithms: Filling and printing values in an array Finding an average, minimum or maximum Searching for and swapping elements26

Common Array Algorithms: Filling & PrintingAn array can be filled by initializing it with values, and printedeither directly or using a for loop.int[] values {58, 23, 70, 105, 64, 12, 174, 33};System.out.println(values[0]);for (int num : values)System.out.println(num " ");5858 23 70 105 64 12 174 33 51 427

Common Array Algorithms: Filling & PrintingAn array can also be filled programmatically by setting eachvalue directly, and then printed.int[] evens new int[10];for (int i 0; i evens.length; i )evens[i] i * 2;System.out.println(evens[0]);for (int i 0; i evens.length; i )System.out.println(" ", evens[i]);0 2 4 6 8 10 12 14 16 1828

Common Array Algorithms: Average ValueTo calculate the average value for an array of values, sum thevalues using a loop and divide by the number of values.int[] values {58, 23, 70, 105, 64, 12, 174, 33, 51, 4};double sum 0.0;for (int num : values)sum num;double average sum / values.length;System.out.println("Average: " average);Average: 59.429

Common Array Algorithms: Minimum ValueA common algorithm used with arrays is finding a minimum.int[] values {7, 11, 99, 5, 17, 2, 73, 3, 9, 12, 8};int minIndex 0;for (int i 1; i values.length; i )if (values[i] values[minIndex])minIndex i;System.out.println("Minimum: " values[minIndex]);System.out.println("At index: " minIndex);Minimum: 2At index: 530

Common Array Algorithms: Maximum ValueFinding the maximum value works the same way as minimum.int[] values {7, 11, 99, 5, 17, 2, 73, 3, 9, 12, 8};int maxIndex 0;for (int i 1; i values.length; i )if (values[i] values[maxIndex])maxIndex i;System.out.println("Maximum: " values[maxIndex]);System.out.println("At index: " maxIndex);Minimum: 99At index: 231

Common Array Algorithms: SearchingSearching for a specific value in an unordered list can be doneusing a linear search.int[] values {7, 11, 99, 5, 17, 2, 73, 3, 9, 12, 8};int target 73;int index 0;while (index values.length && values[index] ! target)index ;if (index values.length)System.out.println(target " found at " index);elseSystem.out.println(target " not in array ");73 found at index 632

Common Array Algorithms: SwappingSwapping one item for another requires a temporary variable.int[] values {58, 23, 70, 105, 64, 12, 174, 33, 51, 4};for (int num : values)System.out.print(num " ");System.out.println();# Swap elements index 3 (105) and index 9 (4)int temp values[3];values[3] values[9];values[9] temp;for (int num : values)System.out.print(num " ");58, 23, 70, 105, 64, 12, 174, 33, 51, 458, 23, 70, 4, 64, 12, 174, 33, 51, 10533

ECLIPSE

EclipseEclipse is an integrated development environment (IDE)for Java programmers that is well-suited to programmersat all levels of experience.An IDE issoftware thatcombines thetools that aprogrammeruses to write,save, edit, andrun code.35

Install EclipseVisit the Eclipse website and click on the Download buttonSelect the version of the Eclipse IDE for Java Developers that'sright for your system, download and install it.

Tour the Eclipse IDE

Write & Run a ProgramSelect File New Java Project. On the New Java Project dialog,type HelloEclipse as the name. Click Don't Create when asked.Then select File New Class and create a HelloEclipse class.

Write & Run a ProgramEnter this code:public class HelloEclipse{public static void main(String[] args){System.out.println("Hello, Eclipse!");}}Run by clickingHello, Eclipse!

Write & Run a Program

OBJECTS & CLASSES

Objects and ClassesAn object is a fundamental program componentIt represents something in terms of attributes and behaviorsPotential attributes of a car:make, model, color, current speed, current directionPotential behaviors of a car:accelerate, stop, change gears, turnWhich attributes and behaviors are actually representeddepends on what the system doesA car object in a racing game would be different than a carobject in a dealer inventory system42

Objects and ClassesAn object is defined by a classA class is:the type of the objectthe pattern from which it is createdYou might write a class called Car and then create many Carobjects using itThe word class comes from the word classificationA class represents a group of similar objectsAn object is an instance of a classEach object has its own instance data that represents itsattributes43

Objects and ClassesAn object has three propertiesidentity – the way you specify an individual objectA reference variable is the object's identity in a programstate – the values of its instance dataOne car: green Honda CRV heading northeast at 55 MPHAnother car: black Ford Focus heading south at 40 MPHbehavior – the list of services an object can performThe methods you can invoke on an object define its behavior(also known as its public interface)44

Objects and ClassesA class is like the blueprint of an objectThe conceptThe realizationYou can't live in a blueprint, but it defines the houseHouses made from the same blueprint are the same type ofhouse, but have room for different furniture and families45

Objects and ClassesA class defines the types of data an object will have anddetermines how that data will be organizedBut it doesn't reserve any memory space for it until an objectis createdEach object has its own memory space and therefore its ownstateThe class contains the code for the methods that define anobject's behaviorBut the methods are called through a particular object, whichdetermines which data is used and updated46

Creating ObjectsThe java.awt.Point class represents a two-dimensional x, ycoordinateTo create a Point object, we use the new operatorPoint p new Point(4, 7);A call to the object's constructor sets up the new objectA constructor is like a method that initializes instance dataand whatever else is necessary to get the object ready to useA constructor has the same name as the class47

Creating ObjectsThese activities are often combined this way, but theydon't have to be48

Creating ObjectsIf a reference variable is null, it doesn't refer to any objectPoint target null;Later on, it can be assigned an objecttarget new Point(12, 15);49

Creating ObjectsBeware the null reference!Following a null reference will cause a NullPointerException tobe thrownPoint nowhere null;double x nowhere.getX();When in doubt, check to see if a reference is nullif (myPoint ! null)x myPoint.getX();50

Creating ObjectsMultiple references can refer to the same objectPoint p2 target;They are sometimes referred to as aliases of each otherChanges made to one affect the other because they are thesame object51

Class AnatomyA class that contains a static main method represents the driverof a programLet's look at a class that defines a classic object (with state andbehavior)The anatomy of a class includesinstance dataconstructor(s)methods52

Class AnatomyA tally counter is a device that helps you count people (as theyenter a room, for example)It's used to track the number of occupants at an eventIt has a button that increments a counter every time it's clicked,and a way to reset that counter to 0We will model the idea of a tally counter insoftware by defining a class called Counter53

Class AnatomyThe only data defined in Counter is a single int variablepublic class Counter{private int count;Instance Data// the rest of the class is defined here}The variable count is called instance data, because each instancof the class (each object) has its ownEvery time a Counter object is created, memory space is reserveto store the count for that object54

Class AnatomyInstance data allows each object to have its own stateRemember, a class is the pattern from which an object ismadeThe variable is declared once in the class, representing theinteger in each Counter object55

Class AnatomyA variable declared at the class level can be accessed by anymethod in the classDeclaring the count variable as private keeps other objectsfrom directly accessing itThat way, the value of count is only changed by methods of theCounter classThis is the basis of encapsulation56

Class AnatomyThe public methods of the Counter class define its behaviorThey are the services that a Counter object will perform whenthey are called by another object// Increments the counter when "clicked"public void click(){count ;}The click method takes no parameters and returns no value57

Class AnatomyTwo more Counter methods:// Resets the count back to 0public void reset(){count 0;}// Returns the current count of this Counterpublic int getCount(){return count;}58

Class Anatomy// Returns the current count as a stringpublic String toString(){return count "";}It's often a good idea to define a toString method for a classtoString is automatically called when you print an object orconcatenate an object to a stringConcatenating count to the the empty string is a quick wayto convert the number to a string59

Class AnatomyA constructor is like a special method that is called when anobject is created// Initializes the count to 0public Counter(){count 0;}A constructor sets up a newly created objectIt has no return type (not even void) and has the samename as the class60

Method AnatomyA method declaration defines the code that is executed whenthe method is calledA method must be declared inside a classA method declaration consists of the method header followedby the method bodyThe method header includes modifiers, the return type, themethod name, and the parameter listThe method body is enclosed in { } and contains the statementsthat will be executed each time the method is invoked61

Method AnatomyIf a method doesn't return a value, it's return type is voidThis method takes no parameters and returns no value:public void printLyrics(){System.out.println("Is this the real life?");System.out.println("Is this just fantasy?");System.out.println("Caught in a landslide,");System.out.println("No escape from reality.");}62

Method AnatomyA return statement is used to return a value from the methodIts expression must be consistent with the return typepublic String getGreeting(){return "Hello! Glad you could join us!";}If a method doesn't return a value, the return statement isusually omittedA method automatically returns when it reaches the end of themethod body63

Method AnatomyA parameter is specified using a type and a nameThe parameter serves as a temporary variable in the methodand takes on the value passed to itpublic static String getGreeting(String name){return "Hello, " name "! Glad you could join us!";}The parameters in the method header are formal parametersThe values passed in by the calling method are called actualparameters or arguments64

Method AnatomyIf the method is called from the main method, it must also bedeclared as staticpublic static void main(String[] m.out.println(getGreeting("Tina"));}public static String getGreeting(String name){return "Hello, " name "! Glad you could join us!";}Hello, Ike! Glad you could join us!Hello, Tina! Glad you could join us!65

Method AnatomyMultiple parameters are separated by commasEach parameter has its own typepublic int max(int num1, int num2){if (num1 num2)return num1;elsereturn num2;}When a return statement is executed, the method returnsimmediately66

Method AnatomyAvoid returning boolean literals in cases like this:public boolean isWithinLimit(int total, int limit){if (total limit)return true;elsereturn false;}A much cleaner approach:public boolean isWithinLimit(int total, int limit){return (total limit);}67

Method AnatomyThis method computes the distance between two points usingthe distance formulapublic double distance(int x1, int y1, int x2, int y2){int diffX x2 - x1;int diffY y2 - y1;return Math.sqrt(diffX * diffX diffY * diffY);}Variables declared within a method are called local dataThey are created each time the method is called68

Method AnatomyIt's often best to have only one return statement at the end ofthe method bodyThis method determines which greeting to return depending onthe value of a boolean parameterpublic String getGreeting(boolean formal){String greeting "Hey. How's it going?";if (formal)greeting "Charmed! So very good to meet you!";return greeting;}69

Example: DiceLet's examine another class that defines a classic objectA die (singular of dice) might have the traditional six sides, or itmay be more specializedSo the instance data of a Die class would track how manysides a die has and what value is currently showing70

The Java Programming Language Key features when Java was first released: Platform Independence – not tied to one type of computer* Applets – Programs that run in a web browser. Object-oriented – A effective programming paradigm. Garbage Collection – Java