Exam 1 Study Guide
Exam 1 Study Guide CSC 120
Popular in INTRODUCTION TO COMPUTER PROGRAM
Popular in ComputerScienence
This 20 page Study Guide was uploaded by AnnMarie on Monday December 14, 2015. The Study Guide belongs to CSC 120 at Louisiana Tech University taught by Debra Blackman in Winter 2015. Since its upload, it has received 183 views. For similar materials see INTRODUCTION TO COMPUTER PROGRAM in ComputerScienence at Louisiana Tech University.
Reviews for Exam 1 Study Guide
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: 12/14/15
Chapter 1 Objects and Classes An object is an abstraction of a set of real world things such that all the realworld things in the set the instance have the same characteristics all the instances have the same behaviors In class Blackman suggested that we should use a large dounut as an typlate when creating objects because the hole center will be the attributes that make up the object and the outside cake part makes up the actions or behaviors that the object can do Objects are created from classesThe class describes the kind of object the objects represent instantiations of the class Objects are refered as instances We use naming conventions while programing to make it easier to distinguash between classes and objects A class will have the first letter uppercase such as Animals An object will have the first letter lowercase and any additional words will begin with uppercase such as whiteLion In Blue J using the figures example we created an instance object by creating a new Circle by right clicking on the Circle Class and choosing new Circle We left the automatic name for the new instance object alone and clicked Ok We noticed that at the bottom of the screen there was a red rectangle that had circle1 Circle this area is called the object bench and it will show all instances objects that were created When you rightclick on the circle instance an operations menu If you click on the void makeVisable the circle instance will appear in a separate window These operations are called methods which in turn are called or invoked You can move the circle instance with any of the move operations such like void moveRight and a dialog will appear prompting fo an input This prompt is asking for the parameter which can be anything from a number to text This provides additional information to the method If you look at the list of methods for the circle instance they begin with void and then some name with parameters at the end This is called a singature The part enclosed by parenthese int distance is the information about the required parameter and also defines a type and a name The type defines what kinds of values a parameter can take and the name gives a hint about the meaning of the data expected For instance void moveRightint distance is looking for the data type of an int because that will be the distance that it moves right If you tried to change the color of circle1 you may have notice that it gives an error if you type in blue This happened because it was looking for a character type and you have to put around the text If you look at Appendix B in the textbook you will find a table that describes the different data types that exist in Java On the next page you will notice that I included that table in these notes Type Name Description Example literals Integer Numbers byte bytesized integer 8 bit 24 2 short short integer 16 bit 137 119 int integer 32 bit 5409 2003 long long integer 64 bit 423266353L 55L Real Numbers oat singleprecision oating point 43889F double doubleprecision floating point 4563 24e5 Other Types char a single character 16 bit 39m39 3939 39u00F639 boolean a boolean value true or false True False Once you have a class you can create multiple instances of that class and each instance has its own attributes So if you make changes to circle1 it will not affect circle2 These attributes define an instance39s state represented by storing value in fields In BlueJ the state of an instance can be inspected by selecting the Inspect function from the instance39s popup menue The object inspector window will display the details of the object Some methods when called change the state of an instance Java referes instance attributes as fields When multiple instances are created the instances of the same class have the same fields This is because the class determines how many fields will the instance have and also defines each instance39s field types This is similar for methods also Methods are defined in the class of the instances and all instances of a given class have the same methods When programing in Java we write instructions down to invoke methods on instances Taking a look at the following code we can determine the following Person person1 new Person person1makeVisible person1moveRight First a new person instance was created from the Person class and stored to person1 as the variable name Second person1 was made visible by changing the field isVisible to true by invoking the makeVisible method on the person1 instance Third the instance was move to the right by invoking the moveRight method In BlueJ you can use the Show Terminal from the View menu to see the text output when methods are called You will need to select the Record method calls from the terminal39s options menu to see the text To be able to invoke methods in Blue you will need to open the Show Code Pad from the view menu This allows you to type Java code Note if you leave out the after a method call you will recieve an error The Blue project house shows that instances can create other instances by calling each other39s methods To look at the source code for the house project rightclick on the Picture class and select Open Editor If you make any changes to the source code you need to recompile the class This can be done by clicking on the Compile button The BueJ project labclasses is used to explain that methods may return values and that objects can be passed as parameters to other methods The value that results from a return is called the result value If you look at the code below you will see that the word void is not infront This is because void does not return a value public String getName return name When invoking the enrollStudent method you may notice that it takes the instance student1 student2 ect This is passing the object as a parameter to the enrollStudent method for the LabClass class Keywords that you may want to remember Object Java objects model objects from a problem domain Class Objects are created from classes The class describes the kind of object the objects represent individual instantiations of the class Method We can communicate with objects by invoking methods on them Parameter Methods can have parameters to provide additional information for a task Signature The header of a method is called its signature and it provodes inforamtion needed to invoke that method Type Parameters have types The type defines what kinda of values a parameter can take Multiple Instances Many similar objects can be created from a single class State Objects have state The state is represented by storing values in fields Method Calling Objects can communicate by calling each other39s methods Source Code The source code of a class determines the structure and behavior the fields and methods of each of the objects in that class Result Methods may return information about an object via a return value The following code declares a class and assigns the attributes or fields that the class will have Note that the class word is a keyword and cannot be used for anything else Public class Picture private Square wall private Square window private Triangle roof private Circle sun private Person person The following code declares a method and inside the method a wall object is created and methods of the Picture class is called to create the wall public void draw wall new Square wallmoveHorizontal140 wallmoveVertical20 wallchangeSize120 wallmakeVisible The following code returns the name of the object that is calling the method public String getName return name The following code enrolls a student object but it first checks to see if the current number of students does not exceed the number declaired when the the lab class was created public void enrollStudentStudent newStudent ifstudentssize capacity SystemoutprintlnquotThe class is full you cannot enrolquot else studentsaddnewStudent The following code is a print method and inside the you see the Systemoutprintln which allows the system to send the information in the 0 If you want to print text you must have the text enclosed in The allows you to add variables to the print out public void printList SystemoutprintlnquotLab class quot timeAndDay SystemoutprintlnquotInstructor quot instructor quot Room quot room SystemoutprintlnquotClass listquot forStudent student students studentprint SystemoutprintlnquotNumber of students quot numberOfStudents Chapter 2 Understanding Class Definitions 23 The class header The text of a class can be broken down into two main parts a small outer wrapping that simply names the class and a much larger inner part that does all the work The following code is an example of a class header public class Animal lnner part of the class is omitted The outer wrappings of different classes all look pretty much the same The outer wrapping contains the class header whose main purpose is to provide a name for the class We always start class names with an uppercase letter a widely used convention The words public class and private are known as keywords and they are reserved which means you cannot use them as names for variables methods etc 24 Fields constructors and methods The inner part of the class is where we define fields constructors and methods that give instances objects of that class their own particular characteristics and behaviour In Java there is very few rules about the order in which you choose to define the fields constructors and methods within the class However for CSC 120 and the examples in the textbook they choose to define fields first constructors second and finally methods Fields are also known as instance variables because the word variable is used as a general term for things that store data in a program Each field has its own declaration in the source code The following code is an example of a field variable that is declared within the class public class Person private String name At this point we begin to see a pattern that applies whenever we define a field variable in a class I They start with a reserved word private I They include a type name such as int String Person etc I They include a userchosen name for the field variable I They end with a semicolon Constructors allow each object to be set up properly when its first initialized This process is called initialization One of the distinguishing features of constructors is that they have the same name as the class in which they are defined The constructor39s name follows immediately after the work public The code below displays this concept public class Person private String name public PersonString firstName name firstName One thing to note is that the name is initially determined externally and then is passed into the constructor When examining the source code for TicketMachine you will notice above the fields The allows you to enter a single line comment It is suggested that you use a single line comment to eXplain why you have a field named a specific way or to explain something happening in your code 25 Parameters receiving data Parameters are another sort of variable just as fields are so they are also used to hold data Parameters are variables that are defined in the header of a constructor or method If you look at the example for the constructor in the Person class you will notice that the parameter is enclosed in parentheses has a type defined and has a user provided name The parameter acts as a temporary messenger carrying data originating from outside of the constructor or method and making it available inside To distinguishing between the parameter names inside a constructor or method and the parameter values outside we refer to names as formal parameters and the values as actual parameters A formal parameter is available to an object only within the body of a constructor or method that declares it The scope of a parameter is restricted to the body of the constructor or method in which it is declared However the scope of a field is the whole of the class definition can be accessed from anywhere in the same class A concept related to variable scope is variable lifetime The lifetime of a variable describes how long the variable continues to exist before it is destroyed The lifetime of a parameter is limited to a single call of a constructor or method When a constructor or method is called the extra space for the parameter variable is created and the external values copied into that space Once the call has completed its task the formal parameters disappear and the values that they held are lost However the lifetime of a field is the same as the lifetime of the object to which it belongs 26 Assignment The assignment statement below means the parameter cost is assigned to the variable called price To make it easier to understand try reading it right to left The righthand side is called an expression price cost One rule about assignment statements is that the type of the expression on the righthand side must match the type of the variable to which it is assigned Exercise 221 Suppose that the class Pet had a field called name that is a type of String Write an assignment statement in the body of the following constructor so that the name field will be initialized with the value of the constructor39s parameter public PetString petsName Solution public PetString petsName name petsName Exercise 222 Challenge exercise The following object creation will result in the constructor of the Date class being called Can you write the constructor39s header new Date March 23 1861 Try to give meaningful names to the parameters Solution public Datestring month int day int year 27 Methods Methods have two parts a header and a body A method header always include a pair of parentheses and no semicolon at the end of the header The getPrice is an example of a method and is shown below public int getPrice The method body is the remainder of the method after the header and is always enclosed in a matching pair of curly brackets The method body contain the declarations and statements that define what an object instance does when that method is called Declarations are used to create additional temporary variable space while statements describe the actions of the method Any set of declarations and statements between a pair of matching curly brackets is known as a block Methods can have a return type whereas constructors may not have a return type The following statement is an example of a return type return price The return statement is responsible for returning an integer value to matching int return type in the methods header 28 Accessor and mutator methods Methods that are described as get methods are considered to be accessor methods This is because they return information to the caller about the state of an object An accessor method usually contains a return statement that allows the method to pass back that information Methods that change the state of their object are called mutator methods An example of a mutator method is shown below public void insertMoneyint amount balance balance amount As you can see the balance field value is changed by adding the amount to the current value of the balance field 29 Printing from methods When you invoke the printTicket method you should have seen something printed in the Blue terminal window This method contains the following statements Systemoutprintln Systemoutprintln The Blue Line Systemoutprintln Ticket Systemoutprintln price cents Systemoutprintln Systemoutprintln The code above shows that anything in the is a string output Looking at the fourth line of code shows price with the string output This allows the system to concatenate two strings together 213 Making choices the conditional statement Conditional statement takes one of two possible actions based upon the result of a test Conditional statements are also known as if statements The pseudo code below shows the layout of an if statement if perform some test that gives a true or false result Do the statements here is the test gave a true result else Do the statements here is the test gave a false result 216 Local variables A local variable is a variable declared and used within a single method lts scope and lifetime is limited to that of the method The following method shows a local variable public int refundBalance int amountToRefund amountToRefund balance balance 0 return amountToRefund The amountToRefund variable is a the local variable Notice that it looks similar to a field declaration but the word private or public is not part of a local variable Constructors can also have local variables 217 Fields parameters and local variables In this chapter we have learned about three different kinds of variables The following summarizes their features All three kinds of variables are able to store a value that is appropriate to their defined type For instance a defined type of int allows a variable to store an integer value Fields are defined outside constructors and methods Fields are used to store data that persist throughout the life of an object As such they maintain the current state of an object They have a lifetime that lasts as long as their object lasts Fields have class scope their accessibility extends throughout the whole class so they can be used within any of the constructors or methods of the class in which they are defined As long as they are defined as private fields cannot be accessed from anywhere outside of their defining class Formal parameters and local variables persist only for the period that a constructor or method executes Their lifetime is only as long as a single cell so their values are lost between calls As such they act as temporary rather than permanent storage locations Formal parameters are defined in the header of a constructor or method They receive their values from outside being initialized by the actual parameter values that form part of the constructor or method call Formal parameters have a scope that is limited to their defining constructor or method Local variables are defined inside the body of a constructor or method They can be initialized and used only within the body of their defining constructor or method Local variables must be initialized before they are used in an eXpression l Local variables have a scope that is limited to the block in which they are defined They cannot be accessed from anywhere outside of that bock 221 Calling Methods The following code illustrates calling a method on another object and using the value returned from method39s return result as part of an expression Public String getLoginName return namesubstring04 idsubstring03 The return statement returns the characters from index 0 to index 4 of the name field and the characters from index 0 to index 3 of the id field This is a subject that we will learn more about in the next chapter 223 Concept Summary 0 object creation Some objects cannot be constructed unless extra information is provided 0 field Fields store data for an object to use Fields are also known as instance variables 9 comment comments are inserted into the source code of a class to provide explanations to human readers They have no effect on the functionality of the class 0 constructor Constructors allow each object to be setup properly when it is first created 0 scope The scope of a variable defines the section of source code from which the variable can be accessed lifetime The lifetime of a variable describes how long the variable continues to exist before it is destroyed assignment assignment statements store the value represented by the righthand side of the statement in the variable name on the left accessor method Accessor methods return information about the state of an object mutator method Mutator methods change the state of an object println The method Systemoutprintln prints its parameter to the text terminal conditional A conditional statement takes one of two possible actions based upon the result of a test boolean expression Boolean expressions have only two possible values true and false They are commonly found controlling the choice between two paths through a conditional statement local variable A local variable is a variable declared and used within a single method lts scope and lifetime are limited to that of the method Keywords that you may want to remember field instance variable constructor method method header method body actual parameter formal parameter accessor mutator declaration initialization block return type comment expression operator variable local variable scope lifetime Exam Review for Exam 1 that will be on December 16 2015 for CSC 120 You will want to remember the following terms and their definitions field constructor parameter formal and actual methods accessor and mutator keywords or reserved words variable scope of a local variable lifetime of a local variable scope of a field lifetime of a field scope of a parameter lifetime of a parameter boolean expression conditional statement local variable comment OOOOOOOOOOOOOOOO You will want to make sure that you are stating the subject term in the beginning of the sentence then state a group or classification to which the subject belongs followed by a clause that qualifies the subject and differentiates it from other members of the group If you need further information about this please see the How to write a good definition handout on moodle I have included some Pseudocode to assist with recalling how to create Objects ClassesFields Constructors Methods Print Statements Variables and If Else Statements All addtional information that you need to know for the exam is explained in the handouts in moode Creating Objects ClassName objectname new ClassName Example Circle cicle1 new Circle Method Calling obectnamemethodparameter values parameter value ect note parameter values are only used if the method has parameters in the method header Example circle1draw circle1changeColor Blue Class Header public class ClassName Example public class TicketMatchine Fields omitted Fields private type fieldname Example private int price Constructors public ClassNameparameters if needed do something Example public TicketMachineint cost price cost balance 0 total 0 public Picture Methods Accessors and Mutators public type methodName Example Example of a accessor method public int getPrice return price Example of a mutator method public void insertMoneyint amount balance balance amount Print Statement Systemoutprintln somethingwewanttoprint Examples Example of a String Systemoutprintln Hellow World Example of stringcacatenation Systemoutprintln The sum of a b is c Conditional Statement ifperform some test that gives a true or false result Do something else Do something else Example ifamount gt 0 do something else print an error Local Variable public type method type variableName Example public int refundBalance int amountToRefund amountToRefund balance balance 0 return amountToRefund
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'