Data Structures CSCI 3230
Popular in Course
Popular in ComputerScienence
This 75 page Class Notes was uploaded by Leonor Kulas on Monday October 12, 2015. The Class Notes belongs to CSCI 3230 at Georgia Southern University taught by Debopam Acharya in Fall. Since its upload, it has received 47 views. For similar materials see /class/221982/csci-3230-georgia-southern-university in ComputerScienence at Georgia Southern University.
Reviews for Data Structures
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 10/12/15
Java Review Program Structure Typical Java program consists of User written classes Java Application Programming Interface API classes Java application Has one class with a main method Java program basic elements Packages Classes Data fields Methods Ml Lecture Notes Java Reviewppt Packages Provide a mechanism for grouping related classes package statement Indicates a class is part of a package Java assumes all classes in a particular package are contained in same directory Java API consists of many predefined packages Ml Lecture Notes Java Reviewppt 13 Packages import statement Allows you to use classes contained in other packages Package javalang is implicitly imported to all Java code Ml Lecture Notes Java Reviewth A Simple Java Program L lndietes Siplesphexe is Pan 2 Indeesdas Mach 5 used by Simplasp heze 7 39 1e 7 gt Paltkage 7gt package EYPACKaQE n javaaan 7 Ass gnrnem scam 9 Asggnrnem meal 1 ea Eegins mghod Jetkaaius 1 Returns data eld radius 7 1 s ndsdzm Simlesphexe 7 77 1 7 ndmmes TeatclaBl 39 pan of a Daltkage 7 1 a Eegins d 51estclagg 77 7 9 3 20 mamg qune 711 77 IL reams a Siplesyhaxe damn 7 23 ontinuaxinu or am 9mg 7 or 24 antinuainu quotminis lucnasVnquot n um mgr 7 7 rm Lemme NutESrJava Revmvvpp 25 Endsdass Testclaa and mans Classes Data type that specifies data and methods available for instances of the class An object in Java is an instance of a class Class definition includes Optional subclassing modifier Optional access modifier Keyword class Optional extends clause Optional implements clause Class body Ml Lecture Notes Java Reviewppt 1 0 Classes Every Java class is a subclass of either Another Java class Object class new Operator Creates an object or instance of a class Ml Lecture Notes Java Reviewplat Classes Component Syntax Description Subclassing abstract Class must be extended to be useful modi er use only Om final Class cannot be extended AL WSS P mlic Class is available outside of package modi ers no access modi er Class is available onlywithin package Keyword class class name Class should be contained in a le called class class namejava extends extends Indicates that this class is a subclass of the class clause superclassname superclass name in the extends clause implements implements Indicates the interfaces that this class implements clause interface list The interface list is a comma5e painted list of l tt l39F JCB HM39DE39S Class body Enclosed in braces Contains data elds and methods for the class Figure 12 COWPeQEl et a gsa cilaavgieview ppt Data Fields Class members that are either variables or constants Data field declarations can contain Access modifiers Use modifiers Modules Mi Lecture Notes Java Reviewpoi Data Fields Type of modi er Keyword Descri ptiun Access modi er public Data eld s avalahle everwvhere when the class is 1 use on y one also dcrlared publicl private Data eld is available only wld n the Lbs protected Dam eld is available within the LES available in subclasses and avadable to classes Within the same wacLa e N0 access Data eld is available within the class and within modi er the package Use modi ers static Indicates that only cut sut h data eld is IlVMlAlJlk 1 all can he used at for all instances ofthls class Without this modi cr once each Instance has hi own copy It d data eld final The value provided for the data eld cannor be modi ed a constantlt transient The data eld is nor part of tlk persistent state of the obiect volatile The value provided for die data eld an be accessed by muluple threads of canal lava ensures that 2hr freshest copy of the data eld is always used Figure 13 ifiers useg in data Ield declarations Mo 1 Lecture l es Java 39 ewewppt Methods Used to implement operations Should perform one well defined task Method modifiers Access modifiers and use modifiers Valued method Returns a value Body must contain return expression Ml Lecture Notes Java Reviewppt Method Modifiers Type af madii tcr Keyword Description Acccss modi er public Method is available xv Wlk l c ll hCn tl39w ch is lug only mk l aim dcclat39cd aspublt c private Method IS availablt only Withln the class i cannot be tclami abstract protected Method is available within the tlass available in subclasses and available to classes Within the same package No access Method is available vithm le lass and to classes modi er Within the package Use modi ers static Indicates that only one such method is available iall can be used at for all instances m39this claas Since a static once39i nk39lhDd is shared by all ll39lSl JnL39CS mt method can refer only to data elds that are also declared actinc and shared by all inmates nal The method Cd nCt be nvcmddtn in a subclass abstract The method must be VCI39rK ldt n in a siibtlass native The body of the mtthod is quot0 written in lava but in some mati programming language synchronized The method can he run by only one thread ui control at a time Figure 14 Mo ifiers usggeisti alarggerghod declaration 1 Lecture eVIew ppt Methods Syntax of a method declaration access modifier use modifiers return type method name formal parameter list method body Arguments are passed by value Except for objects and arrays A reference value is copied instead Java 15 allows a method to have a variable number of arguments of the same type Using the ellipses three consecutive dots Ml Lecture Notes Java Reviewppt 143 Methods Constructor Special kind of method Has the same name as the class and no return type Executed only when an object is created A class can contain multiple constructors Ml Lecture Notes Java Reviewpoi How to Access Members of an Object Data fields and methods declared public Name the object followed by a period followed by member name 0 Members declared static Use the class name followed by a period followed by member name Ml Lecture Notes Java Reviewbrat 145 Language Basics Java application Collection of classes One class contains the main method Java programs can also be written as applets Ml Lecture Notes Java Reviewppt Comments Comment line Begins with two slashes Continues until the end of the line 0 Multiple line comment Begins with and ends with Useful for debugging Cannot contain another multipleline comment javadoc comments Begins with and ends with Mi Lecture Notes Java Reviewpot Identifiers and Keywords Identifier Sequence of letters digits underscores and dollar sngns Must begin with either a letter or underscore Used to name various parts of the program Java distinguishes between uppercase and lowercase letters 0 Keywords Java reserved identifiers Ml Lecture Notes Java Reviewppt 148 Variables Represents a memory location Contains a value of primitive type or a reference Its name is a Java identifier Declared by preceding variable name with data type double radius radius of a sphere String name reference to a String object Mi Lecture Notes Java Reviewppt 149 Primitive Data Types 0 Organized into four categories Boolean Character Integer Floating point Character and integer types are called integral types 0 Integral and floating point types are called arithmetic types Ml Lecture Notes Java Reviewppt l20 Primitive Data Types Category Data Type Wrapper Class Baalsari boulean Boolean Character char Charact er Integer byte Byte short ShQrt int Integer long Long Floating point float Float double Douh le Figure 15 Primitive data types and corresponding wrapper classes lVI l Lecture Notes Java Reviewppt Primitive Data Types Value of primitive type is not considered an object java lang provides wrapper classes for each ofthe primitive types Autoboxing Automatically converts from a primitive type to the equivalent wrapper class Auto unboxing Reverse process Ml Lecture Notes Java Reviewppt l22 References Data type used to locate an object Java does not allow programmer to perform operations on the reference value Location of object in memory can be assigned to a reference variable Ml Lecture Notes Java Reviewppt l23 Literal Constants Indicate particular values within a program Used to initialize the value of a variable Decimal integer constants Do not use commas decimal points or leading zeros Default data type is either int or long Floating constants Written using decimal points Default data type is double Ml Lecture Notes Java Reviewppt l24 Literal Constants 39 Character constants Enclosed in single quotes Default data type is char Literal character strings Sequence of characters enclosed in double quotes Ml Lecture Notes Java Reviewpoi Named Constants 0 Have values that do not change Declared as a variable but using the keyword final Ml Lecture Notes Java Reviewpot l26 Assignments and Expressions Expressions Combination of variables constants operators and parentheses 0 Assignment statement Exampe radius r 0 Arithmetic expression Combine variables and constants with arithmetic operators and parentheses Arithmetic operators Mi Lecture Notes Java Reviewppt i2quot Assignments and Expressions Relational expressions Combine variables and constants with relational or comparison and equality operators and parentheses Relational or comparison operators lt lt gt Equality operators Evaluate to true or false Ml Lecture Notes Java Reviewppt l28 Assignments and Expressions 0 Logical expressions Combine variables and constants of arithmetic types relational expressions with logical operators Logical operators ampamp Evaluate to true or false Short circuit evaluation Evaluates logical expressions from left to right Stops as soon as the value of expression is apparent Ml Lecture Notes Java Reviewppt l29 Assignments and Expressions Implicit type conversions Occur during assignment and during expression evaluation Righthand side of assignment operator is converted to data type of item on left hand side Floating point values are truncated not rounded Integral promotion Values of type byte char or short are converted to int Conversion hierarchy int 9 long 9 float 9 double Ml Lecture Notes Java Reviewppt l30 Assignments and Expressions Explicit type conversions Possible by means of a cast Cast operator Unary operator Formed by enclosing the desired data type within parentheses Multiple assignments Embed assignment expressions within assignment expressions Exampleza 5 b 4 Evaluates to 9 while b is assigned 4 Mi Lecture Notes Java Reviewppt l3l Assignments and Expressions Other assignment operators Mi Lecture Notes Java Reviewth L32 Arrays Collection of elements with the same data type Array elements have an order Support direct and random access One dimensional arrays Declaration example final int DAYSPERWEEK 7 double maXTemps new doubleDAYSPERiTEEK Length of an array is accessible using data field length Use an index or subscript to access an array element Ml Lecture Notes Java Reviewppt i33 Arrays D 1 2 3 A1 5 6 al index mayTemps 82quot a39 15 1 8 T513 883 10 l 00 l v39 1 maxTemps 4 Lin used at present Figure 17 Onedimensional array of at most seven elements M1 Lecture Notes Java Reviewppt 134 Arrays One dimensional arrays continued Initializer list example double weekDayTemps 820 715 618 750 883 You can also declare array of object references Multidimensional arrays Use more than one index Declaration example final int DAYSPERWEEK 7 final int WEEKSPERYEAR 52 double minTemps new doubleDAYSPERWEEKWEEKSPERYEAR MlLedweNomsJmmivawpm BE Arrays Columns A o I 51 r 0 I How lt 6 Figure 18 Atwodimensional array M1 Lecture Notes Java Review ppt Arrays Passing an array to a method Declare the method as follows public double averageTempdouble Invoke the method by writing double avg averageTempmaXTemps 6 Location of array is passed to the method Cannot return a new array through this value Method can modify content of the array temps int n Ml Lecture Notes Java Reviewphi Selection Statements The if statement if expression statementl or if expression statementl else statementZ Ml Lecture Notes Java Reviewpot Nested i f if expression statementl else if expression statementZ else statementB end if 138 Selection Statements 0 The switch statement switch integral expression case 1 statementl break case 2 case 3 statement2 case 4 statementB break default statement4 end of switch Mt Lecture Notes Java Reviewpot 139 Iteration Statements The while statement while expression statement statement is executed as long as expression is true statement may not be executed at all continue expression Stops the current iteration of the loop and begins the next iteration at the top of the loop Ml Lecture Notes Java Reviewppt l40 Iteration Statements The for statement for initialize test update statement statement is executed as long as test is true for statement is equivalent to a while statement The for loop and arrays for ArrayElementType variableName arrayName statement Mi Lecture Notes Java Reviewpm i4i Iteration Statements 0 The do statement do statement while expression statement is executed until expression is false do statement loops at least once Mi Lecture Notes Java Reviewpm i42 Useful Java Classes 0 The Object class Java supports a single class inheritance hierarchy With class Object as the root More useful methods public boolean equals Object obj protected void finalize public int hashCode public String toString Ml Lecture Notes Java Reviewbrat l43 Useful Java Classes String classes Class String Declaration examples String title String title Walls and Mirrors Assignment example Title Walls and Mirrors String length example titlelength Referencing a single character titlecharAt 0 Comparing strings titlecompareTo string2 Vii Lecture Notes Java Reviewppt i44 Useful Java Classes String classes continued Class String Concatenation example String monthName quotDecemberquot int day 31 int year 02 String date monthName quot quot day quot 20quot year Ml Lecture Notes Java Reviewpm l45 Useful Java Classes String classes continued Class StringBuffer Creates mutable strings Provides same functionality as class String More useful public public String public end public public end methods StringBuffer appendString str StringBuffer insertint offset str StringBuffer deleteint start int void setCharAtint index char ch StringBuffer replaceint start int String str Mi Lecture Notes Java Reviewpm i46 Useful Java Classes String classes continued Class StringTokenizer Allows a program to break a string into pieces or tokens More useful methods public StringTokenizerString str public StringTokenizerString str String delim public StringTokenizerString str String delim boolean returnTokens public String nextToken public boolean hasMoreTokens Mi Lecture Notes Java Reviewpm i4quot Java Exceptions Exception Handles an error during execution 0 Throw an exception To indicate an error during a method execution Catch an exception To deal with the error condition Mi Lecture Notes Java Reviewppt Catching Exceptions Java provides try catch blocks To handle an exception Place statement that might throw an exception within the try block Must be followed by one or more catch blocks When an exception occurs control is passed to catch block Catch block indicates type of exception you want to handle Ml Lecture Notes Java Reviewppt Catching Exceptions try catch blocks syntax try statements catch exceptionClass identifier statements Some exceptions from the Java API cannot be totally ignored You must provide a handler for that exception Mi Lecture Notes Java Reviewppt 1430 Catching Exceptions Exceptionaxanple 91 new Excaptionkxample myAIxay public vom addvalueun 1 in value I add v t n by calling addme n times i lt value i Q to 1319an for lm 1 1 addoneuu and for 9nd addvalue pubnc vold adamant In add 1 to the element It myArrayIn 4 l H end addone The method main public static voxd maintstringl arqs Except onlxalple el new Exceptionaoamplet eladdva1ue9 3 add 3 to element 99 II 9nd min The element you requested 99 is not available 9 java 16mgArraylndexoutofBoundsExceptlon 99 at Exceptionaxam 1eaddoneExceptionixenpledava at ceptlunzmpleaddvaluecompiled code 1 9 at Testzxceptionz xamplemain esh xceptlon xamplejava Flow of control in a simple Java application M1 Lecture Notes Java Review ppt 151 Catching Exceptions Types of exception Checked exceptions Instances of classes that are subclasses of javalangException Must be handled locally or thrown by the method Used when method encounters a serious problem Runtime exceptions Occur when the error is not considered serious Instances of classes that are subclasses of javalangRuntimeException Ml Lecture Notes Java Reviewppt Catching Exceptions The finally block Executed whether or not an exception is thrown Can be used even if no catch block is used Syntax finally statements Ml Lecture Notes Java Reviewpot Throwing Exceptions throws clause Indicates a method may throw an exception If an error occurs during its execution Syntax public methodName throws ExceptionClassName throw statement Used to throw an exception at any time Syntax throw new exceptionClassstringArgument You can define your own exception class Mi Lecture Notes Java Reviewppt i54 Text Input and Output Input and output consist of streams Streams Sequence of characters that either come from or go to an IO device InputStream Input stream class PrintStream Output stream class javalangSystem provides three stream variables System in standard input stream System out standard output stream System err standard error stream MI Lecture Notes Java Reviewppt I05 Input Prior to Java 15 BufferedReader stdin new BufferedReadernew InputStreamReaderSystemin String nextLine stdinreadLine StringTokenizer input new StringTokenizernextLine x IntegerparselntinputnextToken y IntegerparselntinputnextToken NM Lecture Notes Java Reviewth L58 Input Java 15 The Scanner class int nextValue int sumO Scanner kanput new ScannerSystemin nextValue kanputnextInt while nextValue gt O sum nextValue nextValue kanputnextInt end while kanputclose NM Lecture Notes Java Reviewth 1e O I Input Java 15 The Scanner class continued More useful next methods String next boolean nextBoolean double nextDouble float nextFloat int nextInt String nextLine long nextLong short nextShort Mt Lecture Notes Java Reviewpm Output Methods print and println Write character strings primitive types and objects to Systemout println terminates a line of output so next one starts on the next line When an object is used with these methods Return value of object s toString method is displayed You usually override this method with your own implementation Problem Lack of formatting abilities an to NM Lecture Notes Java Reviewppt i Output Method printf Cstyle formatted output method Syntax printfString format Object args Example String name quotJamiequot int x 5 y 6 int sum x y Systemoutprintfquots d 6d dquot name x y sum produces output Jamie 5 6 11 Mt Lecture Notes Java Reviewppt 180 Output Output Sara String name Sarah double y 1012334568 int n 145 systemantprintfy39isls xnquot name 3 a Systemout printfquotl zsmquot name 1 1 5 Systemoutprintfquotl dnquot n l 10e04 Systemoutprintfquotl 29 mquot y 101 2 3 3 5 Systemoutprintfquot102f mquot y 10 l 2 3 3 4 5 6 9 Systemoutprintfquot55 quotnquot y 1234567391011 C ofumn number Figure 110 Formatting example with printf M1 Lecture Notes Java Review ppt 161 File Input and Output File Sequence of components of the same type that resides in auxiliary storage Can be large and exists after program execution terminates Files vs arrays Files grow in size as needed arrays have a fixed size Files provides both sequential and random access arrays provide random access FHetypes Text and binary general or nontext files Ml Lecture Notes Java Reviewppt l62 Text Files Designed for easy communication with people Flexible and easy to use Not efficient with respect to computer time and storage End of line symbol Creates the illusion that a text file contains lines End of file symbol Follows the last component in a file Scanner class can be used to process text files Ml Lecture Notes Java Reviewppt l63 Text Files T is the endof Iine symbol is the endof le symbol Figure 111 Atext le with endof Iine and endof file symbols M1 Lecture Notes Java Review ppt 164 Text Files Example String fname lname int age Scanner fileInput File inFile new FilequotAgesdatquot try fileInput new ScannerinFile while fileInputhasNext fname fileInputnext lname fileInputnext age fileInputnextInt age fileInputnextInt39 Systemoutprintfquots s is d years oldnquot fname lname age end while fileInputclose end try catch FileNotFoundException e Systemoutprintlne end catch I Ml Lecture Note Java Reviewth 163 Text Files Open a stream to a file Before you can read from or write to a file Use class FileReader Constructorthrows a FileNotFoundException Stream is usually embedded within an instance of class BufferedReader That provides text processing capabilities StringTokenizer Used to break up the string returned by readLine into tokens for easier processing Ml Lecture Notes Java Reviewppt l68 Text Files Example BufferedReader input StringTokenizer line String inputLine try input new BufferedReadernew FileReaderquotAgesdatquot while inputLine inputreadLine null line new StringTokenizerinputLine process line of data end try catch IOException e Systemoutprintlne Systemexitl IO error exit the program end catch Ml Lecture Note Java Reviewth i6quot Text Files 0 File output You need to open an output stream to the file Use class FileWriter Stream is usually embedded within an instance of Class PrintWriter That provides methods print and println Ml Lecture Notes Java Reviewppt 168 Text Files Example try PrihtWriter output new PrihtWriterhew FileWriterquotResultsdatquot outputprihtlhquotResults of the surveyquot outputprihtlhquotNumber of males quot numMales outputprihtlhquotNumber of females quot numFemales other code and output appears here end try catch IOExcepti0h e Systemoutprintlne Systemexitl IO error exit the program end catch NM Lecture Notes Java Reviewpm 169 Text Files 0 Closing a file Syntax myStreamclose 0 Adding to a text file When opening a file you can specify if file should be replaced or appended Syntax PrintWriter ofStream new PrintWriternew FileOutputStreamquotResultsdatquot true Ml Lecture Notes Java Reviewppt l70 Object Serialization Data persistence Data stored in a file for later use Object serialization Java mechanism to create persistent objects Serialization Transforming an object into a sequence of bytes that represents the object Serialized objects can be stored to files for later use Ml Lecture Notes Java Reviewppt Object Serialization Deserialization Reverse process Interface java io Serializable Needed to save an object using object serialization Contains no methods Objects referenced by a serialized object are also serialized As long as these objects also implement the Serializable interface Ml Lecture Notes Java Reviewbrat l72 Summary Java packages Provide a mechanism for grouping related classes import statement Required to use classes contained in other packages Object in Java is an instance of a class Class Data type that specifies data and methods available Data fields are either variables or constants Methods implement object behavior Method parameters are passed by value Ml Lecture Notes Java Reviewppt l73 Summary Comments in Java Comment lines Multipleline comments Java identifier Sequence of letters digits underscores and dollar sngns Primitive data types categories Integer character floating point and boolean Java reference Used to locate an object Ml Lecture Notes Java Reviewpoi l74 Summary Define named constant with final keyword Java uses short circuit evaluation for logical and relational expressions Array Collection of references that have the same data type Selection statements if and switch Iteration statements while for and do Mi Lecture Notes Java Reviewphi
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'