Popular in Course
verified elite notetaker
Popular in Electrical Engineering
This 91 page Class Notes was uploaded by Dorris Borer on Monday September 28, 2015. The Class Notes belongs to ESE112 at University of Pennsylvania taught by Staff in Fall. Since its upload, it has received 4 views. For similar materials see /class/215450/ese112-university-of-pennsylvania in Electrical Engineering at University of Pennsylvania.
Reviews for INTROTOESE
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 Conditionalslf statements 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 EsE112 Control Structures I Allow a program to base its behavior on certain conditions I Two kinds I Conditional If Statements I Loop Structures EsE112 Recap Boolean I Boolean is one of the eight primitive types I Only 2 value true orfalse I 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 resuts to false 25 gt 24 12 13 resuts to true I Thus based on certain conditions we can alter the outcome or flow of the program EsE112 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 EsE112 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 EsE112 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 ifX gt 0 SystemoutprintlnX is positive EsE112 ifelsequot statement if condi tion sta tement s else condition statements Assume X is an integer ifX gt O SystemoutprintlnX is positive else Systemoutprintln X is negative EsE112 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 if xlt 10 xx 1 else xx 1 w v EsE112 Cascading ifelse Assume variable score is entered by user if score gt 90 System out println Grade A else if score gt 80 System out println 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 EsE112 Nested ifstatements An if within an if Truth Table if condition1 if condition2 statements A What Values must the conditions have in order for block A to run B C else statement 5 B A B C condition1 T else H statements 5 C Condltl n2 EsE112 The infamous dangling elsequot if x gt y if y lt z statementA else statementB I An else is paired with the last elseless if regardless of spacing unless dictate otherwise EsE112 When is statementB executed In other words which if is the else paired with if X gt y if y lt 2H statementA else statementB Lecture Two Part Mass Spring Damper System An intuitive look Joel Weingarten Sept 2007 ESEI I2 Mass Spring Damper m J 4 We Created by Wikipedia user 1le 0 Mass m Attached to hook s law spring 0 Recall Fs kx 0 Damping Fd c dxdt Exercise 0 What happens with no damping when the spring is pulled 0 Can you describe the motion as a function of time 0 How do the mass and spring constant values effect the motion Let s Take a Look 0 httpwwwoncapaorgmmpkap 3 cd36 ahtm Exercise 0 What happens if there is clamping 0 What is the behavior of the system 0 What is the relationship between the amount of damping and the behavior 0 Can you describe the motion as a function of time Let s Take a look 0 httpIinltsmathrpieduappetsappindex springmasshtml Homework 0 Find three real world applications for MSDs 0 How are K the spring constant and C the damping coeffecient chosen to produce a desired Behavior ESE112 Computing Compufing Examples User information Assurance Perform mice siiii uluti on IherSnurceshll iicnwamc announce izn ESE112 9 9 What does The computer does best I Perform operations Add sub multiply copy from data from location to another I Store information Depending on memory capacity I Interact with outside world InputOutput I Fast E g 2 GHZ processor can roughly cany out 2 billion Instruction d In 1 Secon ESE112 Compu l39ing in general I Automate a known solution I Howwe can best do it I Investigate things we don t know I Its theoretical foundation lies in I Mathematics discrete math I Electrical Engineering ESE112 Digiml System Digital vs Analog I Computer is a digital system I Digital 8 stem I Uses discrete discontinuous values I By contrast nondigital or analog systems use a continuous range of values to represent information gt Eg Temperature at a given location with respect to time I A discrete value is a sampled version of an continuous value I Data is noted at fixed intervals Source mm NEHWlKlpEdla DrgWlKlFHE Digital signal svg I Eg every microsecond rather than continuously ESE112 4 ESE112 Whm does The Compufer Understand Wha l39 does the Computer process amp store I At the lowest level a computer has electronic I An electronic device can represent uniquely only one of plumbing two thin s I Operates by controlling the ow of electrons through very fast I EaCh 0 and EaCh 1 395 rafermd to as 3 3mm 0399quot or Bquot tiny electronic devices called transistors I Fundament unit of information storage I To represent more things we need more bits I The deVIces react to presence or absence of voltage I Eg 2 bits can represent four unique things 00 01 10 11 I Could react actual voltages but designing electronics then I k bits can distinguish 2K distinct items becomes complex I Combination binary bits together can re resent some I Symb0lcally we represent information or data Eg 01000001 can be 1 Presence of voltage as 1quot 1 Decimal value 65 2 Absence of voltage as 0quot 2 Alphabet or character A in ASCII notation 3 Command to be performed eg Performing Add operation ESE112 s ESE112 Mach Erie Language Computers ur39nderstar39nd or39nly O s ahd 1 s Allta Machine hardware Language Each machine has it unique language gt Eg combination of 00101001 is not same meaning on different machine gt Difficult for humans to program the computer in machine language ESE112 Programming 0 Machine Language Write ir39n Iahguage almost r r ly like Ehglish Ahother special software compiler trahslates the programmihg lahguage ihto a Speci c machine lahguage Specific Machine gtElectror lic Hardware Operating System wwwhackerstickerscom Ohce trahslated Programmihg gt Machihe I he same program cannot run on different machine Java avoids the above problem Code is portable Write one run anywhere One of the features for popularity of Java Caveat The code we write for Boa Bots is not pot table ESE112 Pr39og r39crhm Eng Languages Computer Programming ls telling the computer how to do something WiKipedia Definition Applies specific programmlng languages to solve specific computational problems with solutions Programming Languages Unlike human languages gt Designed for instructing computers to solve problems Like hurt tar languages e I hey have a grammar gtWe will be learning grammar for Java Programming gtCaveat Stripped down version of the regular Java ESE112 Pr og r39omm i rig Language Synfox Syhtax is the grammar of the lahguage Analogous to rules in English Language gt Missing a period after sentence gt Rules using verbs nouns etc Compiler special software Will point out every syntax error Error messages may be helpful gt Often they are not gt V gain experience V error messages after a While Helps to have good editor that provides highlights for language feature ESE112 11 Program 5 WW II IAnnnensetnnnsnncnnns If E n pannunannangnage n I Minn n Wquot IThennststepinnn t ngannpnngnan is n ananzetnennnnnbtn be done nnnngnnnna I Angnntnn IStepnnsnppnncednnetnatnsguannteedn Innnnatnsncntnateacnsnpnspnnsennatedand cannecanndnnt ESEW In ESEW In Programming Language Senannics I nnn the nnpntn canesnnt nunnnsnnnnns I Running nEnenning a pngnan I Semanticsntne meaning nnn program IWeneantne senanncsanennnnunnexennetne pmgnan I Bantaunwe ubsenetneunput I Anentneexenuting pnngnan tnn senantinsnf n prognannannnannncnnn I Senannnnn nun nonnannnenstn bennng I Yunnannnannut gen enunnessages nEnEnnMssageDnn nng annnnenhnzen I Won pmgnan is n01 dung nn you wan n10 du tnuugn n nuns tneenunnssenann ESEW In I Penpne nne differenttastes n programming but nannnanesanenendncommon IPnnvnannnnsananasnenasanan I Oran InannonnepnsfnndanentnnaHpnngnannng angna ES ILnanannntonjenOrientedPngnannng nndnusngnna ILeannananetnnfdatastructuresandangnntnns nan ESEW In Programming Recurring Themes I Modularity l Break big problem into sub problems and compose I Algorithm Thinking I Awell defined procedure I Abstraction I Look for and encode common features EsE112 16 Introduction to Programming WI39fz Java for Beginners Loops while amp for A Loop I A simple but powerful mechanism for making lots of things happenquot I Performs a statement or block over amp over I Usually set up to repeat an action until some condition is satisfied I Computing Scenarios Examples I Run an application until user hits quit button I Deal card hands until game over EsE112 Syntax of the whie statement While condition statement 5 l I condition is a truefalse boolean expression I If condition is initially false the statement is never executed I If condition is true statement is executed and condition is reevaluated I The statement should eventually make the loop stop EsE112 A wh39e Loop to Print Numbers Print the numbers 1 thru 10 int x 1 while x lt 10 Systemoutprintlnx x x 1 l I What happens if you forget the statement x x 1 I We print value 1 forever I Known as in nite loop EsE112 More Infhire Loops Compute Square of first 10 numbers Some infinte loops are intentional while true In Squarejava statement 5 int num 1 int sqNum 0 while num lt 10 Others are not sqNum num num int x 5 Systemoutprintlnnum quot quot sqNum While x lt 10 num num 1 statement 5 which don t change x ESE112 4 ESE112 For Loop While vs For for init endtest reinit Explanatlon t t t int X 1 An example of S a amen while x lt 10 a while loop Systemoutprintlnx that has this patte n x x 1 I Executes loop body statements within as long as endtest evaluates to TRUE I Initialization and reinitialization code included in loop statement for intx 1 xlt 10 xx 1 Afar loop 1 Systemoutprintlnx at 51055 the th39 I Note Test Is evaluated before executing loop same 1 19 body Note For loops are used generally for bounded iteration ESE112 6 EsE112 Summary of Loops while while condition statement5 for for exprl condition expr3 statement 5 EsE112 Introduction to Programming with Java for Beginners Primitive vs References Type The Stock and the Heap Primitive vs Reference Types I We ve seen Java s 4 primitive types int double boolean char I Types other than the primitive types are known as reference types I Used for objects I Examples of reference variables Dog d1 Counter c1 Player mario String name Note String is an object not primitive type 55112 2 Memory Stack and Heap I When we run Java programs memory is allocated for variables and objects I Understanding how this memory is managed helps us understand how Java works I The JVM uses two kinds of memory stack and heap I The stack is used to store variables of primitive type I Vvhen created in the DrJava interactions pane I During method calls I The heap is used to store objects 555112 How the Stack Works boolean done false Note Variables are added in the order they are declared 555112 4 Reference Type I In Java no variable can ever hold an entire object I One variable can only contain one thin I Object consists ofmultiple of datastate and hence store I The term reference is used because it refers to a memory location where the object live I The variable of reference type is used to access the object I The value of reference variable is either null or a ressquot I nullmeans currently not pointing at any location ESEMZ Value of a Reference Variable Example gt Counter 1 gt 1 null gt c1 new Countero gt c1 Countereeo ad I e05ad6 is location in memory where c1 resides I e05ad6 nexadecnnalbase16 number Tnis location Will different on your computer I We don39t have to and can39t deal with these hex numbers directly Convenience or using variables ESEMZ How the Heap Works DrJava Interactions Stack and Heap gt me x e 99 gt emcee e1 C ml gt e1 x 1 U STACK iH Al i gt cl new Cnuntel O i gt 1 c 9m I CounterZrBBEr x a i L STACK HEAP gt 11inuremenwnunt0 gt Counter 12 new sauntero Counter4a ac ESEMZ Aliases I Two or more references can point to the same object I These references are then known as aliases I Example In Dr Java Interactions Pane gt g oi new Dog Lassie 5 gt dl Dog83d8be dli gt d2 Dog83d8be gt oi getAge gt o2 getAge 5 ESEMZ String I A sequence of characters I A String is a builtin Java objectt e I Java provides this type because it s used so frequently I Examples of String creation gt String 1 new String hello gt String 52 v39hello smartly used shortcut 2 52 Th result is v 100 gt Systemoutprint1n5239 The result is 100 ESE11Z String contd DrJava Interactions Stack and Heap gt Slxlnq cl MW suinqwmnn gt String c1 new String quotHillquot gt quotHi e I We do not get heap address of String reference I Later when we learn Inheritance it will be clear ESE11Z E5E112 Engineering Lab Introduction to Electrical Circuit Theory Electric Charge I Fundamental to all Electrical phenomena I Is a property of atomic particles ofwhich matter exists I Protonsve Electrons ve I Measured in CoulombsC I 1 C 62 x 10IE charged particles EsEiiz Electricity I Charges can become mobile ilthere is force to move I Voltage V is the energy required to move a unit charge throug an element 39 Pnieriiial diliereriue between We pniriis 39 Measured iri Volts W i e IJnuleI Cnulnrnb h I I Motion olcharges creates Electric Current I Current is the rate offlow of charge Easytn measure currenttriari measuring charge Measu ie ICnulurnbIsec CurrentllnwsImrnriigrirpnteritialtn Inwpnteritial The arreeirgn nitrie current istakeritn be astrie movement gr pnsitiyechargesie nppnsitetnllnwnlriegatiye charges EsEiiz Resistance R I Is the opposition to the ow of charge I Depends on I Directly proportional to length of element I I Inverser proportional to crosssectional area A I Inverser proportional to conductivity of the element I Measured in Ohms Q EsEiiz Relationship between VIR Kirchoff39s Electrical Laws I Voltage Law I Sum of the Voltage around a closed path or loop is zero ET I Current Law I Sum of current entering a node B or closed boundary is zero Ohms Law V IR 55112 5 55112 5 Resistors in Series and Parallel Voltage Divider I Find Equivalent Resistance I Resistors in series ReqR1R2Rquot quoti Ill I Resistors in Parallel v 7 Vin 4 P f 1 1 1 ll Viml oul 2 v Req R1 2 I Using KVL and KCL we can prove Series and Parallel Equivalent Resistance Equations 55112 7 555112 Summary of Symbols l Battery a x a Resistance W Variable Resistance ESE112 Measuring VIR I Digital Multimeter Meter DMM can measure VI R I Voltage I Connect the DMM to the two points in a circuit where you want to measure voltage I Resistance I Measure the across the resistor while not connected in the circuit I Current I Get that current to flow through the DMM ESE112 10 Polarity When Measuring I Polarity is important I Usually the terminals of the DMM will be coded to indicate polarity I Red terminal positive and a black terminal negative I If you get a negative reading means that your DMM probes are reversed ESE112 Introduction to Programming Wm Jam m BegMel39s Loops while amp for How can we help Bart ESEMZ A LOOP I Asim le but owerful mechanism for making lots 0 things appenquot I Performs a statement or block over amp over I Usually set up to repeat an action until some condition is satis ed I Computing Scenarios Examples I Run an application until user hits quit button I Deal card hands until game over seem Syntax of the while statement while condi tion statements oonditionls atruetalse boolearl expresslorl lt oondition l5 lrlltlally false the statement l5 never executed lt oondition l5 true statement l5 executed and condition l5 reevaluated The statement should eventually make tne loop stop ESEMZ A whie Loop to Print Numbers Print the numbers 1 thru 10 int x 1 while x lt 10 Systemoutprintlnx x x 1 l I What happens ifyou forget the statement x x 1 I We print value 1 forever I Known as in nite loop EsE112 More Infnfe Loops Some infinte loops are intentional boolean notQuitKey true while notQuitKey statement 5 l Others are not int x 5 while x lt 10 statement 5 which don t change x EsE112 Compute Square of first 10 numbers In Squarejava int num 1 int sqNum 0 while num lt 10 sqNum num num Systemoutprintlnnum quot quot sqNum num num 1 EsE112 For Loop for init endtest reinit statement I Executes loop body statements within as long as endtestevaluates to TRUE I Initialization and reinitialization code included in loop statement I Note Test is evaluated before executing loop body EsE112 While vs For39 Explanation int x 1 while X lt 10 System out println x x x 1 for int x 1 x lt 10 x x 1 A for loop that does the same thing System out println x Note For loops are used generally for bounded iteration EsE112 Summary of Loops while condition statement 5 for exprl condition expr3 statement5 EsE112 Introduction to Programming with Java for Beginners GUI Casting amp operator Switch statement Main with arguments Heap Management Intro to Graphical User lnterfaceGUl I Create a Window in which to display things usually a IFrame for an application or a IApplet for web browser I Use the setLayoutLayoutlanager manager method to specify a layout manager I Create some Components such as buttons panels etc I Add your components to your display area according to your chosen layout manager I Write some Listeners and attach them to your Components gt Interacting with a Component causes an Event to occur gt A Listener gets a message when an interesting event occurs and executes some code to deal with it EsE112 2I15 Necessary Packages to Import I The GUI components are in javaxswing so you always need to import that for a Swing application I Swing is built on top of AWT Abstract Window Toolkit and uses a number of AWT packages including most ofthe layout managers so you need to import javaawt I Most listeners also come from the AWT so you also need to import javaawtevent EsE112 3I15 Events and Listeners I Interacting with a GUI component such as a button causes an event to occur I An Event is an object in Java I You create Listeners for interesting events gt Listener is an interface you create a Listener by Implementing that Intertace I The Listener method gets the Event as a parameter EsE112 15 actionPerformed Method public void actionPerformedActionEvent event I Ifthere are multiple GUI components then we want to know which button was pressed and what to do with them I eventgetource return reference heap address to the object component that caused the event I ifeventgetSource buttonl do something else if eventgetSource button2 do something different EsE112 5I15 Casting with Numeric PrimitiveTypes I Numeric types are considered wider or narrower than other numeric types gt Based how much memory space they occupy I Java doesn t mind ifyou assign a narrow value to a wide variable double n 3 I Java is not happy if you assign a wide value to a narrow variable int n 35 l llegal I But if you want to narrow assign a wider type to a narrower type you have to cast it double d 3539 i int d Illegal due to casting I Java checks to make sure that the cast works and gives you an error if it didn t EsE112 6 Casts with Reference Types public class Vehicle public class Car extends Vehicle protected int numDoors protected int regNum ublic Carint r int n public Vehicleint r regNum r superr or regNum r num oors public int getRegNum return regNum public int getDoors return numDoors l EsE112 7 Casts with Reference Types contd gt Vehicle v new Car454 valid gt vgetRegNum 45 gt vgetDoorsO Error I Illegal because v could potentially refer to other types of vehicles that are not cars I The solution here is to use typecasting EsE112 8I15 Casts with Reference Types contd I If for some reason you happen to know that v does in fact refer to a Car you can use the type cast gt 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 So you could do CarvgetDoors EsE112 9 The increment operator l adds 1 to a variable gt It can be used as a statement by itself or Within an expression gt It can be put before or aftera variable gt If before a variable preincrement it means to add one to the variable then use the result gt If put after a variable postincrement it means to use the current value of the variable then add one to the variable I The same applied to decrement operator EsE112 1o Examples of int a 5 a a is now 6 int e 5 intfe 1ntb5 ei56fi55 b bis now6 intgtlt10 inty100 I 39ntz gtlt th5 gtlti511yi5101zi5111 intd c cis 6 d 156 Confusing code is bad code so this is very poor EsE112 11 char I The primitive type char gt Just stored as numbers gt Each char as a unique integer value based on Unicode standard I You can use characters in arithmetic they will automatically be converted to int gt char ch 39A39 gt ch 1 66 gt char ch2 char ch 1 cast result back to char EsE112 12 Syntax of the switch statement 39 The syf tax 395 I The expression must yield an swttch exrrefslon integer or a character He case va Statements i I Each value must be a literal rea integer or charac er case valueZ Statements I Notice that colons are used well as semicolons rea more cases default The last statement in every case statements should be a break reak gt leven like to do this in the I The default case handles every value not otherwise ndled EsE112 13 Example switch statement switch cardValue case 1 SystemoutprintquotAcequot rea case 11 SystemoutprintquotJackquot break case 12 SystembutprintquotQueenquot break case 13 SystemoutprintquotKingquot break default SystembutprintcardValue break EsE112 14 Main public static void main String l args I Must have the exact signature gt Only variation allowed is name of the input parameter I 80 main starts everything how do we call main and provide inputs 2 I To run a program recall gt Command java ClassName This what calls the main method if the class has one gt So we could pass arguments as follows java ClassName listofarguments EsE112 15 Main with arguments example public class ExampleArgs public static void mainString args SystemoutprintlnquotDemo for Inputs argsquot forint i 0 i lt argslength i systemoutprintlnargsi gtjava ExampleArgs ESE 112 Demo for Inputs args ESE 112 Note Code works even if no arguments are passed to main because JVM passes to main a zerolength array of Strings and not a null EsE112 16 Memory Management I Memory is not infinite I Stacks grow and shrink I Heap gt Grow when you dynamically allocate memory ie new Object gt If you do not manage the allocations then you will run out of this memory Objects that will never be accessed or mutated again by application need to be reclaimed This is known as Garbage Collection I Some Languages like CC leave it upto the programmerto do explicit memory management I Java does automatic garbage collection gt Done by JVM Java Virtual Machine EsE112 17 Introduction to Programming Wifz Java for Beginners Intro OOP with Java ObjectOriented Programming OOP Model I Design problemsprograms such that they correspond to real world entities I aka Object I Something that has real existence I Examples person dog car student bank account EsE112 126 Objects I Objects have I DataState information about that object I Behaviors describe how the object behaves I Class in Java for GOP model I Is an abstract description of objects gtDescribe common features to all objects I Templates for creating objects I Hence object is an instance of a class ESE 1 12 226 Example 1 Student Object name Tux address Helsinki 39or CSE courseList CSE380 CSE331 CSE320 I Data name address major courseList I Behavior change address change major adddrop a course EsE112 Example 2 Dog Objects Mi 2 EsEnz ESE I Classes contain GOP in Java I A Java program is a collection of objects Objects model the parts of a problem Data Fields that hold the data for each object gtData is stored in variables instance variables Methods that describe the actionsbehaviors the object can perform Constructors that tell how to create a new object of this class 112 OOP Class S l39r39uc l39ur39e class Classname Data Fields data for each object Constructor create a new object of this class Methods describe the behaviors the object can perform EsEnz EsEnz Data Fields Classes describe the data held by each of its objects I Also known as instance variables class Dog String name int age rest ofthe class Data Fields contd I Data can also describe the relationship of the object to other objects I Example a checkingAccount might have gtAn accountNumber used as an ID number gtA balance the internal state of the account gtAn owner some object representing a person ESEttZ 826 Constructor I A constructor is a piece of code that I Constructs or initializes a new object of that class I If you don t write a constructor I Java defines one for you behind the scenes I ie defautconstructor I Usually a constructor is written to initialize an object s data fields I Constructor can take input parameters I Default constructor initialize object s state default value for that type Eg for type int the default value is zero ESEttZ Constructor Initialize Data Example Example 1 Example 2 class Dog class Dog String name String name int age int age constructor wi w parameters constructor without parameters DogString Name int Age Dog name Name39 name Unknown age Age age rest of the class rest of the class I Important Constructor name is same as ClassName I A class can have more than one constructor ESE t 12 1026 Creating ObJects I Decare a variable of appropriate type to hold the object I The type of an object is the class that describes that object gt Eg For Dog object we a need a variable of type Dog I To create an object og Fido 5 make a new object ma e a new object I The keyword new allocates space for the object in computers memory I Constructor initializes the data of the object ESEt 12 1126 Methods I A class may contain methods that describe the behavior of objects I Two kinds of Methods I Query Methods ask an object about its state gt What39s your name Age Amount in Bank Account I Command Methods change an object39s state gt Withdraw 100 from my bank account gtmy bank balance I Methods just like how you are use to writing static methods I But written without the keyword static EsE112 1226 Example of Method Methods usually go after the data amp const tor style rule class Dog veld quot quot mt dOgAge l Note Methods age dOgAge have access to l instance variables defined within int getDOgAge class outside of a any method return age ESEIIZ 326 CallingInvoking a Method on an Object I CallingInvoking a method on an Object I Is a programming terminologyfor asking or making an object to perform some behavior I In general I objectNamemethodName0 parameters I Note that in a method call gt the number order and type of arguments must match the corresponding parameters I Examples d1 getAgeO d1 setAge5 EsE112 1426 Temporary Local vs Instance Variables I Temporarylocal variables are known I From the point of declaration until the end curly brace of the block in which they are declared I In contrast instance variables are I Declared outside of any method I Known to all methods in the class in which they are declared EsE112 1526 Asking Object about its data directly I It may possible to ask a object about its data without querying the Examplequot Dquot Java object D 9ud139 Few Dog Fido 5 l ObjectName ataFied dl ge 5 I But you can prevent Milage 6 such change by 211395 making object data private I Eg private int age ESE 1 12 1626 Putting it all Together I When you want to create standalone Java application program one of the classes should contain the main method I Entry point into your program I Method main is not part of any object I Hence it is static I In main 0 we create objects ask objects to do something or interact with another object EsE112 1726 Main Method public class DogTest public static void mainString args Dog d1 new DogquotFidoquot 5 creates a Dog Systemoutprintln Age d1 getAge d1 setAge6 change Fido s age from 5 to 6 Systemoutprintln Name d1 getName Systemoutprintln Age d1 getAge ESE 1 12 1826 A Counter class example IncrementCount gt Counter reset Counter int count 4 7 int count 0 EsE112 1926 Complete Counter class public class Counter Data field instance variable Counter class declaration EsE112 2026 Counter Object Behaviors I Counter c new Counter I If you want to increment count value of object c l cincrementCount I If you want see the count value of object c I ccurrentCount I If you want to reset count value of object c I creset EsE112 2126 Complete Counter Program public class Counter private int count public Coumer or int whatlsCount 0 cou l cincrementCount public in ge c um H cincrementCount 0 return count whatlsCount ccurrentCount l SystemoutprintnwhatlsCount public void incrementCount 0 95959 ount 1 whatlsCount ccurrentCount SystemoutprintnwhatsCount public void reset count 0 l EsE112 l ends the class public static void mainString args Counter c ew Counter 2226 General OOP Java Program I A program consists of one or more classes I Typically each class is in a separate java file EsE112 2326 Writing and Running Programs in GOP I When you write a program I You are writing classes and all the things that go into classes I Your program typically contains commands to create objects and make them do something I When you run a program I It creates objects and those objects interact with one another and do whatever they do to cause something to happen ESE I 12 2426 OOP Recap I Class a template for creating objects I An object is an instance of a class I Example I One Dog class I Multiple Dog objects I Lord of the Rings Simulation gtOne Human class multiple Human objects gtOne Elf class multiple Elf objects gtOne Orc class multiple Orc objects ESEI 12 2526 Advantages of OOP I GOP is conducive to good design and efficient redesign I Most changes affect only a few classes ESE I 12 2626 Motivation for39 Methods Introduction 1390 Programming I Break up a complex problem into simpler sub problems which you can solve separately l Eg Chocolate cake dessert gt Baking a cake amp preparing the Icing with Java for Beginners I Write once and reuse Static Methods I This is an application ofthe DRY principle Don t Repeat Yourself I Methods are also known as procedures subroutines functions EsE112 About methods Method Syntax Method t th d te I A method is a named group of statements imam type me a name parame rs Header I You execute those statements by calling the statements Method method Body I When you call the method you can give it parameters information Example I A method typically has a return value a single 1 323313 i e piece of information coming out of the method return age gt magicAge parameter I Example 2 t statemen s remquot value double averageint a int b i int c a b 20 quot return a EsE112 2 EsE112 Method Names Parameters I The parts of your computation can be given a name I So you can reuse it later myjust using the name I Variables that get declared within parentheses ofa method header I Each variable is ass00iated With type I Proper choice of method names is important I Verbs are usually best since methods do I Are mpUts thatW39quot be used to do some somethingquot computation Within the method I Naming rules are the same for naming variables I A method can have 0 or more parameters gtDescriptive names make your program more readable EsE112 4 EsE112 Returning a result from a method Returning no result from a method I If a method is to return a result it must specify I The keyword void is used to indicate that a method the type of the result doesn t return a value I boolean isAdult I There are two ways to indicate void method Execute a return statement by itself no return values I You must use a return statement to eXIt the Reachthe closing brace ofthe method method with a result of the correct type I return age gt magicAge I Example b I Ad It t void printAgeString name int age 00 eaquot ls u In age Systemoutprintlnname quot is quot age quot years oldquot Int magIcAge 21 return return age gt magicAge EsE112 s EsE112 Keyword Static I For now all methods must contain keyword static before the returntype of a method I Eg static boolean isAduItint age I Later we will see nonstatic methods with ObjectOriented Pro rammin 555112 a Accessibility Level Modifier I To control the usage Methods and Classes I Who has access I public makes the method accessible from outside the class Eg public static void main String l args I privatenot accessible outside the class I In default case ie no mention of public and private accessible if within same directory I Accessibilityeve appears before I static keyword for static method I class keyword for class description 555112 9 Methods within Classes I Methods are always written within a class I Ig In Circlejava public class Circle public static double area double radius final double Pi 314 return radius radius Pl 555112 10 Calling or39 Invoking 0 Static Method I A way to use the method as part ofan expression I Within the same class staticMethodNameparameters I Examples 1 double a area30 2 double X 55 double a areax Systemoutprintlna 555112 11 Calling or39 Invoking 0 Static Method I Outside class in which it is declared in I Examples 1 double a Circlearea30 2 double a Circleareax EsE112 Main Method public static void mainString args I A special static method I Whose return type is void and I Input Is a String array more or arrays later I Entry point of a java program ie where the instructions starts to get executed step by step I Ifthere is variable declared then space is allocated in memory I If it comes across method call then method declaration and statements are executed I Until the last statement after which terminates the program EsE112 Option 1 w Main Method public class Circle public static void mainString args double a area3U Systemoutprintln Area a public static double area double radius final double Pl 314 return radius radius Pl end of Circle class EsE112 Option 2 w Main Method lln TestCirclejava public class TestCircle public static void mainString args double a Circlearea30 Sstemoutprintn Area a l and of TestCircle class lln Circlejava public class Circle public static double area double radius nal double Pl 314 return radius radius Pl lend of Circle class EsE112 sumOdd Implementation 1 public static int sumOddint n sum positive odd numbers upto n ew sum 3 4 int sum 0 forinti1iltnii2 sum sum i return sum EsE112 sumOdd Implementation 2 public static int sumOddint n sum positve odd numbers upto n eg sum3 4 int sum 0 forinti1ilt nii1 ifisOddi sum sum i return sum EsE112 Return statements in loops I Return statement should last statement before ending method I Having return statements within loops will cause compiler to throw syntax error I This because the compiler does not know whether the statement is reachable or no I Always use variable to store the value and then finally return that value EsE112 E5E112 Java Programming Loops while amp for How can we help Barf SEMI A Loop I A sim le but owerful mechanism for making lotso things appenlquot I Performs a statement or block over amp over I Usually set up to repeat an action until some condition is satis ed I Computing Scenarios Examples I Run an application until user hits quit button I Deal card hands until game over SEMI Flowchart View of a Loop ll 39zndmn s I imam slaw Syntax of the HIMe statement While condition statement 5 l I condition is a truefalse boolean expression I If condition is initially false the statement is never execute I If condition is true statement is executed and condition is reevaluated I The statement should eventually make the loop stop EsE112 A A wh39e Loop to Print Numbers Print the numbers 1 thru 10 while x lt 10 System outprintln x x x 1 l I What happens if you forget the statement x x 1 I We print value 1 forever I Known as in nite loop EsE112 More InfHire Loops Some infinte loops are intentional boolean notQuitKey true While n tQuitKeY Note ifthe boebot needs statement 5 to continuously readoutput something then it will be in a Whiletrue loop T t th t39 39 i Others are not 050p 53039 Slmpy bring the switch to 0 position int x 5 while x lt 10 statement 5 which don t change x EsE112 Compute Square of first 5 numbers In Squarejava int num 1 int sqNum 0 while num lt 5 sqNum num num Systemoutprintlnnum quot quot sqNum numnum1 EsE112 For Loop While vs For39 for init endtest reinit Explanation t t t int x An example of S a men while x lt 10 a while loop Systemoutprintlnx that has this pattern x x 1 I Executes loop body statements within as long as endtest evaluates to TRUE I Initialization and reinitialization code included in loop statement for intx1xlt10xx1 A for loop Systemoutprintlnx that does the I Note Test is evaluated before executing loop same thing body Note For loops are used generally for bounded iteration ESE112 8 ESE112 Summary of Loops Type of Loop Syntax while while condition statement 5 for exprl condition expr3 statements ESE112 Introduction to Programming with Java for Beginners Comparing Strings Import Statement Do while Loops Continue amp operator Switch statement Comparing Strings I If the operator is used gt Java compares the addresses where the String objects are stored not the letters in the String v I Use the String class39 equals method to compare two Strings for equality gt aequalsb true gt bequ alslgnoreCase Hlquot true String class is part of Java Language just I ke Math class EsE112 2I15 Packages and import Statements I lfa class is not part ofjava language iejavalang you39ll see package name I What is a package gt Basically it39s a directory that has a collection of related classes gt Eg Random Class description containsjavautilRandom gt Indicating that the Random code is stored in ja utilRandomclass somewhere on your machine gt Thejavalutil directoryfolder is known as the quotutilquot or utility I Since Random is not part of Java Language we need to tell Java where to nd it by saying gt importjavautilRandom gt Another way is to use the asterisk quotwildcard characterquot import javautil EsE112 ms Random Class I A class to create Random numbers I Constructor Summary shows the objects of this type can be created gt Eg Random r new Random I Method Summary shows that it can generate random values of types gt integers doubles etc gt Eg rnextlnt6 Generate a integer numbers between 0 inclusive and 6 exclusive gt How do I generate a number between 1 and 6 2 EsE112 ms Number Width I Numeric types are considered wider or narrower than other numeric types gt This is based partly on how much memory space they occupy gt Also based on how large a number it can hold I Java doesn t mind if you assign a narrow value to a wide variable int n 3 Java is not happy if you assign a wide value to a narrow variable int n 35 l llegal I But if you want to narrow assign a wider type to a narrower type you have to cast it double d 35 i int d legal due to casting EsE112 5I15 Casts I You can convert cast one numeric type to another I When you Widen no explicit cast is necessary gt Eg double d 5 gt But it doesn t hurt I When you narrow an explicit cast is required gt This requirement is made to help avoid accidental loss of precision I Casting tells Java that the value in the Wider type will fit in the narrower type I Java checks to make sure that the cast works and gives you an error if it didn t EsE112 6I15 char I The primitive type char gt Just stored as numbers gt Each char as a unique integer value based on Unicode standard I You can use characters in arithmetic they will automatically be converted to int gt char ch 39A39 gt ch 1 66 gt char ch2 char ch 1 cast result back to char B EsE112 ms The dowhile statement do statement 5 While condition 1 Do the statements at least once 2 If the condition is true reexecute statements repeat step 2 false we re done with the loop EsE112 8I15 Example 1 dowhile Example 1 int count 1 do l SystemoutprintlnquotCount is quot count count l while count lt 11 Example 2 char input do l input getInputFromUserO processInput input l while input q EsE112 9I15 A forwhile Ioop with continue for exprl conditionl expr2 if condition2 continue evaluate expr2 then conditionl while conditionl if conditionz continue go up and re evaluate conditionl Note Continue for do while is same as while loop ESE112 10I15 The increment operator I adds 1 to a variable gt It can be used as a statement by itself or Within an expression gt It can be put before or after a variable gt If before a variable pre increment it means to add one to the variable then use the result gt If put after a variable postincrement it means to use the current value of the variable then add one to the variable EsE112 11I15 Examples of inta 5 ais now6 1nte5 intfe intb5 eis fi55 b bis now6 in 10 1nty100 intzgtlt th5 gtltisllyislolzislll intd c cis dis Confusing code is bad code so this is very poor style EsE112 12I15 The decrement operator I subtracts 1 from a variable gt Used similarly as operator gtinta5 gta ais now4 mt c 5 5 intdccis4 gtaaisnow3 Hdis l 3 intgtlt10 inty100 intz ygtltis 9 yis 99 zis 109 Con lsing code is bad code so this is ver poor style EsE112 13I15 Syntax of the switch statement 39 The syf tax 395 I e expression must yield an swttch exlprefslon integer or a character a He case V Statements I Each value must be a literal rea integer or character case valueZ Statements I Notice that colons are used break as well as semicolons more cases default I The last statement in every case statements should be a break39 break gt I even like to do this in the I The default case handles every value not otherwise ndled EsE112 14I15 Example switch statement switch cardValue e SystemoutprintquotAcequot break case 11 SystemoutprintquotJackquot SystemoutprintquotQueenquot break case 13 SystemoutprintquotKingquot break default SystemoutprintcardValue brea EsE112 15I15 ESE112 Java Programming Inheritance Polymorphism Example PacMan and SuperPacMan public class PacMan private int x private int y public PacMan1nt x int y public void eatnot public void move public void turnLeft public class SuperPacMan extends PacMan public void turnRight turnLeft turnLeft turnLeft EsE112 Inheritance One of the key concepts of OOP I Ahierarchical relationship among classes I Establishes a superclasssubclass relationship I Establishes is aquot relationships gt eg a SuperPacMan is aquot PacMan 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 many formsquot gt Write general purpose code designed for a supertype that works for all subtypes EsE112 The extends keyword Inheritance is established via the extends keyword public class PacMan public class SuperPacMan extends PacMan Now we say I SuperPacMan inherits from PacMan I A SuperPacMan is a PacMan I SuperPacMan is a subclasssubtype of PacMan I PacMan is the supercasssupertype of SuperPacMan EsE112 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 Wi h pzivate visibility are not I Problem How to make class instance variables visible only to its subclasses I Solutlon Java provldes a thlrd VISIbIIIty modlfler that elps In lnherltance sltuatlons protected ESE112 Inheritance Tree Java has smge Inheritance each node has one parent Except for Oblect whlch has no parent ESE112 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 lmplledlmpllclt publlc class Cat l pubhe class Cat extends abjeetl l The ooect class has several methods whlch all ooect lnherlt most notably tostrlngo and equals once we lnherlt these we can also overrlde the behavlor I e make lt conform to what the object of subclass wlll do when thls method ls called ESE112 Need for equalso Comparison of St lfthe operat trlngs Java compares the addresses where the strlng objects are stored not the letters ln the strlng For example result 7 a 7 result false U e t e strlng class39 equals method to compare two strlngs for equallty a equalsb ESE112 gs The equals Method I By default compares heap addresses I By convention it is overriden to match the developer s notion of equa 39ty public class Person private int social social security it private String name public int getSocial return social public boolean equals Person p turn thissocial pgetSocial 555112 9 The toString Method I By default it returns a String containing an object s heap address I By convention it is overriden to describe the objects state I Most common usage debugging Public class C l NOIeI toetrlng Is not Prtvate Wm supported on BoeBot Private Stung del platform because memory limitations public Carstring model thismode1 miles 0 public String toString return model model miles miles ESE112 10 Constructors and Inheritance SuperPacMan b new SuperPacMan 00 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 PacMan then its own SuperPacMan I The default behavior is such that the default noargument constructor is executed I A constructor can explicitly call its parents its superclass constructor by making a call to 5uperarguments public class SuperPacMan extends PacMan public SuperPacMan int x int y sup 39 555112 11 Polymorphism Polymorphism means many poly shapes morph In Java polymorphism refers to the fact that you can have multiple methods with the same name in the same class There are two kinds of polymorphism I Overloading 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 signa ure We ve already seen Overloading scenario with Constructors Eg public BoeBotControlO public BoeBotControlPWM l PWM r 555112 12 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 fooint x double y EsE112 Overriding 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 EsE112 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 PadIan b Which of the following assignments are valid compile 11 mm 55 m39U rrw r Hg 1 21 SuperPacManw 0 Object 1 m s 7va 1 m 5 How about these SuperPacMan bb bb n PacMan0 0 bb new String bb new SuperPacManw 0 The instanceot Operator PacMan b new PacMan0 0 b instanceof PacMan Answer true b instanceof Object Answer true b instanceof SuperPacMan Answer false EsE112 b new Object EsE112 15 The instanceof Operator Supeziacman bb new SupeziacManw o bb instanceof supersacman Answer true bb instanceof object Answer true bb instanceof Eaman Answer true sscman bbb new supersacmanm 0 a variable can stare a subtype bbb instanceof supersacmanm 0 Answer true bbb instanceof Eaman Answer true EsE112 17 ESE 112 Java Programming Arrays of Primitives 1 DimensionalArray ESE112 What if we need 10 different ints for storage int numl P int an12 P int num3 P int num4 P int anS P int num6 P int num7 P int num8 P int num9 P int numlO P ESE112 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 ESE112 What is an Array I It s an easy way to declare lots of variables that all have the same type type 1 variableNane new type 1 Eg declare an array of integers int data new int5P 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 ESE112 Array Elements and Indices I To initialize integer array I dataO 6 nun I data2 12 I The number within square brackets is called an index I The valid indices are 0 thru array length 1 I 0 first element ofthe array I n l last element ofthe array ESE112 4 An Arro is an Object int data data is a reference variable whose type is int meaning array of ints At this point its value is null data new int 5 The new operator causes a chunk of memory big enough for 5 ints to be allocated on the heap Here data is a assigned a reference to the heap address data 0 6 Initially all ve ints are 0 Here data 1 10 three of them are assigned other data 2 12 values int info 6 10 12 o 0 int info new int6 10 12 0 1 ESE112 Array of Primitives int data data new mm a dame s m H datal 10 ESE112 6 Using Array Elements in Expressions An element of an array of ints can be used virtually anywhere an expression of type int is valid Likewise for arrays of other types int data new int 6 10 12 0 0 int x dataO data3 data2 data4 data3 data2 2 Systemoutprintln data0 is data0 data4 Malhpow2 data4 ESE112 Accessing an Array39s Length I ArrayNamelength gives size of the array int data data new int5 data0 5 data1 10 data2 12 datalength is 5 How to Sum the contents of an array int result 0 for int i 0 1 lt datalength i result result datai EsE112 Passing arrays I Methods can take an array as input return type methodNameint data I This gives the function to access each element of the array I It also gives it ability to change the array Hence we sa arras are I assed b reference unlike variables that are passed by values EsE112 Returning Array I Similarly a method can also return an array int methodName return arrayName I Uses I Allows any type of method to create an array I This may provide access to array that may be declared private EsE112 Complete the sum method public class Array l oolkit H Takes an array of ints as an argument returns the sum of all the integers in the array public static 139 int result for 39 nt sum int 1 data 0 int i 0 i lt datalength39 i result result datali In maln int data new int 5 10 12 0 0 int sum Array39I oolkitsumdata EsE112 Array Out of Bounds Exceptions public class ArrayToolkit public static int sumint data for int i 0 i lt datalen7th i sum sum datai return sum int data new int 6 10 12 0 0 int sum ArrayToolkitsumdata ArrayIndexOutOfBoundsException EsE112 12 Declaring Ki Initializing Arrays of Primitive Type int info1 2000 100 40 60 int inf02 new int 2000 100 40 60 char choices1 39p39 39s39 39q39 char choicesZ new char 39p39 39s39 39q39 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 EsE112 13 Complete this method public class ArrayTooll Returns true if all integers in the data array are positive false otherwise 1 public static boolean allPositiveint data EsE112 14 Finding Max l Complete max method that finds the maximum value in the array l Assume that input passed is valid no need for error Checking In main intl data new intl 6 10 12 0 0 int max ArrayToolmaxdata EsE112 15 Finding Max I Suppose you want to find the largest value in an array called scores int largestScore 0 for int i 0 i lt scoreslength i if scoresi gt largestScore largestScore scoresi I What is wrong with this approach 2 EsE112 Improved Solution I To find the largest value in an array scores of possibly negative integers int largestScore scoresO for int i 1 i lt scoreslength i if scoresi gt largestScore largestScore scoresi EsE112 Finding Location of Max Value I Suppose you want to find the location in which you find the largest value in an array scores int largestScore scoresO int index 0 for int i 1 i lt scoreslength i if scoresi gt largestScore largestScore scoresi index i EsE112 Er39r39or39 Checking I int a new int value or I lnt a b where b is of type int I lfvalue is ltO or b is null tthen we have run time errors I lfvalue 0 Creates an array object of size zero But there are no elements I lfvalue is negative then NegativeArraySize Exception is raised No check value before creating array of size va ue I Check before accessing array elements I ifa null aength 0 EsE112 Introduction to Programming with Java for Beginners Primitive vs References Type The Stock and the Heap Has A relationship Primitive vs Reference Types I We ve seen Java s 4 primitive types int double boolean char I Java also has reference types for objects I Note String is an object not primitive type I Examples of reference variables Dog d1 Counter c1 Player mario String name 555112 212 Memory Stack and Heap I When we run Java programs memory is allocated for variables and objects I Understanding how this memory is managed helps us understand how Java works I The JVM uses two kinds of memory stack and heap I The stack is used to store variables of primitive type I When created in the DrJava interactions pane I During method calls I The heap is used to store objects 555112 312 How the Stack Works DrJava Interactions Stack gt int x gt doubl 05 gt boolean done false 555112 412 Reference Type I In Java no variable can ever hold an entire object One variable c n only contain one t a hing Object consists ofmultiple of datastate and hence stored on heap I The term reference is used because it refers to a memory location where the o The variable of reference typ bject lives e is used to access the object I The value of reference variable is either null or a heap re quot add s nullmeans currently not pointing at any location 555112 512 Value of a Reference Variable Example gt Counter 1 gt 1 null gt 1 new Counteror39 gt 1 Countereeo ad I e05ad6 is location in memory where c1 resides I e05ad6 hexadeclrnal base 16 number Tnis location Wlii oirrerent on your computer I We don39t have to and can39t deal with these hex numbers directly Convenience or uslrlg varlables 555 112 512 How the Heap Works DrJava Interactions Stack and Heap c 15 gt 51 a 1 W STACK H39E Api gt 51 new Countero gt c1 a men l CuunterZfBBEf x 39 l O STACK HEAP gt 11intzremenwnunt0 gt Counter 12 new Cauntel oi Cuunter4a a5 555112 712 Stri n g I A sequence of characters I A String is a builtin Java object type I Java provides this type because it s used so frequently I Examples of String creation gt String 51 n Stingquothelloquot gt String 52 quothelloquot commonly used shoztc 2 quot you39quot quothello youquot gt 52 quot e5u1t is quot 100 he gt Systemoutpint1n52 quotThe e5u1t is 0039 555 112 ai12 String contd DrJava Interactions Stack and Heap gt String c1 new Sting ill STACK Amp Note I Dr Java does not give the heap address of String reference this because Strings are special objects gt String 01 new String quotHillquot gt 01 quotHillquot ESE112 912 Has aquot Relationship I An obtject of type A has an instan whose type is B A has a objec cggariable which is an I Eg A Freshman object whose room is of reference type Freshman ring name rmRoom room DormRoom DormRncm int number it String building ge getLocatlonU ge tName tRcom I The UML diagrams below show instancebvaritables and C methods of Freshman and DormRoom o e I UMLUniversaModelin descnbe dassesin ESE112 00 g Lanaguage industry standard used to 1012 DormRoom Code Dormoom A DormRoom on the Heap t smug bLilding gt room getLocation 203 Hill gethcatl cn gt DormRoom room new DormRoom208 Hill public class DormRoom private int num private String bldgName public DormRoomint n String b ll 11 bldgName b 1 public String getLocation return num quot quot bldgName ESE112 1112 DormRoom HEAP String gt DormRoom room new gt roomgetLocation 203 Hill DormRoom208 will ESE112 1212 Freshman Code Freshman gt DormRoom room new DormRoom208 quotHillquot Stzing name Domeoom m gt Freshman f new Freshmanquotjoquot room m gt fgetName getName getRoom J quotjgquot gt f getRoom getLocation quot208 Hillquot A Freshman on the Heap ESE112 public class Freshman private String name private DormRoom room public Freshmanstring n DormRoom r name n room 2 public String getName return neme public DormRoom getRoom return room 13I12 gt DormRoom room new DormRoom208 quotHillquot gt Freshman f new Freshmanquotj0quot room gt fgetName quotjgquot gt f getRoom getLocation quot208 Hillquot String String STACK 39 HEAP room 0 ESE112 14I12 Object creating another object public class not private int x Introduction to Programming public Dotint x int Y With Java for Beginners x x Y Y public not displacedDotint dispmt Object creating another object int newx x dispmnt Keyword thls Ureth nyntdispmt7 gt Dot d1 new Dot53 d new Dotltnewx new gt d1getX getX not shown return d 5 l gt Dot d2 d1 displacedDot5 gt d2getX 10 EsE112 Keyword this this with data fields I this is a reference to the current object public class Dot private int x I The object whose method or constructor is Private int y shadows the instance variablex amp y Localvariablex amp y being called H 1 public Dotint x int y I The value of this is an objects heap x x39 problem address Y Yr39 Can be passed as argument to a method public class Dot Can be returned as value Private int X public Dotint x int y thisx fixed thisy y 2 EsE112 EsE112 Facebook Example I FBPerson has a name and at most one friend I Rules for adding a friend I When FBPerson Achooses FBPerson B to be a friend the operation succeeds if FBPerson A i5 riot String name A has no friends FBPerson person B has no friends getNameO getFriendO Note that A has a friend who is B if and only if se AFr39quotd0 B has a friend who is A SAFr39em O addAFriend in otherwords When A adds B as a friend B must aiso add A as a friend EsE112 Facebook Example class FBPersonf public boolean addAE riendFBEerson p EsE112 ifp this thishasRFriend true II p null ret urn fa se i phssmriend true return false thissetFriendP Ilset mum F Pexsnn nhjecl s illend p5eti riendthis um Pexsnn 1quot mm m m any return true lnFHPexsnn 1 cl Interactions for FBPerson gt FBPerson jo new FBPersonquotjo brownquot gt FBPerson flo new FBPersonquotflo smithquot BPerson mo new FBPersonquotmo jonesquot gt johasAFriend al e V gt joaddAFriendflo e 39ogetE riend getName smith 4 l LI o gt flogetFriendgetName jo brown gt joaddAFriend mo 30 alxeady has a mend in 931an add Inn as ixlend false gt moaddAFriendjo false gt mohasAFriend false EsE112 Introduction to Programming with Java for Beginners Interfaces Seeing EyeDog gerTrackIngCodeo ESE112 1 What if we wanted a category oftrainable quot Trainabl animals like this 3 3 1 I z s num L makeNoisetl makeNorsetl v SeeingEyeDog xrackingCnde erTracKInaCodel ESE112 Creating an Interface public interface Trainable public void sit public void stand I An interface is like a class except I The keyword interface is used instead of class I All of its methods are body less I It has no instance variables I It can not be instantiated Illegal new Trainable IAn interface is like a contract protocol role or point of view I Code written for an interface type works with any object whose class implements it I It can assume that all of the subtypes have the methods listed in the interface eg sit and stand ESE112 A Class implements an Interface Abstract class vs Interface public class Dog implements Trainable I When a partial implementation is feasible abstract public void sit code for sit method Classes make Sen asmey can PFOVIde some functionality With the methods public void stand code for stand method I Pure abstract classes with all abstract methods in Java are functionally equivalent to an interface but A class that implements an interface reStnCted to smgle mhentance I Must provide concrete methods for each interface method J H t I t th I May have additional methods I ini xe a OW you 0 mp emen more an one 39 May 39mplement mUIt39ple 39nterfaces I Multiple interface inheritance allows an object to inherit many di eren met 0 signatures with the caveat that the inheriting Public Class Dog implements TrainablerCC mParablet object mustimplement thoseinherited methods code I You can use access modifiers eg protected in an abstract class though Interfaces are always public EsE112 4 EsE112 5 Example Trainable Interface Examples 0f Interfaces I Interfaces are typically lightweight with only a few method Key Jsiaiididj headers Immune i mums Purple ex sigmvies answer public interface Displayable publ39c void displayii Black text signi es icnncic ie public interface XYZProtocol public void connecti gt 39 Lion lion new LionO public void disconnectii gt Dog dog new D090 public int receive gt Trainable beast gt beast lion lbeast is oftype Trainable pointing to lion object gt beastsit cas lion s sit method gt beast 09 gt beastsit cas dog s sit method EsE112 6 EsE112 instanceof Operator with Interfaces 39Usage value instanceof T IThe expression is true if value has type T or is a subtype ofT I Example public class Rectangle implements Displayahle public class Square extends Rectangle gt Rectangle 1 new Rectangle2a gt r instancenf Rectangle txue gt r instancenf Displayahle txue gt r instancenf Square gt false gt r new Square10 gt r instancenf Square txue gt Square s new SquareE gt s instancenf Square true gt s instancenf Rectangle true gt s instancenf Displayahle ESEMZ What if we want to Write graphics code for all the animals and want to A Design Problem require that they all have a display method There are many ways to accomplish this I ESEMZ I cal tquot it n One of Many Solutions v am Dimnigh ms 39a assayi ESEMZ new mmme Ni Extending and Implementing I Class can only extend one other class I But can implement multiple interfaces I The exact declaring a class below public class SubclassVerne Extend lntErfacEZ I Otherwise there is compile error ESEMZ order must be used as shown below in s SuperclassNamE implements interfacei Summary Regular Class Abstract Class Interface Methods a concrete concrete andor a abstract abstract May have yes yes no instance variables May be yes no no instantiated EsE112 Who r if our39 Frog from lab could say 10 different Things In rr39oduc rlon To Programmmg public class men private boolean formerPrince m39fz Java for Beginners private string phrase1 private string phrase2 private string phraseB private string phrase4 Arrays 0f Pr39m39t39Ves private string phrases Arrays of Objects private string phrases private string phrase7 private string phrases private string phrase9 private string phraselO What a Person could adop r Io rs of Pe rs What if we won t To store Io rs of Things public class yeraon private String name I But we don t want to declare a separate ivate Pet eti p p varlable for each one private yet pet2 private yet petJ private yet pet4 ivate Pet etS 5mm m Sets I That 8 what arrays are good for private yet pets private yet pets private yet peta private yet pets private yet petlo private yet pet11 private yet pet12 private yet petu private yet pet14 private yet petis I It s an easy way to declare lots of variables that What is an Array all have the same type type 1 variableNa H type lt 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 zero Array Elements and Indices I To initialize integer array I data1 10 I data2 12 I The number within square brackets is called an index I The valid indices are 0 thru array length 1 I 0 first element of the array I n1 last element of the array An Array is an Object int data data is a reference variable whose type is int meaning array of ints At this point its value is null data new int5 The new operator causes a chunk of memory big enough for 5 ints to be allocated on the heap Here data is a assigned a reference to the heap address data0 6 datal 10 data2 12 Initially all five in ts are 0 Here three of them are assigned other values int info 6 10 12 o 0 int info new int6 10 12 o 1 Using Array Elements in Expressions An elementof an array of ints can be used virtually anywhere an expression of type int is valid Likewise for arrays of other types int data new int s1o12o0 int x data0 data3 data2 data4 data3 data2 2 Systemoutprint1n data0 is data0 data4 Mathpow2 data4 Accessing an Ar39r39ay39s Leng rh I ArrayNamelength gives size of the array int data data new int5 datalength is 5 data0 5 data1 10 data2 12 How to Sum the contents of an array int result 0 for int i i lt datalength i result result datai Comple re The sum me rhod public class ArrayTool u Takes an array of ints as an argument returns the sum of an the integers in the array public static int sulll int data r int i 0 i lt datalength i result result datali Welcome to DrJava int data new int 5 10 12 0 0 gt Array39I oolsumdata 28 Ar39r39ay OUT of Bounds Excep rions public class Array39I ool public static int sumint data 39n for int i 0 i lt datalength i sum sum datai return sum gt int data new int 6 10 12 0 0 gt ArrayToolsumdata ArrayIndexOutOfBoundsException Declaring amp Ini rializing Arrays of Primi rive Type int info1 2000 100 40 60 int inf02 new int 2000 100 40 60 charchoices1 39p3939s3939 39 char choicesZ new char 39p39 39s39 39q39 doubletemps1 756 994 867 double tempsZ new double 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 Complete This method public class ArrayTool Returns true if all integers in the data array are positive false otherwise public static boolean allPositiveint data Finding Max I Complete max method that finds the maximum value in a the arr l Assume that input passed is valid no need for error checking Dr Java Interactions Pane gt int data new int 6 10 12 0 0 gt ArrayToolmaxdata 12 Array of Primitives int 1 data data new int3 data0 5 data data1 10 Array of Objects mm m STADK HEAP Counter counters counters new Counter 3 I it has 3 references to Counters in it I all of these references are initially null can ecum Ban null mu nun STACK HEAP counters0 new CounterL counters0add0ne gt gt gt counters1 new Countern gt counters a getCount 1 gt counters 2 getCount NullPointerException E9 Person ObJec r Person Ar r GY PersonI People new Personquotjoquot neu Personquotfloquot puhhe class Persnn PersonI people new Personu new Personquotjoquot pmaee smug name pmaee m age Persnn5tr1ng has na Personquotfloquot Persnn 1 en 1e name 1nt age P P em mm Cum sage e age penple new yersanm papinl mo aauhuufaun publlc 1nt getngeo return a e publlc seung getllameo r urn name peaplem ew Persnn jn Pqnpla mm 71 ax39 azslnun ew Persun fln penple 1 E9 Person Da rabase con rd In PersonDBjava nae elaee e a P aerianuf39l ple 39 mete Pr39MDBO gtPer B peop e new PersonDBo publlc PersnnDB meme DMDBO penple new Persnn 1 new Persnn jn 25 Name 9 new Persnn flu 1E y lo 25 new P rsnn nm 19 O 18 mo 19 Caleulaeee a nd us the average age publlc dnuble getnver tux I Complete islnDatabase metho agengem gt ersonDB peop e new PersonDBO New th gt peop e statabaseC o true gt peop e 5 nDatabaseC rex fa se ESE112 Introduction to Electrical Circuits Application Robotics I Sensors to get information I A device that measures a physical quantity and converts it into a signal electrical I Eg Thermistor to measure temperature Thermistor Type of resistor whose resistance varies with temperature I Actuators used in navigation I Electrical energy is converted in mechanical energy to drive motors Usually interaction of magnetic fields and currentcarrying conductors Video of simple motor ESE112 Simple Electric Motor Electric Charge I Fundamental to all electrical phenomena I Is a proper of atomic particles of which matter exists I Protonsve Electrons ve I Measured in CoulombsC I C v4 A ulacharged particles 7 ESE112 3 Voltage amp Current I Charges become mobile if there is force to move them I Voltage V is the energy required to move a unit charge through an element Potential difference between two points Measured in Volts V ie 1 Joule1 Coulomb I Motion of charges creates Electric Current I Current is the rate of flow of charge Measured in Amperes A Le 1Coulumb1 sec Current flows from highpotential to low potential The direction of the current is taken to be as the movement of positive charges ie opposite to flow of negative charges ESE112 Buffery elec l r omo l ive force I 2 different metals in a chemical solution One metal ve charge and other ve charged I If a wire conducting material eg copper is attached from one end of the battery to the other then I Electrons flow through the wire to balance the electrical charge I If a load such as a livhtbulb is I laced along the wire the electricity can do work as it flows through the wire ESE112 Bot l er y co n l39d I House hold solution Lemon Battery Cu penny ve Zinc galvanized nail ve I Commercial AA Zinc amp carbon Alkaline Zinc amp Manganese Oxide Car battery Lead acid ESE112 AC vs DC cur r en l I Alternating Current AC I Current that varies sinusoidal with time Wall socket provide AC that alternates 60 times per second I Easy to change the voltage a device called a transformer I Direct Current DC I Batteries solar or fuel cells produce current that remains constant wit time I Current always flows in the same direction between two positive and negative terminals ESE112 Resistance R I Is the opposition to the flow of charge I Depends on Directly proportional to length of element I lnversely proportional to ossrsectional area A lnversely proportional to conductivity of the element I Measured in Ohms Q RNZ a n I Passive element R l Element which is not a ource of energy ESE112 Source wwvvpcrconlroIcouklimageslresislor codeZ gif I Resistors can be 4 band or 5 band I In 4 band resistors gt 4th band is tolerance bandgold or silver gt 3rd band is multiplier ESE112 Relationship between VIR WESE W R Unii mm W mmyllmv An electric circuit is an interconnection of electrical elements Ohms Law V IR 55112 Inter nal resistance I Easy to forget that resistance in every part of a circuit I Avoid long connecting wires I Simple longer the wire longer time it takes for the electrons to travel I Simulation software used to model electric circuits may not account that compared to a real circuit 55112 Kir39choff39s Electrical Laws I Voltage Law I Sum of the Voltage around a closed loop is zero W I Loop any path that starts and ends at the same point I Current Law I Sum of current entering a node or junction or closed boundary is zero 55112 Resistors in Series and Parallel Vol l age Divider I Equivalent Resistance I Resistors in series ReqR1 7 H2 7 I Resistors in Parallel Vquot v m 32m 1 1 1 l R nm A ont L Tl n Req R1 R2 T I Using KVL and KCL we can prove Series and R7 Parallel E uivalent Resistance E uations lquot t 39 T q q on R1 R m ESE112 ESE112 Power DC resistive circuits Summary of Symbols I Is the rate at which work is performed or energy is transmitted a h Battery I P V I 1J1C 1C1sec 1J1 second 1 Watt Jw r Reststance I Alternatively using Ohm s Law I P V VR V2R I Power Rating Variable Reststance I Primarily for elements that dissipate electric power and or convert into mechanical ower p Lu Ground reference point in an I Indicates the max powerthan can be safely E electrical Circuit from which other 39 voltages are measured dissipated by the device ESE112 16 ESE112 Diode I Allows electricity to flow in only one direction Ira D l Jamie I The arrow ofthe circuit symbol shows the direction in which the current can flow I Modern diodes are realized from semi conductors Semiconductor I Semiconductor material are in between conductors like metals and insulators like glass I In pure form it is nonconducting I Eg silicon crystal has 4 electrons in its outer orbital which form perfect covalent bonds with four neighboring atoms leaving no electrons to conduct electric current I You can change the behavior of silicon and turn it into a conductor by doping it In doping you mix a small amount of an impurity into the silicon crystal NType amp PType Semiconductors Fhoiptmus Atom 15 NType Semiconductor Abundance of electrons N for negative char e Eg Phosphorous as dopant amn39 Mom 53 PType Semiconductor A M ngummns Abundance of positive charge L3Ejm P for positive charge Eg Boron as dopant Semiconductor Diode Hole Electrons 1 39 3 39 1h 1 5 IE P Typl quot1191 as 3 xi b 15 I39 Cullanl llan mass m inminn lEl aauery Electrons and holes start moving and the depletion zone disappears At the unction free electrons from the Ntype material fill holes from the Ptype material This creates an insulating layer in the middle of the diode called the depletion zone LED Light Emitting Diode I Photons energy in form of light are released as a result of moving electrons I In an atom electrons move in orbitals around the nucleus I Electrons in different orbitals have different amounts of energy I Electrons with greater energy move in orbitals farther away rom the nuc eus I For an electron to jump from a lower orbital to a higher orbital something has to boost its energy level I Conversely an electron releases energy when it drops from a higher orbital to a lower one I This energy is released in the form ofa photon Band Gap Un lled J Conduction bands band E RBand gap Valence band F1 led band ifalriprulectsi jam EsE112 LED I Anode Long end I Cathode short end I Iypically operate Ltus between 5 20 mA ff I Never connect an LED directly to D a battery or power supply m WNW I It will be destroyed almost instantly because too much current will pass through and burn it out ujl w Introduction to Programming With Java for BEgInners Inheritance Example Bot and BetterBot pauses pubhs class Eot 1nt x pubhs 1nt getXO l pubhs 1nt getY t I ubl vold a Dot l pubhs vold moveo l I pubhs vold tutnLeftO l I pubhs class BettetEot extends sou ESE112 111 Inheritance One of key conce A hierarchical relationship among classes Establishes a superclasssupclass relationship Establishes IS aquot relationships gt e g a BellerBol IS aquot Bot Benefits Reusablllty of code Put code in one class use it in all the subclasses ReVisions only needs to be done in 1 place Polymorphic code works on many forms gterte general purpose code designed for a supertype that works for all subtypes Polymorphic data structures gt E 9 an array of a supertype can hold obiecls of any subtype ESE112 211 Inheritance Tree Java has Singe Inheritance each node has one parent Except for Obiect which has no parent C has multiple inheritance but its messy 31 1 The Object Class All classes inherit from the Object class Object class is the root of the class hierarchy I When we create a new class extends Objectquot is implied mplicit public class car 1 public class Car extends object The Object class has several methods which all object inherit most notably toString and equals EsE112 m1 The toString Method By default it returns a String containing an objects heap address By convention it is overriden to describe the object s state Most common usage debugging public class car private int miles private String model Recall toString public carstring model thism del model from RealveCtor miles o ASSIgnment public String toString return model 1 model miles 1 miles EsE112 5m The equals Method By default compares heap addresses By convention it is overriden to match the developer s notion of equa 39ty public class Person private int social social security it private String name public int getSocial return social public boolean equals Person p return social pgetSocial 555112 5m The extends keyword Inheritance is established via the extends keyword public class Bot public class BetterBot extends Bot Now we say BetterBot inherits from Bot it gets all the instance variables and methods defined in Bot unless they are declared to be final A BetterBot is a Bot BetterBot is a subclasssubtype of Bot Bot is the supercasssupertype of BetterBot 555112 m1 Type Rules A reference variable of type t may hold a value of its own type or any subtype but not of a supertype Given the following variable declaration Bot 13 Which of the following assignments are valid b new Bot b new String b new BetterBot b new Object How about these BetterBot bb bb new Bot b new String bb new BetterBot b new Object 555112 am If u 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 instance of BetterBot gt bb instanceof Object true gt bb instanceof Bot true gt Bot bbb new BetterBot Ila variable can store a subtype gt bbb instanceof BetterBOt true bbb instanceof Bot true 555112 9I11 Another Example public class Dog private String name private int age DogString dogName int dogAge N m age dogAge class BetterDog extends Dog 555112 10m Constructors and Inheritance gt BetterDog d new Betternogo 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 Dog then its own BetterDog l The default behavior is to that the default noargument constructor is executed A constructor can explicitly call its parents its superclass constructor by making a call to super class BetterDog extends Dog public BetterDogString name int age supername age 555112 11m Introduction to Programming wlfh Jam far BagImus Intro OOP with Java Object Oriented Programming OOP Model I Design problemsprograms such that they correspond to real world entities l aka Object l Something that has real existence I Examples person dog car student bank account EsE112 Object Characteristics l A Object has I DataState information about that object I Behaviors describe how the object behaves Student Object DataState name address major courseList Behavior change address change major adddrop a course EsEMz 2 More Examples I Radio I DataState onorr current voiurne current Station I Behavior gtturn onorr increasedecrease voiurne seek Station I Dog I DataState gtnarne age coior breed I Behavior gt change age bark nunng EsE112 GOP in Java I A Java program is a collection of objects I Objects model the parts of a problem Anatomy of Class in GOP I Classes contain I Data Fields that hold the data for each object gtData is stored in variables I Class In Java for GOP model I IS an abstract description of objects I Methods that describe the actionsbehaviors the object can perform gtDescribe common features to all objects gtTemplates for creating objects I Constructors to initialize object with some I Hence we say that object is an instance of a 39 class information gt Each object has its own unique data E5912 E5912 OOP Class S l39r39uc l39ur39e class Classname Example 2 Dog Objects Data Fields data for each object quotConstructor create a new object of this class Methods describe the behaviors the object can perform E5912 6 E5912 Data Fields I Classes describe the data held by each of its objects I Also known as instance variables class Dog rest of the class EsE112 Constructor I A constructor is a piece of code that initializes a new object I Used to initialize an object s data fields I Constructor can initialize data to set value or taken external values I If you don t write a constructor I Java defines one for you behind the scenes ie default constructor gt The data will initialize to the default value for that type gt Eg for type int the default value is zero EsE112 Constructor Initialize Data Example Example 1 Example 2 class Dog class Dog String name String name int age int age constructor wi w parameters constructor without parameters DogString Name int Age Dog name Name name Unknown age Age age 1 rest of the class rest of the class I Important Constructor name is same as CassName I A class can have more than one constructor EsE112 Creating Objects I Class is just an abstract description I In order to use objects we need to create them Step 1 I Declare a variable of appropriate type to hold the object I The type of an object is the class that describes that object I Eg For Dog object we a need a variable of type Dog gtDog d1 gtDog Fido EsE112 Creating Objects contd Step 2 I Create object with keyword new and call to the constructor Dog d2 D090 d2 Dog Fidoquot 5 a new object make a new object I The keyword new allocates space for the object in computers memory I Constructor initializes the data of the object EsE112 Methods I A class may contain methods that describe the behavior of objects I Two kinds of Methods I Query Methods ask an object about its state gtWhat s your name Age Amount in Bank Account I Command Methods change an object s state gtWithdraw 100 from my bank account my bank balance changes I Methods just like writing static methods I Butwritten Withoutthe keyword static EsE112 Example of Method Methods usually go after the data amp cons tor style Iule class Dog VOid int degAge Note Methods age dogAge have access to instance variables defined within int gemogAge 0 class outside of any method return age EsE112 Sending messages to objects I We don t perform operations on objects we talk to them I This is called sending a message to the object I A message looks like this objectmethodextra information gtThe objectis the thing we are talking to gtThe method is a name of the action we want the object to take gtThe extra information is anything required by the method in orderto do its job EsE112 Sending Messages to Objects contd I objectNamemethodName0 parameters l Examples d1getAge d1setAge5 l Note the number order and type of arguments must match the corresponding parameters as in the methods header description I Is just like CallingInvoking a static method but in OOP we asking or making a particular object to perform some behavior EsE112 16 Temporary Loca vs Instance Variables I Temporarylocal variables are known I From the point of declaration until the end curly brace of the block in which they are declared I Cannot use modifier private or public with these I In contrast instance variables are I Declared outside of any method I Known to all methods in the class in which they are declared I Can use modifier private or public with these EsE112 17 Asking Object about its data directly I It may possible to ask a object about its data Without querying the object Example in Dr Java I public or no modi er gtDog d1 new I ObjectNameDataField Dog Fidoquotl5 gtd1age 5 gtd1age 6 gtd1age I But you can prevent such 6 change by making object data private I Eg private int age EsE112 18 Encapsulation or Information Hiding I One of the advantages of OOP is that object need not reveal all of its attributes datastate and behavior I We can hide details of one object from another I Use modifiers privatepublic to hide information I Ideally we make all instance variabes private I Provide methods querycommand if you want to allow the data to read or written I Getter methods to read eg getAge I Setter methods to modify eg setAge gt not necessary to rovn e EsE112 19 OOP Recap I Class a template for creating objects I Variables data I Methods behavior I Constructor initialize data I An object is an instance of a class I Dog d new Dog Lassiequot5 gt d is an object of class Dog I A Java program is collection of cooperating objects I Eg Lord ofthe Rings Simulation One Human class multiple Human objects gt One Elf class multiple Elf objects gt One Orc class multiple Orc objects gt One weapon class multiple weapon EsE112
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'