Popular in Course
Popular in Computer Information Technology
verified elite notetaker
This 77 page Class Notes was uploaded by Kathleen Cartwright on Monday September 28, 2015. The Class Notes belongs to CIS110 at University of Pennsylvania taught by Staff in Fall. Since its upload, it has received 27 views. For similar materials see /class/215380/cis110-university-of-pennsylvania in Computer Information Technology at University of Pennsylvania.
Reviews for INTROTOCOMPPROG
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: 09/28/15
Introduction to Programming WI39fz Java for Beginners Frame Call by Value Stack Frame for method calls I Whenever a method is called some memory is set aside to contain information related to the call I Example parameter values current statement being executed etc I This is called the frame for the method call int add int number1 int number2 int sum number1 number2 return sum I The frame is discarded when the method returns I This implies parameters and local variables variables declared within method are discar ed I Hence this explains the reasoning for scope rules Call by Value IWe call a method like this result add El 3 int add int int Actual parameter values are copied into formall de ned parameters number2 int sum number1 number2 return sum cls11o CS110 Call by value contd int m 391 The value ofmie 1is int resut copied to the formal parameters absoluteint m lt 0H n n1 The value ofn is returned but the variable n is thrown away 3 cls11o Methods calling other Methods I boolean isLeapYearint year void eapYearsint start int end int X start SystemoutprintlnquotLeap years between quot start quot and end Whiex lt end ifisLea pYearx Systemoutprintlnx x cls11o Stack I Suppose a call of method m1 is being executed so that a frame forthe call exists eg eapYears2000 2008 I Suppose the method m1 While executing calls another method m2 eg eapYears method calls isLeapYearx I Aframe for m2 is created amp now at this point two frames exist I If m2 caes another method m3 then a third frame is created I The frames are destroyed in the order in which they were created I Eg Call to m3 is rst completed and hence discarded then m2 and nally m1 I Follows rstinIastout principle and the section of memory that allocates memory during method calls is known as stack cls11o In rr39oduc rion ro Programming wfh Java for Beginners Algorithm to Program Formulating a Solution I First Think Algorithmically Well defined step by step procedure I Use psuedocode to write out your steps English like code It allows the designer to focus on the logic of the algorithm with0ut being distracted by details of language syntax I Then Translate the solution into programming language I Put together the components we have so far declarations assignme on t res CIS110 Example Fibonacci sequences I A Fibonacci sequence is an infinite list of integers I The first two numbers are given I Usually but not necessarily these are 1 and 1 I Each subsequent number is the sum ofthe two preceding numbers 1123581321345589144 I Let s write instructions to compute the sequence as long a number less than 1000 CIS110 Starting the Fibonacci sequence I We need to initialize two numbers in the sequence Set first to 1 Set second to 1 I We need to print these out Print first and second I We need to compute and print the next number Set next to sum of first amp second print next CIS110 Taking the next step I Now what I Need to add second and next nextnext second next I What if the sequence is to long I do want to make 100s of variables to hold each item I The sequence so far is first second next I Do I see a attern emer39in39 CIS110 Preparing to make many steps I We need to make these moves first second next first second next 1 1 2 1 2 3 first second next I We can do it like this 2 3 5 Set first to second 3 5 8 Set second to next I We can put these statements in a loop and do them as many times as we please CIS110 Complete Psuedocode Set first to 1 Set second to 1 Print first and second while next number lt 1000 Set next to sum of first amp second Print next Set first to second Set second to first CIS110 Psuedocode Rules I Can use words such as while if elseif I Eg for1 to n I Do not specify data declarations or types I Use Words that specify an action such as set reset increment compute calculate add sum multiply print getinput I Use indentation tor DIOCK or code ie CIS110 Translate if to Programming Language int first 1 int second 1 int next u Systemoutprintfirst quot quot Systemoutprintsecond quot quot while next lt 1000 next first second Systemoutprintnext quot quot first second second next CIS110 Introduction to Programming WI39fz Java for Beginners API Random Class Math Class Dynamic vs Static Recap Java Library I Java provides a huge library or collection of useful programs I A gold mine of welltested code that can save you countless hours of development time I This huge librarr information is 7 rovided in API Application Programming Interface cls11o cls11o Example with Java 131 l Elle Edit view ngmiles Iaals Help szzw z Platfnrm Sui Ed v131 A Classes E WPackage r eczled Index m lav I pm my Es V Javaw 2 Platform Standard Edition v 131 API Speci cation Ths dacumentxs the API speci cauanfmthe imz eaan vexsmnl z t squot Descm39 nu des the classes necessi p e alas calm Views The link bar39s Package Class Use Tree Deprecated index Help PREV NEXT FRAMES JL FR l 1E3 Oveniew is Where you start out Index is handy for looking up methods Help is the obvious lfgou don t like frames you can choose N FRAMES JavaTMZFIarmrm Standard Ed 50 Deprecated methods are those that have been replaced by better methods and should not be used I Trees is View of hierarchy of programs in folders packages I More clear when we do inheritance cls11o Class Panel gt I This panel shows both classes and interfaces I We haven t yet talked about interfaces I Note that some classes have names similar to primitive types Boolean Character m haracter V haracteLUnicodeBlocl ass lassLoader 4 ClS11 Random Class I A class to create Random numbers I Constructor Summary shows the objects of this ype can be created I Eg Random r new Random I Method Summary shows that it can generate random values of types I integers doubles etc I Eg xnextlnt6 Generate a integer numbers between 0 inclusive and 6 exclusive ClS11 Packages and import Statements I What is a package I Basically it39s a directory that has a collection of related classes Random Class description containsjavautilRa d m I Indicating that the Random class code is stored In the directory 39 H il somewhere on your mach39ne utii snort for utility package I Inorderto use implemented work need to tell Java compiler where class is located I Use import statement iinponiava utll Random Another Way is to usethe asterisk Wildcard character import iava utll import staternent is Written outside tne ciass description in a tile ClS11 Math Class I Math Class Interface I Field Summary Has two constants PI and E Constructor Summary has no public constructor Methods Summary many methods all which are static Method Details eg sqrt takes a double and returns a double ClS11 Math Class Description I Notice the phrase javalang at the top ofthe main panel above the word Math I This means that the Math class is part of the core Java language and hence can be used directly No need of an import statement gt MathPl 3141592653589793 a 2718281828459045 gt Mathsqrt25 w gt Mathpow210 gt Mathcos0 gtIMathcos2 MathPl Cl5110 1 What39s different about Math Class I It s different from OOP class It does not have datastate I We only need one Math class Not multiple instances I No need to instantiate it Hence no public constructor All of its variables and methods are static static means applies to the class as a Whole vs applies to an individual instance cls11o How the Math Class is Implemented public class Mathi public static final double PI 3141592653589793 public static double sin double d public static double sqrtdouble d i gt Math PI 3 141592653589793 gt Math sqrt 25 50 cls11o Dynamic Variables and Methods I All instance variables object data and methods object behavior created Without static keyword I Note There is no dynamic keyword in Java I Dynamic by default I In general dynamic refers to things created at run time ie when the program is running I Every object gets its own dynamic instance variables I Every object effectively gets its own copy of each dynamic method ie the instructions in the method cls11o Static Variables amp Methods in General I A static method that is public can be accessed outside class definition I ClassNamemethodNameargs I double result Mathsqrt250 I A static variable that is public may be accessed I Using ClassNamevarableName Eg MathPI MathE I Static variables act as global variable ie accessible Within any static method cls11o Static Variables with 00 class I Static means pertaining to the class in general not to an individual object I Variable is declared with the static keyword outside all hods I Keyword static goes before type of the variable I Eg static double PI39 T ere is one variable numTickets for the class not one per object I A Static Variable IS snared by all Instances It any I All instances may be able readwrite it cls11o Use of static variable I I With Constants I Constants are variable that don t change I Constants are made static because there is no need for more than one copy it I Example class Deck public static final int JACK 11 public static final int QUEEN 12 public static final int KING 13 public static final int SPADE 1 cls11o Use of static var39iable II I Providing communication among instances of classes ie objects I In this case using static variable is way of accessing some common resource cls11o Example Ticket No Generator public class Ticketl shared private static int num39I39icketsSold 0 one per object private int ticketNum public Ticket num39I39icketsSold num39I39icketsSold 1 ticketNum num39l39icketsSold Notestatic variable is used to generate ticketNum and in way keeps track ofthe number oftickets sold which can be accessed by all objects CS110 16 cls11o Static Methods with 00 class A method may be declared with the static keyword Static methods live at class level not at object level Static methods can access static variables and methods but not dynamic ones I How could it choose which one We have not created any obje sye Example public static int getNumSold return numTicketsSold Example Ticket No Generator public class Ticketl private static int num39l icketssold o shared private int ticketnum one per object public TicketOl nuln39l icketssold nuln39l icketssold l ticketnum nuln39l icketssold public static int getnumbersoldo return num39ricketssold public int get39l icket umbero return ti ketnum public string getInfo return ticket ii W ticketnum quot num39l icketssold quot tickets soldquot cls11o 18 cls11o Ticket class Interactions gt Ticketget umbersold 0 gt Ticket tl new Ticketo t1getTicketllullI t1getInf0 quotticket it 1 l tickets soldquot gt t1getllullibersold l gt Ticket t2 new Ticketo gt t2getTicketllullI t2getInf0 quotticket it 2 2 tickets soldquot gt tlgetlnfo quotticket it 1 2 tickets soldquot gt Ticketgetllumbersold 2 Special method called main To have standalone Java Application we need a method called main I Main is known as a program s entry point ie where the program it starts getting executed I Usually the main method gets things started by creating one or more objects and telling them what to do public static void mainStrin args Point p new Point4 l creates a Point The main method belongs to the class in which it is written I ce it is static ie does not belong to any ob39ect I Instance variable cannot be referenced from main unless the object is ated I A er compiling to execute the program Dr va Press Run button to create the object In Dr Ja a39 39 39 r 39 CIS110 Example Main inside OOP class public class Point private int x private int y public static void mainString args x 5 y 10 all are wrong Must create the Point object to initialize x amp y To avoid confusion put main in completely by itself in another file cls11o When to use static with OOP I A variable should be static if I It logically describes the class as a whole I There should be only one copy of it I A method should be static if I It does not use or affect the object that receives the message it uses only its parameters cls11o Static amp Dynamic Rules Recap I static variables and methods belong to the class in general not to individual objects I The absence of the keyword static before nonlocal variables and methods means dynamic one er obrec instance A dynamic method can access all dynamic and static variables and methods in the same class I A static method can not access a dynamic variable How could it choose or which one I A static method can not call a dynamic method because dynamic method might access an instance variable cls11o Introduction To Programming wit7 Java for Beginners Array Discussion Arrays I Creating an array Type new Type I What if is 0 I An object is created with length field contain 0 Le arrayName length 0 I Then data 0 would give a ArraylndexOutOfBoundsException IWhatifislt0 I Negative inputs give runtime error NegativeArraySizeException HOW can we reverse an array Fromm I TO I Need to update the original array Solution void reverseint b int left 0 ll index ofle most element int right blength1 ll index of rightmost element while le lt right exchange the lelt and right elements int temp ble blelt bright bright temp move the bounds toward the center le right Passing an Army as a parameter I Passing an array to a parameter is passing the heap heap address of where the array is located I Hence we can change the contents ofthe actual address IsInDatabase Interactions I Dr Java Interactions gt PersonDB people new PersonDBo gt peopleislnDatabasequotfloquot true gt peopleislnDatabasequotrexquot false Per39son Database public class PersonDBl private PersonI people public PesonDBl peopl ew Person I new Personquotjoquot25 ew Personquotfloquot18 new Personquotmoquot 19 l Returns True if SearchName is foun public boolean isInDatabaSeSting seachName Comp1ete l l Solution isInDatabase public boolean islnDatabaseString searchName boolean value false forint i 0 i lt peoplelength i use equals or equalslgnoreCase method in String class part ofthe java language ifpeopleigetName0equalslgnoreCasesearchName value true return value Solution with Error Checking public boolean islnDatabaseString searchName ifpeople null peoplelength 0 return false forinti 0 i lt people length i ifpeopleigetNameOequalslgnoreCasesearchName return true return false GUI building with Swing By David Mastuszek Edited by Diana Palsetia g Jun723708 How to build a GUI Create a window in which to display thingsiusually a JFrame for an application or a JApplet for webbrowser Use the setLayoutLayoutManager manager method to specify a layout manager Create some Components such as buttons panels etc Add your components to your display area according to your chosen layout manager Write some Listeners and attach them to your Components Interacting with a Component causes an Event to occur A Listener gets a message when an interesting event occurs and executes some code to deal with it Display your window Im ort theinecessary packages The Swing components are in javax SWing so you always need to import that for a Swing application Swing is built on top of AWT and uses a number of AWT packages including most of the layout managers so you need to import javaawt Most listeners also come from the AWT so you also need to import javaawtevent A few listeners such as DocumentListener and ListSelection Listener are speci c to Swing so you may need to import javax swing event For more compleX GUIs there are additional javaawtsomething and javax swingsomething packages that you may need to import Make a Container For an application your drawing window is typically a JFrame JFrame is a Container object Container is like a drawing sheet that holds the components JFrame frame new JFrame JFrame frame new JFramequotTeXt to put in title barquot However the frame is not displayed until it is made visible framesetVisibletrue You can create a JFrame in your main class It s often more convenient to have your main class extend JFrame class myClass extends JFrame Add a la out manager I The most important layout managers are l BorderLayout l Provides ve areas into Which you can put components I This is the default layout manager for both JFrame and JApplet FlowLayout l Components are added le to right top to bottom GridLayout l Components are put in a rectangular grid I All areas are the same size and shape BoxLayout l Creates a horizontal roW or a vertical stack I This can be a little Weird to use GridBagLayout l Too complex and a danger to your sanity Spri ngLayout I New very exible layout manager Add com onents to containers I The usual command is container add component I For FlowLayout GridLayout and BoxLayout this adds the component to the next available location I For BorderLayout this puts the component in the CENTER by default I For BorderLayout it s usually better to use container add component BorderL ayout position I position is one of NORTH SOUTH EAST WEST or CENTER Create components JButton button new IButtonquotClick mequot JLabel label new JLabelquotThis is a JLabelquot JTextField textField1 new JTextFieldquotThis is the initial textquot JTextField textFiele new JTextFieldquotnitial textquot columns JTextArea textArea1 new JTextAreaquotnitial textquot JTextArea textAreaZ new JTextArearows columns JTextArea textArea3 new JTextAreaquotnitial textquot rows columns JCheckBox checkbox new JCheckBoxquotLabel for checkboxquot JRadioButton radioButton1 new JRadioButtonquotLabel for buttonquot ButtonGroup group new ButtonGroup groupaddradioButton1 groupaddradioButton2 etc This is just a sampling ofthe available constructors see the javaxswing API for all the rest BorderLayout public class BorderLayoutExample extends IFrame public void createGui setLayout new BorderLayout addnew IButtonquotOnequot BorderLayoutNORTH addnew JButtonquotTwoquot BorderLayoutWEST addnew IButtonquotThreequot BorderLayoutCENTER addnew JButtonquotFour39 BorderLayoutEAST addnew IButtonquotFivequot BorderLayoutSOUTH addnew IButtonquotSixquot GridLayout 7 public class GridLayoutExample extends JFrame public void creatGui setLayoutnew GridLayout2 4 add new JButtonquotOnequot add new JButton 39Twoquot iii Gndlaycugamani dih new JButton 39Fourquot I addnew JButtonquotThreequot 39 addnew JButtonquotFivequot 0 Fnur rue Illree Nested layifouts A JPanel is both a Container and a Component l Because it s a container you can put other components into it I Because it s a component you can put it into other containers All but the very simplest GUIs are built by creating several JPanels arranging them and putting components possibly other JPanels into them I A good approach is to draw on paper the arrangement you want then nding an arrangement of JPanels and their layout managers that accomplishes this d An example nested layout Container container new JFrameo JPanel p1 new JPanel p1setLayoutnew BorderLayout p1addnew JButtonquotAquot BorderLayoutNORTH 39 also add buttons B C D E JPanel p2 new JPanel p2setLayoutnew GridLayout3 2 p2addnew JButtonquotFquot also add buttons 3 H I J K JPanel p3 new JPanel p3setLayoutnew BogtltLayoutp3 BogtltLayoutY p3addnew JButtonquotLquot also add buttons M N O P containersetLayoutnew BorderLayout containeraddp1 BorderLayoutCENTER containeraddp2 BorderLayoutSOUTH containeraddp3 BorderLayoutEAST i Quitting the program setDefaultCloseOperationJFrameEXTONCLOSE Other options are DONOTHNGONCLOSE HIDEONCLOSE and DISPOSEONCLOSE Create and attach listeners JButton okButton new JButtonquotOKquot okButtonaddActionListenernew MyOkListener class MyOkListener implements ActionListener pubic void actionPerformedActionEvent event ode to handle okButton click A small class like this is o en best implemented as an anonymous inner c ass OR Or have your main class im lement ActionListener at same time it extends JFrame I prefer s one Usin an anonymous inner class Instead of okButtonaddActionListenernew MyOkListener class MkaListener implements ActionListener void actionPerformedActionEvent event co e to handle OK button c 39c You can do this okButtonaddActionListenernew ActionListener 39 voi actionPer ormedActionEvent event code to handle OK button click Keep anonymous inner classes very short typically just a call to one of your methods as they can really clutter up the code actionPerformed method If there are multiple buttons then we want to know which button was pressed event getSource return reference heap address to the object component that was pressed ifeventgetSource button1 do something else if eventgetSource button2 do something different Su ested program arrangement 1 clan SomeCla implement Actiontitener Declare component a in ame variable JFrame frame Can alo oenne tnern nere ifyou prefer JButton button public tatic void main5mng arg t newSomeClacreateGui I Denne component and attach lptener in a method noro createGuv frame new JFrameO button new JButton OK frameaddbutton we default Bordertayout buttonaddAcLionLitenerthi l public void actronperrorrneolxlctrongnent event Code to handle button clrcl goe nere l Su ested k rogram arrangement 2 clam SomeCla extend JFi39ame implement I Declare component a inxtance variabl JFi ame frame H Don t need hi JBqun button ActionLitener e public talic Void mairiSririg argx newSomeClacreaLeGui l Denne component and attacn litener in a metnod void createGuiOl frame nevv JFrameO Don t need tni button nevv JButton OK addbutton u Wax renneed button buttonaddActionLitenerthi39 u Ue an inner clam a your litener public Void actionPerformedActionEent event Code to nandle button click goes here Com onents use various listeners JButton JMenultem JComboBox JTextField addActionListenerActionLi t ner public void action er rmedActionEvent event JCheckBox JRadioButton39 addltemListenerItemListener ublic void itemStatecnangedutemEvent event JSlider addChangeListenerChangeListener public void stateChangedChangeEvent event JTextArea mentL public void insertUpdateDocumentEvent event public void removeUpdateDocumentEvent event public void changedUpdateDocumentEvent event i tener Gettin values I Some user actions normally cause the program to do something clicking a button or selecting from a menu I Some user actions set values to be used later entering text setting a checkbox or a radio button I You can listen for events from these but it s not usually a good 1dea l Instead read their values When you need them String myTeXt myJTeXtFieldgetTegtltt String myTeXt myJTeXtAreagetTeXt boolean checked myJCheckBoxisSelected boolean selected1 myJRadioButton1isSelected Enablin r and disabling components I It is poor style to remove components you don t want the user to be able to use I Where did it go It was here arninute ago I It s better to enable and disable controls I Disabled controls appear grayed ou I The user may still wonder why but that s still less confusing anyCamponent setEnabled enabled I Parameter should be true to enable false to disable Introduction to Programming WI39fz Java for Beginners Fundamentals Part I Comments amp Literals Operators amp Expressions Primitive Types amp Variables Declaration amp Assignment Statement Strings and Printing Recap I Computing I Use computer to solve a task I Why lnherently fasterthan humans I Programming Language I Language that humans can write to instruct the gt Syntax grammar of language gt Semantics meaning of the language I Compiler I Checks for syntax errors I Furthertranslates the language into what computer can understand more on this later CIS110 2 Comments I Comments are used to make code more understandable to humans I Java Compiler ignores comments this is a single line comment this is a multi line comment CIS110 3 Literals I Literals are the values we write in a conventional form whose value is obvious 3 II An integer has no decimal point 105 Ila oating point double a Ila character has single quotes true II The boolean literals are of two types true false hello world II A string literal cls11o Arithmetic Operators Relational Operators I to indicate addition I equal to I to indicate subtraction 39 l nOt equal to I to indicate multiplication l lt leSS than I to indicate division I gt greaterthan I to indicate remainder of a division 39 lt less than equal to integers ony I gt greater than equal to I parentheses to indicate the order in which to do things I Note Arithmetic comparisons result in a Boolean value of true or false CIS110 5 CIS110 5 Boolean or Logical Operators EXPF39GSSIOH I Like In English conditional statements formed I An expression is combination of literals and operators using quotandquot quotorquot and quotnotquot I An expression has a value I Given an expression DrJava prints its value I In Java Welcome to DrJava I H gt OR operator gt true if either operandquot is true 3 I ampampgt AND operator 2 3 5 gt true only if both operands are true gtia A Equality operator I gt NOT operator false gt Is a unary operator applied to only one operand gt true ampamp false using the logical AND gt Reverses the truth value of its operand false gt true false using the logical OR Operand a quantity upon which a operation is t ue Performed Later we ll see that an expression may contain other things CIS110 7 cs110 Such as variables method calls a Value amp Type I Value Piece of data 23 105 true a I Type Kind of data integer floating point boolean truefalse character Expression Value Type 23 23 integer 105 20 125 fractional 3 5 6 33 integer 3 415 2 2 true ampamp false 2 2 851 Note Integer dIVIsIon truncates Types a very important concept I All data values in Java have a type I The type of a value determines I How the value is stored in computers memory I Maxmin value that data can be I What operations make sense forthe value I How the value can be converted cast to related values I Note Types are very helpful in catching programming errors CIS110 1o Primitive types I Values that Java knows how to operate on directly I We will work with 4 of Java s 8 primitive types I Integer int 1 42 I Fractional or floating point number double 1 314159 299792458E8 I Character char i JV y my I Truth value boolean true false I Java s othertypes are byte short long float CIS110 11 Storage Space for Numeric Type I Numeric types in Java are characterized by their size I how much you can store computers have nite memory I Integer and Character types Type Value Range 0 65535 Char Note Each char is assigned a unique numeric value amp numeric value is stored int 2147483648 2147483647 I Floating point types Smallest gt 0 CIS110 12 Variables I A variable is a name together with an associated value I Value is stored in computer s memory I Instead of knowing the location we access the value by the name it is associated with I Variable must always be associated with type I It tells the computer how much space to reserve for the variable I The value stored can vary over time cls11o Identifiers I Identifiers are names that you as a coder make up I Variable names I Also class and method names more later I Java Rule for Variable names I Must start with a letter I May consist of alphanumeric characters and the underscore I Cannot use keywords such as int double etc I If not followed compiler will complain syntax error cls11o Identifiers contd I Style Rule for Variable names I Should be a noun that starts with an lowercase letter gt Eg sum average I Ifthe name has multiple words capitalize the start of every word except the first style rule gt Eg firstName lastName I Note Style rule are for consistency and readability of programs I Compiler will not complain ifthe rule is not followed I If you do not follow the rule you get penalized in grading cls11o Declaring variables I All variables must be declared before being used I Done with a declaration statement I Declaration statement I Specifies the type ofthe variable followed by descriptive variable name followed by semicolon I Examples int seats double averageHeight boolean isFriday char initial cls11o Storing value into Variables I To store values into variable we use the assignment operator ie l Variable Expression gt assignment statement I Important I Assignment statement must end with a semicolon I When a variable is assigned a value the old value is discarded and totally forgotten I Examples seats 150 averageHeight 21 174 158 3 isFriday true cls11o Variable value and type I The value of a variable may be changed X 57 assuming X is an integer I However its type may not X true this causes an syntax error iecompiler Will complain I Sometimes conversions be forced but with some precision loss I Eg int X int 35 X becomes 3 gt This is known as castin I Note Any int can be converted to a double ie gt double 2 3 cls11o Initializing Variables I It s good idea to declare and initialize a variable in one statement double milesPerHour 505 boolean isTall true int age 17 Note I If a variable is not initialized before using it you may or may not get a compiler error I This will depend where in the program your variable is declared I More on this later cls11o Constants I Variables that don t change I Initialize a value and never change it I Program s computation might be affected ifa variable is not consistent throughout I Rules I Java Rule Must have the keyword finebefore the t e I Style Rule Should have all caps for variable name gt If multiple words use underscore between words final double PI 314 final int MILESPERGALLON 32 cls11o Putting it all together I Example nal double Pl 314 double radius 3 double area radius radius Pl double circum 2 Pl radius I In Dr Java to view the value of area afterthe statements are executed do the following shortcut gt Area 2826 CIS110 21 Another Important Type String I A String is an Object not a primitive type I Java also has objects cover objects later I String is composed of zero or more chars I A String is a sequence of characters enclosed by double quotes quotJavaquot quot3 Stoogesquot quot39ilJl I means concatenation for strings quot3quot quot quot quotStoogesquot 3 Stoogesquot I Automatic conversion of numbers to strings 3 quot quot quotStoogesquot 3 Stooges CS110 22 Examples of String creation In Dr Java gt String s2 quothelloquot gt s2 quot youquot quothello youquot gt s2 quotThe result is quot 100 gt s2 quotThe result is 100quot CIS110 23 Systemoutprintnstring I Command that prints string to the output screen I Can also print literals and expression values I The answer is automatically converted to string I Prints every time on a new line I Useful in finding semantic errors in a program Systemoutprintln hello worldquot System out println 5 Systemoutprintln x x I To not print on new newline use I SystemoutprintString CIS110 24 Introduction to Programming with Java for Beginners Another use of Reference type as return type Keyword this cls11o Keyword this I this is a reference to the current object I The object whose constructormethod is being called I The value of this is an object s heap address Can be passed as argument to a method Can be returned as value Can assign the value of this to another variable in an assignment statement Can do anything with this that you could do with any other variable except change its value Use of Reference Type as Return type public class not private 39 private int y public notltint newx int newY X x7 yYr Return a reference to l newly created public not displacedDotint dispmt ObjeCt int newx x dispmnt i Dot new Dotnewx newY etuzn d gt Dot d1 new Dot53 gt d1 getX getX not shown 5 gt Dot d2 d1 displacedDot5 cls11o gt d2getX 1o cls11o publ public Dotint x x Use 1 this With data fields ic class Dot private int x private int y Localvariablex amp y shadows the instance x int variablex amp y problem yYi public class Dot private int x private int y public Dotint x int y thisx fixed thisy Use 2 Return as value public class Dot rivate int x private int y public Dotint x int y thi x x this y y public Dot displacedDotint dispAmt x x dispAmt y y dispAmt return this cls11o Use 3 Passed as a parameter and comparison statement Facebook Example I FBPerson has a name and at most one friend I Rules for adding a friend FBPerson I When FBPerson Achooses FBPerson Bto String name be a friend the operation succeeds if FBPerson person AisriotB getNameo A has no friends getFriendO B has no friends setAFriendO hasAFriendO I Note that A has a friend who is B if and only if addAFriendO B has a friend who is in otherwords Men A adds B as a friend B must also add A as a friend cls11o 5 Facebook Example class FBPersonf public boolean addarziendmsrezson p ifp this hasnrziendo true II p nu11 n 1se ifphasAE iend tue etuz false thisseti ziend p 7lsel aunem FHPexsnn object s menu In FHPexsnn p pseti iendthis Int Fmexsnn 1quot menu In uns nhjecl return true cls11o Interactions for FBPerson gt FBPerson jo new FBPersonquotjo brownquot gt FBPerson flo new FBPersonquotflo smithquot new FBPersonquotmo jonesquot gt johasAFriend alse gt joaddAFriendflo V m 391 III 0 1 5 true gt joget riendgetName flo smith gt flogetFriendgetName jo brown gt joaddAFriend mo 1 already has a tuna sn mum add Inn as nma false gt moaddAFriendjo false gt mohasAFriend false cls11o 7 Introduction to Programming with Java for Beginners More on Strings Useful String methods I boolean equalsObject obj gt Compares this string to the specified object The result is true ifand only if the argument is not null and is a String object that represents the same sequence of characters as this object I boolean equalslgnoreCaseString other gt Tests ifthis string s characters are equal to the other string where case does not matter I int length gt Returns the length of this string note that this is a 65110 method not an instance variabe Escape Sequence I Strings can contain any character but some of them must be escaped in orderto write them in a literal I Each of these is written as a twocharacter sequence but represents a single character in the strin gt quot stands for the doublequote quot character gt n stands for the newline character gt stands for the backslash character gt t stands for the tab spacin gt 0 stands for null character indicating nothing Some terminal incorrectly display null as space character Eg SystemoutprintlnquotquotThis is in quotesquotquot quotThis is in quotesquot cls11o Still more about equals I Suppose you want to test whether a variable name has the value quotDavequot gt Here s the obvious way to do it if nameequalsquotDavequot gt But you could also do it this way if quotDavequotequalsname I It turns out that the second way is usually better I Why gt If name null then first way will cause NullPointerException gt But the second way will just return false CS110 Useful String methods II I char charAtint index gt Returns the character at the given index position Obased I boolean startsWithString prefix gt Tests if this String starts with the prefix String I boolean endsWithString suffix gt Tests if this String ends with the suffix String cls11o Useful String methods III I int indexOfchar ch gt Returns the position of the first occurrence of ch in this String or 1 if it does not occur I int indexOfchar ch int fromlndex gt Returns the position of the first occurrence of ch starting at not after the position fromlndex I With charAtindex index0fx just count characters starting from zero quotShe said quotHi quot quot Hg 012345678910111213 cls11o Useful String methods IV I String substringint beginlndex gt Returns a new string that is a substring ofthis string beginning with the characteratthe specified index and extending to the end of this string I String substringint beginlndex int endlndex gt Returns a new string that is a substring ofthis string beginning at the specified beginlndex and extending to the character at index endlndex 1 gt Thus the length of the substring is endlndex beginlndex CIS110 Substring Example I With substringfrom to it works betterto count positions between characters quotShe said quotHiquotquot 01234 567891011121314 I So for example substring4 8 is quotsaidquot and substring8 12 is quot quotHquot cls11o Useful String methods V I String toUpperCase gt Returns a new String similarto this String in which all letters are uppercase I String toLowerCase gt Returns a new String similarto this String in which all letters are lowercase I String trim gt Returns a new String similarto this String but with whitespace removed from both ends whitespace means any spaces or tab characters I See String class in Java API 50 for other methods CS110 Strings are immutable I A String once created cannot be changed I None of the preceding methods modify the String although several create a new String I Statements like this create new Strings myString myString anotherCharacter I Creating a few extra Strings in a program is no big deal I Creating a lot of Strings can be very costly cls11o 1o Introduction to Programming with Java for Beginners more on object creation this Recap HasA Relationship I Example Freshman and DormRoom gt DormRoom r new DormRoom206 Hi gt lreshman a new lreshman sam r OR gt Freshman a new Freshman Samquot new DormRoom 206 Hill gtagetRoomgetLocationO 206 Hill gt achangeRoomnew DormRoom 100 Hilton gt agetRoomOgetLocation 100 Hiltonquot EsE112 Object that creates another object Example 1 public class Point priva e in x private int y public Pointint X int Y X yY public Point displacedXint disAmt Ilreturn new Point with II x coordinate as x disAmt int newX x disAmt Point d new PointnewX y return d EsE112 gt Point d1 new Point5 6 gt d1 getX getX not shown 5 gt Point d2 d1 displacedX5 gt d2getX 10 gt d1 d2 false Object that creates another object Example 2 public class Circle private Point point Center private int radius public CirclePoint p int r Poin p radius r Interactions gt Point p1 new Polnt23 gt Circle c1 new Circlep1 5 gt cl gelRadiusO 5 gt cl gelPoinl getxo 2 l Complete constructor public Circleint x int y int r Complete Interactions gt Circle c2 new Circle4510 gt c2getRadius gt c2getPointgetX 4 Scope Issues with variables public class Point Local variablex amp Y Keyword this private int x shadows the instance I this is a reference a variable to the current private int y variabiex amp y object public Point int x int y I The obect whose method or constructor is bein x problem executed Y W public class Pointl i private int x I The value of this is an object s heap address private int y Can be passed as argument or input to a method Can be returned as value x Cannot be modi ed ie it is nal h1s I Uses ublic Pointint x i i 39 fi P Solution h S Avoid scope issue with instance variable amp local variable names To differentiate and compare Using this for differentiation this passed as a parameter and used in a comparison statement public double slope Point b gt Point a new Point2y1 Facebook Example d UbB diff SgetXO bQHXO gt Point b new Point4 5 I FBPerson has a name and at most one friend double difry I getYo bgetY0 l double 5 e diff if gt asopeb I Rules for adding a friend FBPerson return slope V 2 0 I When FBPerson A chooses FBPerson B to String name 39 be a friend the operation succeeds i FBPerson person gt bsopea isnotB getName 20 A has no friends getFriendO B has no friends setAFriendO hasAFriendO I Note the method is not fool proof I Note that A has a friend who is B if and only if addAFriendO B has a friend who is A in otherwords when A adds B as a friend B must a so add A as friend ESE112 6K Facebook Example class FBPerson lelalic boolean add riend sierson p i p this re 1 thishasnrriend II p nu11 urn fa se i phasnrriend return false this seti ziend p 7lsel cmum Fmexsnn nhjecl s illend m FHPexsnn p p5etF riendthis Ilset Watson Iquot rum to u s 11 return true Interactions for FBPerson gt FBPerson jo new FBPersonquotjo brownquot gt FBPerson flo new FBPersonquotflo smithquot gt FBPerson mo new FBPersonquotmo jonesquot gt johasAFriend false gt joaddAFriendflo true gt jogetE riend getName flo smithquot gt flogetE riend getName jo brownquot gt joaddAFriend mo 1m Emmy has a nun 50 cannot add Inn as rum false gt moaddAFriendjo false gt mohasAFriend se Introduction to Programming with Java for Beginners Recursion Tic Tac Toe Summing an Array public static int sumNumsint data in sum 039 for in iltdatalength i sum datai return sum public static int sumNumsRint data return sumNumsHeIperdata 0 0 private static int sumNumsHeIperint data int index int accum if index gt dataength return accu 39 my return sumNumsHeIperdata index 1 accum dataindex cls11o Alternative Soln Summing Array public static int sumNumsRintl data return sumNumsRHelperdata dataength 1 private static int sumNumsRHelperint array int index ifindex lt 0 return 0 else return 139 39 j 39 39r inde 1 CS110 Binary Search Int data 3 7 12 30 55 57 120 208 309 1024 public static int binarySearchint a int key int b t p alength while bot lt top int mid bot top bot2 if key lt amid top mid else if key gt amid mid 1 return mid return 1 cls11o Recursron Binary Search M Recursive binarySearch Assumes a is sorted If key is in a returns index oflocation else 1 public static int binarySearchRint 3 int key return binarySearchHelpera key 0 a length private static int binarySearchHelperint 3 int key int bot int top ifbot gt top return int mid bot top 2 ifkey lt amid return binarySearchHelpera key bot mid ifkey gt ami return binarySearchHelpera key mid 1 top return mid cls11o TicTacToe Winner Vertical public char winnerVertical forint col 0 col lt 3 co char winner board0col forint row 0 row lt 3 row ifboardrowcol winner winner quot ifwinner 39 return winner return 39 39 cls11o TicTacToe Winner Horizontal public char winnerHorizontal char lastSym ol charwinH 3939 forint r 0 r lt boardlength r lastSymbol boardr0 forint c o c lt board0 length c iflastSymbol boardrc break iflastSymbol 3939 ampamp c boardlength1 ampamp lastSymbol boardrc winH lastSymbol lastSymbol boardrc return winH cls11o Introduction to Programming WI39fz Java for Beginners Conditionalslf statements Sequential Programming I Recap A statement performs an action ie does something but does not have a value I Eg int num 5 I Computer executes statements in the order the statements are written I This is known as Sequential Programming I Example int num 2 int sqNum 0 sqNum num num Systemoutpn39ntlnsqNum cls11o Limitations of sequential programming I Cannot choose whether or not to perform a commandinstruction I Cannot perform the same command more than once I Such programs are extremely limited cls11o Control Structures I Allow a program to base its behavior on certain conditions I Two kinds I Conditional Statements I Loop Structures cls11o Recap Boolean I Boolean is one of the eight primitive types I Only 2 value true orfalse l Booleans are used to make yes or no decisions I All control structures use Booleans I The following expression each give a Boolean result 25 gt 24 ampamp 12 13 lresults to false 25 gt 24 12 13 lresults to true I Thus based on certain conditions we can alter the outcome or flow of the program cls11o Conditionals if statements An if statement is a flow control statement It is also called a conditional or a branch We ll see several flavors An if all by itself An if with an else part An if with an else if part cls11o if statement if condition statement 5 If the condition is true then the statements ie instructions Will be executed Otherwise itthey won t Assume X is an integer if X gt 10 X X 2 Systemoutprintln X X cls11o If statement contd I indicates the block of code that will get executed given the condition is true I You can avoid the curly brace after condition ifonly one statement is to be performed Assume X is an integer if X gt 0 SystemoutprintlnX is positive cls11o ifelsequot statement if condi tion statement 5 se statements Assume X is an integer if X gt 0 Systemoutprintlnx is positive else Systemoutprintln x is negative cls11o Style Rule Indentation and Spacing I Recommended indentation is from 2 to 4 spaces but must be consistentthroughout the program I In Dr Java you can set the indent level Edit gt Preferences gtMiscellaneous I Single space around every binary operator including comparisons and assignment ifxlt10 xx1 else xx1 cls11o Cascading ifelse Assume variable score is entered by user if score gt 90 Systemoutprintln Grade A else if score gt 80 Systemoutprintln Grade B else if score gt 55 System out println Grade C else Systemoutprintln F Note You can avoid the curly brace after condition if only one statement is to be performed cls110 Nested ifstatements An if within an if Truth Table if condition1 if condition2 What Values must the statement 5 A conditions have in order for block A to run B C else statements B A B C condition1 T else H statementss C cond39t39on2 cls11o The infamous dangling elsequot if x gt y When is statementB if y lt Z executed statementA In other words which if is the else paired statementB With An else is paired with the last if X gt Y elseless if regardless of spacing if Y lt 2 unless dictate otherwise StatelnentA else statementB CS110 12 Introduction to Programming WI39fz Java for Bed inners Frame Call by Value Stack Frame for method calls I Whenevera method is called some memory is set aside to contain information related to the call I Example parameter values current statement being executed etc I This is called the frame for the method call int add int number1 int number2 int sum number1 number2 return sum I The frame is discarded when the method returns I This implies parameters and local variables variables declared within method are discar ed I Hence this explains the reasoning for scope rules cls11o Call by Value Actual parameter v ues are copied into formally de ned parameters IWe call a method like this result add El 3 39 int add int int number2 int sum number1 number2 return sum cls11o Call by value contd int m 1 The value ofmie 1is int result I absoluteint W n n1 The value ofn is returned but the variable n is thrown away cls11o AAethodscalhngotherAAethods I boolean isLeapYearint year void eapYearsint start int end int X start SystemoutprintlnquotLeap years between quot start quot and end Whilex lt end ifisLea Year x Systemoutprintlnx x cls11o Stack I Suppose a call of method m1 is being executed so that a frame forthe call exists eg eapYears2000 2008 I Suppose the method m1 While executing calls another method m2 eg eapYears method calls isLeapYearx I Aframe for m2 is created amp now at this point two frames exist I If m2 caes another method m3 then a third frame is created I The frames are destroyed in the order in which they we create cls11o I Eg Call to m3 is rst completed and hence discarded then m2 and nally m1 I Follows rstinIastout principle and the section of memory that allocates memory during method calls is known as stack References Recap I The value of reference variable is I Either null or a heap address IntrOdUCtlon to Programmmg I null means currently not pointing at any location with Java for Beginners I Counter c new Counter I new CounterO allocates space for the actual Counter on the heap and initializes it I c actually allocates space to hold a reference to a Has aquot Relationship Counter c is placed on the stack and existent as long as NUH39 NullPomferExcephon gt Method does not return if declaredi met Call by reference n hod gt Dr J Interactions pane is not reset if declared in Interactions pane I The assignment makes c refer to the new Counter Has aquot Relationship or Composition DormRoom Code I An object of type A has an instan DonnRoom ce variable which is an object whose type is B A has a B gt DormRoom room new DormRoom208 will String building gt roomgetLocation I Eg A Freshman object whose room Is of reference type 208 Him DormRoom getLocationl DormRoom Freshman String name public class DormRoom gitnumerld DormRoom mom private int mm m3 1 9 private String bldgName A getName getLocaLlcnU getRoomU public D ormRoomint n String b num 11 bldgName b I The UML diagrams show instance variables and methods l of Freshman and DormRoom ob39ect39 I UMLUniversal Modeling Language industry standard used to describe classes In 00 public String getLocation return num b ldguame A DormRoom on the Heap DormRoom num 208 String mom bldgName STACK HEAP gt DormRoom room new DormRoom208 quotHillquot gt room getLecatienn quot208 Hillquot Freshman Code Imam gt DormRoom room new DormRoom208 Hill l gt Freshman f new Freshmanquotjoquot room String name DormRoom room gt fgetNameU quotjgquot gamma gt fgetRoomH getLocatien getRoomU quot208 Hillquot public class Freshman private String name private DormRoom room public Freshmanstring n DormRoom r name n room r public String getName return name public DormRoom getRoom return room Note on Operators I Dot operator and parentheses for method calls have same precedence I Associativity L to R I fgetRoomgetLocation is equivalent to fgetRoomgetLocation A Freshman on the Heap gt DormRoom room new DormRoom208 quotHillquot gt Freshman f new Freshnanquotjoquot room gt fgetNameU quot30quot gt f getRoom getLocation quot208 Hillquot Freshman name DormRuom Do rmRo cm 5 numzoa String String room bldgName STACK HEAP More Interactions gt DormRoom rr gt Freshman f new Freshman Tom rr gt fgetRoom getLocation Error Why I If you try to access a datafieldmethod of reference variable Whose value is null then you get a nullPointerException I ie you try to access some object that has not been created I Eg Person p pgetName Gives a runtime error I Runtime error because pgetName is valid syntax ie it compiles but does not execute Null in general I null is a legal value for any kind of reference variable I Example Person p Counter c Player mario p c and mario are null I null can be assigned tested and printed I Example ifmario null More Interactions II gt DormRoom room new DormRoom208 quotHillquot gt Freshman f new Freshmanquotjoquot room gt DormRoom r new DormRooml76 quotMcNairquot gt fchangeRoomr gt f address quot13976 McNair gt fhasARoom true Reference Variables as parameters DormRoom myRoom new DormRooml Hillquot f changeRoommyRoom void changeRoomDormRoom r room r l I When parameters of reference type are inputs the entire object is not copied Only the reference is copied This means that myRoom and r refer to the same object I Changes made to the object referenced byr remain changed when the method returns I This is known as call by reference Algorithm Introduction to Programming 39 93 A reCIpe a finite sequence of steps to complete Huh Java for Beginners a w I Examples searching sorting shortest path Algorithms Sorting I Running time S h Best case worst case average case running earc times for large n BUZZ Words Sorting an Array of Integers Preconditions Thingsthat should be true before Executing an algorithm 1o3o5261218 Postconditions Thingsthatshqud betrue afterexecuting an aIgunthm Looplnvariant I Preconditions an unsorted or sorted array Atruestatementtha IF Ilt7Pni seme I Algorithms selection bubble Running me oranAlgomhm MID I Loop Invariant Depends on the algorithm R r I F I cig gii zmi e e mSENEQSZQTESIQ feru iaiagginimmemnmmeenseuaee I Postcondition the array Is sorted Divide and ConquerAlgorithm ewe a problem by dividing Inn to pieces Key When searemng It s the thing We re looking for 2561o12183o Bubble Sort Compare each element except the last one with its neighbor to the right I lfthey are out of order swap them I This puts thelargest element at the ver end I The last element is now in the correct and nal place Compare each element except the last two with its neighbor to the right I lfthey are out of order swap them I This puts the second largest element next to last I The last two elements are now in their correct and nal places Compare each element except the last three mu its neighbor to the right I a ll you have 39 the le This causes ar er values to quotbubblequot to the end of the list while smaller values 39sinkquot towards the beginning of the list Bubble Sort 10 30 5 2 6 12 18 I Preconditions array may or may not be sorted I Algorithm start 0 end array length 1 Loop Compare successive pairs of items and put the larger on the rightquot This will bubble the largest one all the way to the right start start If start end we re done The array is sorted Loop Invariant At step i the i largest items have been placed Postcondition Array is sorted What is the bestworst running time given n items Best and worst time n1 n2 1 n1n2 which is approximately nquot2 If the array is already sorted AND the bubblesort is optimized to quit if no switches are done then the best time is n publi for Bubble Sort Code a static void bubblesortint a int i0 i lt a1engt 1 i if a pass is made with no swaps we39re done boo1ean swappedElements false for int jo jlt a1ength co if aljl gt alj 1 int tmp alj alj1 alj1 aj1 tmp swappedElements true if swappedElements break Selection Sort 1o3o5261218 1 i j mpare neighbors if the earlier one is bigger swap Running time average best amp worst I n Preconditions an unsorted or sorted array Algorithm start 0 end array length 1 L00 39 p If start end we re done Find smallest item in series arraystart to arrayend Switch arraystart with the smallest item start start 1 Loop Invariant A er step i the rst i items in the array contain the smallest i items in sorted order Postcondition Array is sorted comparisons and then swapping it into the rst position 5 A L I I n1 elements and so on n n1 n2 n 1 n2 which is approximately nquot2 Other Sorting Algorithms I The best possible worstcase running time for sorting n log n I Selection sort and bubble sort have worst case running times of nquot2 I Other algorithms have better performance I Insertion sort best time On avgworst time Onquot2 I Merge sort n log n I Quick sort n log n expected running time nquot2 in worst case Search s Humble Roots I Before attempting to write sophisticated search algorithms it s a good idea to start simple I We will show how to search for an integer in an array of integers I Algorithms I Linear Search I Binary Search Search is a Big Deal I Google I The Mac OS with spotlight I Patternrecognition algorithms used in I Image Processing eg face recognition I Natural Language Processing I Bioinformatics I and many more applications Linear Search 21863012510 I Preconditions an unsorted array and a key Algorithm Considerthe first item in the array to be the next item Loop lfthere is no next item were done return failure Otherwise compare it to the key lfthey re the same we re done return index Otherwise considerthe next item in the array Loop Invariant At step i we ve searched the rst i items I Postcondition If the key is in the array the index of the rst occurrence is identi ed otherwise we establish that the key is not in the array What is the best case running time given n items The worst case step n steps ll 2 Binary Search a divide amp conquer algorithm 5 6 10 12 Preconditions a sorted array and a key 18l30 Algorithm Compare the key wun the arrays middle item Loop If theYre the same we re done return the index If the key is smaller consider the le subarray If the key is larger consider the right subarray If the subarray size is 0 we re done return failure the subarray s middle item Otherwise compare key oop Invariant A er step i the size of the dataset yet to be searched is array length quoti Postcondition the index of an occurrence of the key is returned or n error message is transmitted if the key is not found 1 step log n steps n Best case running time Worst case Introduction to Programming with Ja Va for Beginners Inheritance Note What is Jar I lenamejar I Stands Java archive I Contains collection of precompiled java les class les and any media files images sound involved in the program cls11o Example Bot and BetterBot public class Bot private int y public int getxo public int getY public void eatDot public void move public void turnLeft public class BetterBot extends Bot public void turnRight turnLeft turnLeft turnLeft cls11o Inheritance One of the key concepts of OOP I A hierarchical relationship among classes I Establishes a superclasssubclass relationship I Establishes is aquot relationships gt eg a BetterBot is aquot Bot Benefits I Reusability of code gt Put code in one class use it in all the subclasses gt Revisions only needs to be done in 1 place I Polymorphic code works on manyforms gt Write general purpose code designed for a supertype that works for all subtypes cls11o The extends keyword Inheritance is established via the extends keyword publ39c class Bot public class BetterBot extends Bot Now we say I BetterBot inherits from Bot gt However based on the visibility modi ers certain instance variables and methods de ned in Bot may not be access ble I A BetterBot is a Bot I BetterBot is a subclasssubtype of Bot I Bot is the supercasssupertype of BetterBot cls11o What can you inherit I Visibility modifiers determine which class members are accessible and which do not I Members variables and methods declared with public visibility are accessible and those with private visibility are not I Problem How to make class instance variables visible only to its subclasses I Solution Java provides a third visibility modifier that helps in inheritance situations protecte cls11o Constructors and Inheritance BetterBot b new BetterBot I When an object is created its constructor is called I But rst a constructor from its highest ancestor Object is called then the next highest Bot then its own BetterBot I The default behavior is such that the default noargument constructor is executed I A constructor can explicitly ca its parents its superclass constructor by making a call to super public class BetterBot extends Bot public BetterBot BotWorld world su erw rl cls11o Another Example with super public class Dog private String name private int age DogString name int age this n n e thisage age class BetterDog extends Dog blic BetterDogString name int age super nameage cls11o Except for o CIS11D Inheritance Tree bject whlch has no parent ava has singe Inheritance each node has one parent The Object Class All classes lnherlt from the Object class The Object class ls the root oflhe class hlerarchy When we create a new class extends Objectquot ls lmpllednmpllclt publlc clsss Cat l publlc clsss Cat extends abjectl l The Object class has several methods whlch all object inherit most notably tost rlng and equals CIS11D B mlles l publlc stung to return mode CIS11D lt ls Most common usage publlc Cal Stt1ng model i tnlsmodel mode The toStringO Method y default lt returns a strlng contalnlng an object39s heap address By overrlden to describe the object39s state debugging les stung model 7 Recall toStrlngO 1 from RealVector Sslgnment stungo 1 ll e model e mlles ll e mlles The toStringO Method contd I When you try to print a reference variable39s value the toStringO method is called I This happens behind scenes Eg Dog d new D090 In Dr Java d Dog a0 ls equlvalent to gt d t strlngo Using yste m out prlntlnd ls eqlllvalent to System out prlntlnd toStrlngO CIS11D Need for equals Comparison of Strings I Ifthe operator is used for Strings I Java compares the addresses where the String objects are stored not the letters in the String I For example gt String a quothiquot gt String b hiquot gt a gt false I Use the String class39 equals method to compare two Strings for equality gt aequasb gt true gt bequalslgnoreCase Hl gt true cls11o The equals Method I By default compares heap addresses I By convention it is overriden to match the developer s notion of equality public class Person private int social social security it private String name public int getSocial return social public boolean equals Person p return thissocial pgetSocial cls11o Type Rules I A reference variable of type t may hold a value of its own type or any subtype but not of a supertype I Given the following variable declaration Bot b Which of the following assignments are valid compile b new BetterBot b new Object How about these BetterBot bb bb new Bot bb new String bb new BetterBot b new Object D II cls11o The Instanceof Operator gt Bot b new Bot gt b instanceof Bot true gt b instanceof Object true gt b instanceof BetterBot false gt BetterBot bb new BetterBOtO gt bb instanceof BetterBot rue gt bb instanceof Object gt bb instanceof Bot e tru gt Bot bbb new BetterBot Ila variable can store a subtype gt bbb instanceof BetterBot true gt bbb instanceof Bot true cls11o Inheritance Example public class Vehicle public class Car extends Vehicle protected int new instance variable not registrationNumber inherited private int numberOfDoors public int getRegNumber Interactions I gt Car c new Car2 gt cgetDoors 2 gt cgetRegNumber Inherited Method 0 gt csetRegNumber45 Inherited Method gt cgetRegNumber 45 cls11o 17 return registrationNumber public Carint doors numberOfDoors doors I public void setRegNumberint num public int getDoors FEQISIFBNOHNumber quotum return numberOfDoors I I CS110 16 Interactions II public class TwoWheeler gt TwoWheeler t new extends Vehicle TwoWheelerO public void setRegNumberint gt tgetRegNumber num nherited Method registrationNumber 5000 0 num gt tsetRegNumber45 nherited Method amp Overriden gt tgetRegNumber 5045 cns11o 13 Interactions III gt Vehicle v new Car4 valid why gt vsetRegNumber3 gt vgetRegNumber 3 vgetDoorsO Compile Error No getDoorsO in Vehicle I Since reference type is of Vehicle and not Car this makes sense I In other words v could potentially refer to other types of vehicles that are not cars I The solution here is to use down typecasting conversion cns11o 19 Down Casting I If for some reason you happen to know that v does in fact refer to a Car you can use the type cast I Use instanceof keyword to find that out I Do Carv to tell the computer to treat v as if it were actually of type Car 80 you could do I CarvgetDoors This perfectly compiles amp executes cls11o 20 Cast Exception Error I Suppose you did not check ifv is an instance of class Car I ie Vehicle v new TwoWheelerO I CarvgetDoors is perfectly legal statement I You will get a runtime or semantic error I Known as Class Cast Exception gt Saying TwoWheeler type cannot be cast to Car type cls11o 21 Introduction to Programming with Java for Beginners ArrayList Collections I Data Groups of entities of similar kind I CD collection I Items in store I Characters in a video game I Methods Do the same thing to all of them I Computing the total number of tracks I Adding sales tax to all the prices I Moving all of them one step forward CIS110 Array Recap I Kind of a collection Person people People people new Person3 people0new Person jo people1new Person floquot CIS110 3 Problems with Arrays I Fixed size I Optimal size may depend on information unavailable at creation time I Not good with dynamic growth I Cannot add and remove elements without the pain of resizing I A collection that can dynamically resize is known as a list CIS110 Lists I Basic requirements I Add an element I Get an element I Remove an element I Search for an element I Learn the size of the list I Perform an operation on all elements We will look at I How to create a typespecific List for PointsStrings I A much more convenient List the one provided in the API that works on any type CIS110 5 Visualizing a list I A sequence of references to objects of a given type I Indexed by 0 1 2 I A list Of Points CIS110 A TypeSpecific List for Points public boolean addPoint p Add p to the list Returns false if duplicates are not permitted and already contains the specified element public boolean removePoint p Remove the first occurrence of p Returns true if this collection contained the specified element public boolean containsPoint p Test whether the list contains p public int size Number ofelements in list public Point getint i Get the ith element of the list starts from 0 0 lt i ampamp i lt size public void setint i Point p Setthe ith element t0p 0 lt i ampamp i lt size CIS110 Using a typespecific List gt PointList points new PointList gt pointsaddnew Pointl020 gt pointsaddnew Point3040 gt pointsaddnew Point5060 gt pointssize 3 gt pointsget2getX 50 CIS110 Now a list of Strings public boolean addString 5 Add 5 to the list public boolean removeString 5 Remove the rst occurrence of 5 public boolean contains String 5 Test whether the list contains 5 public int size Number of elements in list public String getint i Get the ith element ofthe list starts from 0 0 lt 1 RE i lt size public void setint i String 5 Set the ith element to s 0 lt 1 RE i lt size cls11o s Problems Code Duplication Lack of abstraction l Much of the functionality of a list doesn t depend on the element type Eg2 size add remove swap etc public void swapPointList list int i int j Point p listgeti listseti listgetj listsetj p public void swapStringList list int i int j s listgeti listseti listgetj listsetj s cls11o 1o The javautiList interface 39 The Java APl s List interface works with any Object public interface List publ39 int size public boolean isEmptyO public boolean addObject element public void addint i Object element public Object get int i public Object remove int i public boolean containsObject e public Object set int i Object element F O l 051 Cannot do List myList new List 11 ArrayList 39 ArrayList is a concrete classes 39 Implements the List interface 39 Does dynamic resizing for you 39 Good for random access 39 Typical Usage 39 Use List for variables and parameters 39 Use ArrayList when instantiating the list List chracks new ArrayListO cls11o 12 Typical Usage of List interface I Example ArrayList with Strings gt import java util List words new ArrayList words add quotcatquot words add quotratquot words get 1 ratquot VVVV n 39One approach for processing all items in a List for int i 0i lt wordssize i System out println words get i cs11o Some more problems I Use ofthe type Object as the basic type for objects that are stored in a list leads I Need to use typecasting in almo tev ry case when an element is retrieved from that list I Since any type of object can legally be added to the list there is no way forthe compiler to detect an attempt to add the wrong type of object to the list The error will be detected only at run time ie when the object is retrieved from the list and the attempt to typecast the object fails cs11o Solution Parameterized Types I An array of type BaseTypel can only hold objects of type BaseType I An attempt to store an object ofthe wrong type in the array will be detected by the compiler I There is no need to typecast items that are retrieved from the array backto type BaseType ListltBaseTypegt I Where BaseType is any object type that is the name ofa class or of an inter ce I Instead of using the plain quotListquot type it is possible to use I BaseType cannot be one ofthe primitive types I Used to create lists that can hold only objects oftype BaseTyp mple ListltPointgt p1 new ArrayListltPointgt0 ArrayListltPointgt p2 new ArrayListltPointgt0 cs11o More on ArrayList Class Methods I Javadocs for ArrayList show input or return type as E I E is nothing but what you declared you ltBase Typegt to be I Example boolean addE o I Adds element of type E to end of the list I If E is not the type specified when you created your ArrayList ie you try to add String instead of a Point then compiler will complain This is why parameterized types were invented cs11o Sample Interactions I Create an list to hold Points I ListltPointgt ist1 new ArrayListltPointgt I Add a Point to list I ist1addnew Point45 I To learn the size ofthe list I ist1size I Remove a Point at speci ed location I ist1remove0 I To append one list to another ist1addAlist2 cs11o 17 Introduction to Programming with Ja Va for Beginners Recursion Meaning of Recursive I Recursive means self referencing IWhen a class has an instance variable Whose type is itself we say it is recursively defined It s an example of structural recursion I Notice that the class has subparts that look like the Whole cls11o Recursive Methods I A recursive method is one that calls itself parameters if condi tion return value else return cls11o Why Use Recursive Methods Many things we model have recursive structures where the subparts look like the whole Ma hematical formulas Power X y k X yr Factorial n n n new l Fioonacci series rion tlbrlrl tibl l72 Fractal geometry Julia Mandelbrot sets I Languages Programming languages Ari Expresslun Earl Eurltal EXprESSlDrlS A statement Earl Eurltalrl other statements HTML tags in aweo pa e nsiole markup language ror storing semlrstructured data I Hierarchical Entities olten stored as trees A r ancestral tree Ari operating system s roloeroirectory hierarchy I Graphs Social networks Faceoook om puter networks 39 Alrllrle travel networks Recursive methods are frequently used to process such structures cls11o Write a Recursive Method Example print down to 1 Considerthis method public static void countDownint num if num lt 0 Recursive method that prints num hum 1 hum 2 1 reFurn Assunes num is positive for int i num 1 gt 1 i System out println num public static void printDownTolint num if num 0 base case return Rewrite it as a recursive method Systemoutprintlnquotnum is quot num Instead of having a loop have it call itself printDownTol num 1 How do you get it to stop when it should l Can we generalize the steps we took as a way to approach the coding of recursive methods CS110 cls11o Recursion Recipe Example sum numbers 1 Handle the base case which is when a recursive call should not be made because the process should stop A recursive method that returns the sum of the numbers from start to end For other cases make a recursive call the recursive leap of faith which must make progress towards a goal towards the base case public static int sumint start int end if start gt end base case return 0 If the base case is nothanded or the recursive call does return Start sumStart 139 end r39 not progress towards the base case then the method is l likely to call itself infinitey it will diverge and you ll get a stack overrun error cls11o cls11o intx sum l3 6 Recursive call sequence Eg sumstart end um l3 sum3 3 return 6 Stan E end 1 accumulate accumulate sum2 3 sum4 3 y return 5 return 0 return 3 accumulate Base case start gt end CIS1 10 Binary Search a divide amp conquer algorithm 25610121830 I Preconditions a sorted array and a key I Algorithm Compare the key with the array s middle item Loop lfthey re the same we re done return the index lfthe key is smaller consider the left subarray lfthe key is larger considerthe right subarray lfthe subarray size is 0 we re done return failure Otherwise compare key with the subarray s middle item CISHO Example Sum using Accumulator Some recursive methods use an additional helper methodquot with an quotaccumulatorquot Here a total is accumulated Other things may be accumulated such as a list ofthings sums numbers recursively with a helper method public static int sumUpint start int end return sumUpHelper 0 start end private static int sumUpHelper int totalint startint end if start gt end return total return sumUpHelper total start start 1 end CISHO Binary Search Code kk binary search which returns an index in a which holds key or f key not found Precondition a is non empty and sorted public static int binaryint a int key int bot 0 top alength while bot lt top int mid bot top 2 if key lt amid t p mid else if key gt amid bot mi 1 else return mid return 1 CISHO Introduction to Programming wit7 Java for Beginners Intro to Arrays of Primitives 1 Dimensional Array What if we need 10 different ints for storage int numl int an12 int num3 int num4 int num5 int num6 int num7 int num8 int num9 int numlO cs11o What if we want to store lots of things I But we don t want to declare a separate variable for each one I That s what arrays are good for cs11o What is an Array I It s an easy way to declare lots of variables that all have the same type type 1 variableName new type 1 Eg declare an array of integers int data new int5 tota1 ints 5 I When an array of particular primitive type is created Java initializes the elements to the types default value Eg Array of ints default value is cs11o Array Elements and Indices An Array is an Object int data data is a reference variable whose type is int meaning I data0 6 array of ints At this point its nun I To initialize integer array I data2 12 data new int 5 The new operator causes a chunk of memory big enough for 5 ints to be allocated on the I The number within square brackets is called an heap Here data is a assigneda in deX reference to the heap address data0 6 Initially all ve ints are 0 Here I The valid Indces are 0 thru array length 1 damn 10 three of them are assigned other I 0 first element of the array data 2 12 values I n l last element of the array int info 6 10 12 o 0 int info new int6 10 12 0 1 CISHO Array of Primitives Using Array Elements in Expressions An element of an array of ints can be used virtually int data data anywhere an expression of type int is valid 39 Likewise for arrays of othertypes d t tlal int data new int 6 10 12 0 O a a new 1n int x dame data3 data2 data4 data3 data2 2 Systemoutprintln dala0 is data0 data4 Malhpow2 data4 data0 5 d i damn 10 CISHO 6 CISHO Accessing an Array39s Leng rh ArrayNamelength gives size of the array int data data new int5 datalength is 5 data0 6 data1 10 data2 12 ch to sum the contents of an array int result 0 for int i i lt datalength i result result datai cs11o a Comple re The sum me rhod public class ArrayTooli a it ke an array of ints as an argument it returns the sum of all the integers in the array public static int sum int 1 data t for int i o i lt datalength i result result datatil Welcome to DrJava gt int data new int 5 10 12 0 0 gt ArrayToolsumdata 23 cs11o 5 Array OUT of Bounds Exceptions public class ArrayTool public static int sumint data int sum r for int i 0 i lt datalength i sum sum datai return sum gt int data new int 6 10 12 0 0 gt ArrayTnnlsumdata ArrayIndexOutOanundsExceptinn cs11o 1 Declaring amp Ini l39ializing Arrays of primi ve Type int info1 2000 100 40 60 int infoz new int 2000 100 40 60 ChaFI choices1 p s q CharH choicesz new char 39p s q doube temps1 756 994 867 doube tempsz new doube 756 994 867 Note The advantage of using the new type syntax is that it can be used in an assignment statement that is not a variable declaration statement cs11o 11 Complete this method public class ArrayTool Returns true if all integers in the data array are positive false otherwise public static boolean a11Positiveint data cisiio Finding Max I Suppose you want to find the largest value in an array called scores int largestScore 0 for inti 0 i lt scoreslength i if scoresi gt largestScore largestScore scoresi I What is wrong with this approach cisiio Finding Max I Complete max method that finds the maximum value in the arra I Assume that input passed is valid no need for error checking Dr Java Interactions Pane gt intl data new intl 6 10 12 0 0 gt ArrayToolmaxdata 2 cisiio Improved Solution I To nd the largest value in an array scores of possibly negative integers int largestScore scores0 for inti 1 i lt scoreslength i if scoresi gt largestScore largestScore scoresi cisiio Finding Location of Max Value I Suppose you want to nd the location in which you nd the largest value in an array scores int largestScore scores0 int index 0 for inti 1 i lt scoreslength i if scoresi gt largestScore largestScore scoresi index i cisiio 1s Introduction to Programming with Java for Beginners Polymorphism Overloading Overriding More overriding inheritance Polymorphism I Polymorphism means many poly shapes morph I In Java polymorphism refers to the fact that you can have multiple methods With the same name In the same class I There are two kinds of polymorphism I Overloading gt Two or more methods with different signatures I Overriding gt A method in a subclass to override a method in the superclass that has the same signature IWe ve already seen Overloading scenario with Constructors Eg public RealVectordouble X double y public RealVectordouble mag Angle theta cls11o Method Overloading Method overloading occurs when I A class has two or more methods with the same name but different signatures gt Different signature gt the number order or types of their parameters differ the foo method is overloaded public void foo public void fooint x public void fooint x double y I When the foo method is called Java picks the one that matches Eg foo 10 3505 cls11o Overriding I Overriding occurs if I There are two or more methods with the same name and the same signature in an inheritance chain I For example the Object class has a toStringO method gt It can be overriden in a subclass simply by creating a method with the same signature public String toString I Java picks the lowest method in the inheritance chain possible cls11o Some Methods cannot be overwritten Overriding Variables class Animal I You can but you shouldn39t final boolean canMoveint direction I Possible for child class to declare variable with same name as variable inherited from parent class Rabbit extends Animal class I One in child class is called shadow variable inherits but cannot override canMoveint gt It shadows the variable with same name in the parent class I Confuses everyone J tl39k 39bl b f39 l thd I at geef grlla es can e ma me o s can I Child class already can gain access to inherited variable with same name 39 MethOds that are nal cannOt be overr39dden m I There39s no good reason to declare new variable with the subclass the same name CS110 4 CS110 Example Some Variables Cannot be Shadowed class Animal public class Dog extends Animal I class BorderLayout Protected String type String type public static final String NORTH quotNorthquot public Dog public Animal type quotDogquot type quotAnimalquot I If you were to create a subclass of gt Dog d new D090 BorderLayout you would not be able to gt dtype can field as not set private rede ne NORTH Dog cls11o 6 cls11o References Recap Poin l39 Class Example public class Point Consider Introduction to Programming private int x Point p1 new Point56 private int y I Point p2 new Point56 WI39fz Java for Beginners I Point p3 p2 public Pointint x int y S39X X What is value of the following expressions thIsy y I p1 p2 Solution to class ExerCIse publicimgem 39 3931 j 3933 return x I p2 p3 I p1getX p2getX public int getY return y cls11o Solution 1 Point Class Example contd I p1 p2 public PointPoint p gt Point p1 new Point56 I false Reference p1 and p2 are pointingrefering to gt Point 2 new Point 1 two different objects ie heap address is different complete gt p1geamp0 p I p p3 5 I false p3 is pointing to object that p2 is also pointing gt 2 etxo to Hence p1 and p3 are pointing to different objects 5 p 39g I p2 p3 public void moveint d I true p2 and p3 are pointing to the same object and X X d gtp239move4 hence are pointing to same object ie heap address gtP1QetX0 is the same Y Y d 5 I p1 getX p2getX gtp2getX I true Because here we making a value comparison 9 p1 s X value is 5 and so is p2 s X value CIS110 2 CS110 3 Solution 2 public PointPoint p Complete x px y Py or x pgetX y pgetY cls11o I Based on the interactions we initialize the newly created object s x and y to be the x and y values of the object that p is referringpointing to Has A Relationship Recap Circle Class Example public class Circle private Point p Center private int radius thisp p radius r public CirclePoint p int r Interactions Point p1 new Point23 Circle c1 new Circlep1 5 cls11o I Complete constructor public Circleintgtlt inty int r Complete Interactions Circle c2 new Circle4510 Solution 3 public Circleint gtlt int y int r Complete p new Pointxy radius r cls11o I Circle has a Pointto indicate center and a radius I But since the constructor gets 00 ordinates and not Point we need to make a point first with the given coordinates
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'