CSE 205 - Study Guide - Exam 2
CSE 205 - Study Guide - Exam 2 CSE 205
Popular in Object-Oriented Program & Data
Popular in Computer Science and Engineering
This 22 page Study Guide was uploaded by RianMartins on Sunday October 18, 2015. The Study Guide belongs to CSE 205 at Arizona State University taught by Hsiao in Fall 2015. Since its upload, it has received 541 views. For similar materials see Object-Oriented Program & Data in Computer Science and Engineering at Arizona State University.
Reviews for CSE 205 - Study Guide - Exam 2
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/18/15
CSE 205 STUDY GUIDE EXAM 2 Common GUI components from iavaxswinq amp javaawt package The components used to construct the Graphical User Interface in Java are located in two main packagesjavaxswing ampjavaawt package Here is a picture of how they are distributed Dimension Font F ontMetrics Color Graphics Component E 4 l LayoatManager I Container I Classes in the javaawt 4 package Heavyweight J Applet J Frame J Dialog HUD I I I Heavy weight container classes gt JFrame JComponem L Lightweight Swing Components in the javaxswing package 0 The container that holds other Swing userinterface components in Java Graphical applications o It can be used in a Java program with a main method Applications gt JApplet o It is a subclass of the Applet class 0 Applet is defined in javaapplet package and JApplet is defined in javaxswing package You need to create a class that extends JApplet to create a Swing based Java applet Such class will not contain a main method 0 Instead it contains applet purpose methods such as init start stop and destroy The applet will be displayed with a html file or appletviewer gt JDialog o A popup window or message box generally used as a temporary window to receive information from a user or provide notification that an event has occurred 0 A dialog box is a temporary graphical window that pops up These heavy weight container classes can be displayed alone and are used to contain other components Applets public void init Initializes the applet Called just after the applet is loaded public void start Starts the applet Called just after the applet is made active every time the web page is visited public void stop Stops the applet Called just after the applet is made inactive when the page containing the applet becomes inactive public void destroy Destroys the applet Called when the browser is exited Also the default constructor can be created to be called by the browser when the Web page containing this applet is initially loaded or reloaded Applications using JFrame vs Applets JApplet A Java application is a standalone program with a main method A Java applet is a program that is intended to be transported over the Web and executed using a web browser Similarities Since they both are subclasses of the Container class all the user interface components layout managers and eventhandling features are the same for both classes Differences Applications are invoked by the Java interpreter and applets are invoked by the Web browser Applets have security restrictions Web browser creates graphical environment for applets GUI applications are placed in a frame Security Restrictions on Applets not to damage the system on which the browser is running Applets are not allowed to read from or write to the file system of the computer viewing the applets Note that a new security protocol allows you to use a security policy file to grant applets access to local files Applets are not allowed to run any programs on the browser s computer Applets are not allowed to establish connections between the user s computer and another computer except with the server where the applets are stored Layout Management Once we start adding more than one component to a container we need to consider how we organizearrange them For this purpose we can use layout managers A layout manager is an object that determines the manner in which components are arranged in a container Here is a list of commonly used layout managers they are defined in javaawt package 0 BorderLayout it organizes components into five areas North South East West and Center 0 FlowLayout it organizes components from left to right starting new rows as necessary 0 GridLayout it organizes components into a grid of rows and columns 0 BoxLayout it organizes components into a single row or a single column 0 CardLayout it organizes components into one such that only one is visible at any time o GridBagLayout it organizes components into a grid of cells allowing components to span more than one cell Some examples 0 BorderLayout import javaxswing to use Japplet JButton import javaawt to import BorderLayout manager public class AppletBorder extends JApplet public void init Container content getContentPane to use BorderLayout to add components contentsetLayoutnew BorderLayout add five buttons to the content pane of JApplet object contentaddbuttonl BorderLayoutCENTER contentaddbutton2 BorderLayoutNORTH contentaddbutton3 BorderLayoutSOUTH contentaddbutton4 BorderLayoutWEST contentaddbutton5 BorderLayoutEAST setSize27070 o FIowLayout Container content getContentPane to use FlowLayout to add components contentsetLayoutnew FlowLayout create three buttons JButton buttonl new JButtonquotButton1quot JButton button2 new JButtonquotButton2quot JButton button3 new JButtonquotButton3quot add three buttons to the content pane of JApplet object contentaddbuttonl contentaddbutton2 contentaddbutton3 setSize27070 o GridLayout First we create a JPanel object to organize buttonl and 2 using GridLayout JPanel panell new JPanel panellsetLayoutnew GridLayout2l panelladdbuttonl panelladdbutton2 Then create another JPanel object to organize everything using BorderLayout JPanel panel2 new JPanel panel2setLayoutnew BorderLayout At the center panel2 contains panell that contains buttonl and button2 add five buttons to panel2 panel2addbutton3 BorderLayoutNORTH panel2addbutton4 BorderLayoutSOUTH panel2addbutton5 BorderLayoutWEST panel2addbutton6 BorderLayoutEAST panel2addpanell BorderLayoutCENTER contentaddpanel2 content pane contains panel2 that contains everything setSize200200 o BoxLayout to use BoxLayout to add components verticallyYAXIS The first parameter is the container that needs to be laid out in this case it is the content pane of the JApplet contentsetLayoutnew BoxLayoutcontent BoxLayoutYAXIS create five buttons JButton buttonl new JButtonquotButtonlquot JButton button2 new JButtonquotButton2quot JButton button3 new JButtonquotButton3quot JButton button4 new JButtonquotButton4quot JButton button5 new JButtonquotButton5quot add five buttons vertically contentaddbuttonl create an rigid area between button 1 and button 2 contentaddBoxcreateRigidAreanew DimensionOlO contentaddbutton2 Create a glue between button2 and button3 Glue area changes its size contentaddBoxcreateVerticalGlue contentaddbutton3 contentaddbutton4 create an rigid area between button 4 and button 5 contentaddBoxcreateRigidAreanew DimensionO20 contentaddbutton5 setSize70270 Events and Event Handling components listener events A GUI is created with at least three kinds of objects components listeners and events An Event is an object that represents some activity to which we may want to respond When an event occurs the generator calls the appropriate method of the listener passing an object that describes the event To create a GUI program 0 Define and set up the components 0 Create a listener object by writing a class that implements a particular listener interface The Java standard class library contains several interfaces that corresponds to particular eventcatego es 0 After creating the listener we add the listener to the component that might generate the event to set up a formal relationship between the generator and listener 0 Define what happens in response to each event of interest Examples PushCounterjava modified from LewisLoftus textbook ButtonListener class represents a listener for button push action events private class ButtonListener implements ActionListener lt updates the counter when the button is pushed public void actionPerformed ActionEvent event pushes labelsetTextquotPushes quot pushes Fahrenheitjava modified from LewisLoftus textbook TempListener class represents an action listener for the temperature text field private class TempListener implements ActionListener Performs the conversion when the enter key is pressed in the text field public void actionPerformed ActionEvent event String text fahrenheitgetText int fahrenheitTemp lntegerparselnt text int celciusTemp fahrenheitTemp 32 59 resultLabelsetText lntegertoString celciusTemp Inner Class gt A class can be defined inside of another class and it is called a quotinner class or an nested daam gt In general a nested class is defined with private visibility so that it can be accessed only by the dasscontah ngit A nested class can access all instance data and methods of the class containing it A nested class produces a separate bytecode file If a nested class called Inside is declared in an outer class called Outside two bytecode files will be produced V39V V7 public class Outside private int num private Inside obj private class Inside public double num2 Exception amp Error Handling An Exception is an object that describes an unusual or erroneous situation If an exception is ignored by the program the program will terminate and produce an appropriate message Example public class DividingByZero Deliberately divides by zero to produce an exception public static void main Stringll args int numerator 10 int denominator O Systemoutprintln numerator denominator Systemoutprintln quotThis text will not be printedquot Output Exception in thread quotmainquot javaangArithmeticException by zero at DividingByZeromainDividingByZerojava7 We can avoid the termination of a program caused by an exception by using try statements trY the line that throws the exception is included here catchput the exception object produced in try eg IOException finally the statements inside of finally are always executed whether there was an exception on try or not finally clause is used to manage resources or to guarantee that particular parts of an algorithm are executed Throws clause The appropriate exception is appended to the header of a method definition where the excep onisthromniorpropagated Example public static void main String args throws lOException the line that throws the exception is here Other Examples of exceptions If a string quotcodequot does not have enough length the methods charAt and substring can throw StringlndexOutOfBoundException If the substring of code contains a nondigit character the Method parserlnt can throw NumberFormatException How do we know which methods throw exception and which exception a method throws See API specification and description of each method For instance see the method quotparselntquot of the class quotIntegerquot t throws NumberFormatException I O Streams A stream is a sequence of bytes that flow from a source to a destination The IO streams can be categorized in three ways 0 Input streams 0 Output streams or 0 Character streams deal with text data 0 Byte streams deal with byte data or 0 Data streams a source or destination 0 Processing streams alters or manages information in the stream Three standard IO streams 0 standard input Systemin 0 standard output Systemout 0 standard error Systemerr Read amp Write texts and obiects Reading Text Files Instead of reading from the standard input we can read from text files using the classes FileReader and BufferedReader The parameter for the FileReader constructor is the name of a file to be read The constructor of FileReader can throws FileNotFoundException if the file specified in the parameter is not located It is a good practice to close the file after finishing reading it Writing Text Files We can write into text files using the classes FileWriter BufferedWriter and PrintWriter The FileWriter class represents a text output file The parameter of the FileWriter constructor is the name of a file to be written The PrintWriter class provides print and printn methods similar to the standard IO PrintStream class The Buffered Writer class gives the output stream buffering capabilities which makes the processing more efficient 7NOG Ermaplow wnlmb pubic Sa39 0 Von mam lmqgm 39H ITOWS Slang Julianam wfpoffxf i F chrllcr 1f ncw tlQomekr fwien mai BU3yer Cw gullcrwnlcr it d Rnl uri pod new Ridwh b 5 32 Pw Pr39n lp f e 463 L90 Pu Scymf n Graphics class to draw shapes lines and strings gt Defined in javaawt abstract windowing toolkit package gt It is used to draw shapes lines and strings Paint method in JAppIet public void paintGraphics page The paint method is invoked automatically whenever the graphic elements of the applet need to be painted to the screen 2 Some methods of the Graphics class void drawRectint x int y int width int height paints a rectangle with upper left corner xy and dimensions width and height void fillRectint x int y int width int height same as drawRect but with inside filled with a foreground color void drawOvalint x int y int width int height paints an oval bounded by the rectangle with an upper left corner of xy and dimensions width and height void fillOvalint x int y int width int height same as drawOval but with inside filled with a foreground color void drawLineint x1 int y1 int x2 int y2 paints a line from point x1y1 and point x2y2 void drawStringString str int x int y paints the character string at point xy extending to the right void drawArcint x int y int width int height int startAngle int arcAngle paints an arc along the oval bounded by the rectangle defined by x y width and height The arc starts at startAngle and extends for a distance defined by arcAngle positive counter clockwise void fillArcint x int y int width int height int startAngle int arcAngle same as drawArc but with inside filled with a foreground color void setColorColor color sets this graphics content s foreground color to the specified color Color getColor returns this graphics content s foreground color Examples pagedrawRect 50 20 100 40 U1 a W 4i llll pagedrawOval 175 20 50 80 bunding rectangle if 50 pagedrawLine 10 20 150 45 or pagedrawLine 150 45 10 20 1 150 pagedrawArc 175 20 50 80 30 90 Arc is drawn MS I x l i is 20 I Mfre Arc angle free 39339 Start angle aka oundin rectangle i Y 50 L Linear Search and Binary Search Algorithms Linear Search Algorithm gt Looks sequentially at each element of a given collection of elements until we either come to the end of the sequence of elements or find an item that equals to X the element that we are searching for public int linearSearchint A int x for int i0 iltAlength i return i return 1 returns 1 when the element is not found Binary Search Algorithm gt It is used to look up a word in a dictionary or a name in a phone book gt It uses Divide and Conquer approach gt A list needs to be sorted before a binary search precondition public static int binIterint num int x int n numlength if xgtnumn l xltnum0 return 1 x is not found int i 0 int j n l int k while iltj k int Mathfloorij20 if xltnumk jk else i kl if numi x return i x is found else return 1 x is not found Example Search for x 11 5 2 7 9 11 12 20 31 x gt 9 so x is in right half segment 11 12 20 31 x lt 12 so x is in left quarter segment 11 12 x 11 We found x Selection Sort Insertion Sort MergeSort QuickSort algorithms Sort algorithms are very useful in computer programming There are a lot of ways to do it such as Selection Sort Insertion Sort MergeSort and Quicksort Selection Sort It sorts a list of values by successively putting particular values the smallest value among unsorted values in their final sorted position 2 Find the smallest Lil a el eaehange so that the smallest will be at the le mast 7 i i 7 73 Fin1 the seeeml smallest and exchange so that the End smallest still he at the Em left nlest Find the thde smallest 3 and exchange 9 Find the famth smallest The fem39th smallest llEl all vEEld in the rtght peattte he exchange public static void selectionSort int numbers int min temp for int index 0 index lt numberslength l index min index for int scan indexl scan lt numberslength scan if numbersscan lt numbersmin min scan Swap the values temp numbersmin numbersmin numbersindex numbersindex temp The complexity of the selection sort algorithm is order of n2 Insertion Sort It sorts a list of values by repetitively inserting a particular value into a subset of the list that has already been sorted 3 939 5 ll 2 9 should ho luso tod after 3 no ohsugo 3 I 9 ll 2 should to lustsmod hotui39oou 3 and El 3 5 9 ll 2 ll should ho illuso od before 3 l K 3 El 2 2 should to lustsmod hotui39oou 1 and 3 l 2 3i 5 9 public static void insertionSort int numbers for int index 1 index lt numberslength index int key numbersindex int position index shift larger values to the right while position gt O ampamp numbersposition l gt key numbersposition numbersposition l position numbersposition key The complexity of the insertion sort algorithm is order of n2 AergeSort Merge Sort is a recursive method that uses Divide and Conquer approach It divides elements evenly and invokes itself to sort two subcollections subarrays of elements iii39ilcling premises Merging process 2369 public static void mergeSortint num int start int end base case is when start end does nothing if start lt end recursive case int mid int Mathfloordouble startend20 mergeSortnumstartmid mergeSortnummidlend mergenum start mid end public static void mergeint num int start int mid int end get the length of the first half subarray int nl mid startl get the length of the second half subarray int n2 end mid int left new intnl int right new intn2 i is used for the array quotleftquot j for quotrightquot k for quotnum int i j k copy the elements in the array quotnumquot to the arrays quotleftquot and quotrightquot for i0 iltnl i lefti numstarti for jO jltn2 j rightj nummidlj i0 jO kstart merge left and right into quothumquot while i lt hl ampamp j lt h2 if lefti lt rightj humk lefti i else humk rightj j k copy the rest of the subarray that did not get copied if i nl while k lt end humk rightj k j else if j h2 while k lt end humk lefti k i Quicksort The quick sort uses the strategy of divide and conquer like merge sort Its idea is to rearrange the element in the range so that no element in the first subarray is larger than any element in the last subarray ie all elements in the first subarray are smaller or equals to a pivot value and all elements in the last subarray are greater or equals to a pivot value There are several ways to pick a pivot value but one way is to pick the first element of a given array If we have an array containing 53264137 And if we use quot5 the first element of this array as a pivot to partition we can arrange it into two sub arrays as 3 3 2 1 4 6 5 7 this can be viewed as one array 3 3 2 1 4 6 5 7 The first subarray contains elements smaller or equals to 5 and the second subarray contains elements greater or equals to 5 We can repeat the similar partitioning process on two sub arrays to get four subarrays and so on At the end we will have a sorted array public static void quickSortint elements int from int to if from lt to int p partitionelements from to quickSortelements from p quickSortelements pl to end of quickSort method public static int partitionint elements int from int to int pivot elementsfrom int i from l int j to 1 while i lt j until i and j cross each other i move i towards right until we find an element greater or equals to than pivot while elementsi lt pivot i j move j towards left until we find an element smaller or equals to than pivot while elementsj gt pivot 3 we swap the two elements if i lt j int temp elementsi elementsi elementsj elementsj temp end of the while loop return the index where the array can be divided partitioned return j end of partition method What is biqOh notation The bigOh notation is the most common way to express the time complexity of an algorithm It is used to express the worst case running time The worst case running time of the linear search for instance can be expressed as a function of n where n is an input size 39HMc1nc2 where c1 and c2 are positive constants Intuitively we can see that when n input size gets larger the time that takes to execute the linear search grows Tn grows proportionally to n And when n gets very large constant c2 has a very small effect on the running time We say that the complexity of the linear search is On but here is a formal definition of O pronounced as quotbigOh notation Definition of Onotation If there exist positive constants a and c such that Tn lt agn for all n larger than c Then we say that Tn Ogn This means that agn is an upper bound of Tn For the linear search gn n Note that there is more than one such function gn For instance it is correct to say that Tn Onz for the running time of the linear search though this is not a tight upper bound Recursive methods A recursive method is a method that calls itself To avoid infinite loop inside the method we must follow some crucial steps All recursive methods should have as the first statement of the method a base case and a recursive case The base case is a condition that checks whenever it should return a value and get out the method The recursive case is where the actual call for the function is located See some examples below 0 Recursive factorial public int factorialint n if number lt 1 test the base case return 1 else return n factorialn l o Recursive reverseStrinq public String reverseStringString str ifstrlength return str return reverseStringstrsubstring1 strcharAtO How to construct a recursive method 1 Identify your subproblem ie the same problem as the original problem but on a subset of the original input 2 Think how you can use a solution of the subproblem to solve the original problem Consider an example to sum all the elements of an int array the original problem is to compute the sum from 1 to n and the subproblem is to compute the sum from 1 to n1 If we had the sum from 1 to n1 then we just need to add n to it to get the sum from 1 to n 3 Also consider your base cases 4 When converting an iterative method to a recursive method in some cases additional parameters might be needed One such parameter is the variable used to increment or decrement the loop in iterative methods You can practice on writing recursive methods starting computations on power XV and factorials
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'