CS 1302 Chapter 9 (Review) Object & Classes

Size: px
Start display at page:

Download "CS 1302 Chapter 9 (Review) Object & Classes"

Transcription

1 CS 1302 Chapter 9 (Review) Object & Classes Reference Sections , Defining Classes for Objects 1. A class is a blueprint (or template) for creating objects. A class defines the state (the current conditions) and behavior (the things it can do) that objects have. State is implemented with instance variables (also called data field, field, property, attribute) Behavior (also called services, responsibilities) is implemented with methods. 2. The Unified Modelling Language (UML) is a standardized graphical language for modelling object-oriented software. UML is composed of a number of different diagrams, however we will only consider class, object, and package diagrams. 3. A UML class diagram is used to model the classes in a system. As shown above on the right, a class diagram has three compartments: the top box shows the name of the class, the middle box shows the state and the bottom box shows the behaviors. On the right, we show the complete notation used for a class diagram. Notice that the notation is a little bit different than Java because UML is for any object-oriented language. For example: Methods are shown as: method(paramname : datatype) : returntype Instance variables has this format varname : datatype We will discuss the dependency arrow later. 1

2 4. We can show a class in various degrees of detail as shown below, depending on the stage of modeling. When you first start to analyze a problem, you may only be concerned with documenting the classes. Later, you may add state and behavior. Finally, you may assign visibility, parameters, datatypes, and return types. 5. A UML object diagram shows an example of objects that might exist in a system when it is running. For example, the object diagram on the right shows that we have a dog reference variable of type Dog and that this dog has a name of Spot. The full notation is shown below Example 1. A class is need to represent a box. A box has a length, width, and height which are supplied when the box is first created. The length, width, and height cannot be directly changed except through setters (mutators). They can also be retrieved. A box has a method that can calculate the volume. It also has a method that accepts a length, width, and height of a product that it might contain. The method should return true if the product will fit in the box and false otherwise. a. Draw a class diagram to represent the box. b. Draw an object diagram that shows a box. c. Write the box class. d. Write a main to test the class. 2

3 Homework: 1. A class is needed to represent a savings account. Savings accounts have an owner and a balance which are initialized when the account is first created. The owner can never be changed, however the owner can be retrieved. The balance can be retrieved also. The balance cannot be changed directly except through deposit and withdrawal actions which accept an amount of money, which must be positive. A deposit increases the balance by the amount of money that is passed in and a withdrawal decreases the balance by the amount of money that is passed in. A withdrawal should not be executed if it would decrease the balance below zero. In addition this class has a method that accepts an interest rate in decimal form, which must be positive and increases the balance by this rate. a. Draw a class diagram for this class. b. Draw an object diagram that shows a savings account. c. Draw an object diagram that shows a savings account with a name and balance. d. Write this class. e. Write a main to test this class. 2. The default value for data fields: reference type is null, numeric is 0, and boolean is false. There is no default value for local variables. 3. When we create an object we usually assign it to a variable. This type of variable is called a reference type and the variable is called a reference type variable. For example: 4. A reference type variable is not the actual object (although we frequently refer to it as the object). It really is a pointer to a location in memory where the actual object resides. This is shown in the table below on the left. first row of the table on the left, below. As shown in the second row, when assign a new reference variable (b2) to an existing one (b1), we create another reference to the same box. Thus, if we use that new reference (b2) to change the box, the original reference (b1) reflects this change (because they both refer to the same box) as shown in the third row of of the table. Reference Types Primitive Types Code Memory Code Memory Box b1 = new Box(4,6,2); int x = 3; Box b2 = b1 int y = x; b2.length = 6; y = 5; 3

4 The primitive data types in Java are: byte, short, int, long, float, double, boolean, char. All other types are reference types. Use of the assignment operator with primitives works differently as shown in the figure on the right, above. Homework: 2. Consider the three lines of code below. Draw an object diagram showing what is in memory after each line is executed. Thus, there will be three diagrams. Box b1 = new Box(2.0,3.0,4.0); Box b2 = new Box(1.0,5.0,3.0); b1=b2; 9.7 Static Variables & Methods 1. A static variable is shared by all instances of a class. We use the class name to reference a static variable. For example: Math.E or Math.PI 2. A static method is shared by all instances of a class, thus, it cannot depend on on the values of instance variables for a particular object. For example, the String class defines methods like substring and indexof which operate on a particular instance of a string. The String class also defines the static method, valueof that turns an integer (or double, Boolean, etc) into a string. We use the class name to reference a static method. For example: 3. We don t use static variables and methods very often in domain classes. For instance, the Box and SavingsAccount classes we have defined earlier would not need either. As far as this class goes you will never need to define your own static variables or methods. The one exception is when we write driver classes to test our code we frequently use static methods. For example: public class BoxDriver { public static void main(string[] args) { boxtest1(); public static void boxtest1() { Box b = new Box(2,3,4); System.out.println(b.volume()); b.setlength(10.5); System.out.println(b.volume()); 4

5 When we call a static method from the class where it is defined we do not have to precede the call with the class name as shown above. 9.8 Visibility 1. A package is a way to group related classes. The UML package diagram shown on the right shows a package named warehouse_stuff which contains three classes: Box, PackingTape, and PackingPeanuts. A package not only provides a way to organize classes, it also provides protection as we will see below. 2. We declare a package with a package statement as the first line in a file. By convention, package names are all lower-case with an underscore separating words. For example: Box.java PackingTape.java PackingPeanuts.java package warehouse_stuff; package warehouse_stuff; package warehouse_stuff; public class Box {... public class PackingTape {... public class PackingPeanuts {... All classes in a package must be inside a folder with the same name as that of the package. 3. Example Suppose we have a class A in package pack1 and a class B in package pack2 as shown in the figure on the right. If class A needs to use class B, then it must import it as shown below. A.java package pack1; import pack2.b; B.java package pack2; public class B { public class A { public static void main(... ) { B b = new B(); You can import all classes in a package with, for example: import pack.*; however, by convention, it is recommended that you only import the specific class(es) you need. 4. There are 2 visibility (accessibility) modifiers for classes: UML Java Example Meaning + public public class Box {... The class is available in any package [blank] [blank] class Box {... The class is available only in containing package 5

6 5. There are 4 visibility modifiers for members (methods and instance variables) in a class. In order of most to least visible, they are: UML Java Meaning + public Available in any class # protected [We learn about this in Ch 11] [blank] [blank] Available in any class in the same package - private Available only in the class (and not in subclasses). 6. Classes and methods can access classes and methods in other packages if they are imported and if the accessibility allows it. For example, consider the packages and classes shown in the UML diagram on the right and note the following: Class A can access class C because C is public. It can also access class B because it is in the same package. Class B can access classes A and C. Class C can access class A, but not B because class B has package-level accessibility. Methods in C can access the x method in A, but not they y method because it is private, and not z because it has package-level accessibility. 7. We can also define subpackages. For example: package pack1.subpack; public class A {... In this case, class A would be defined in a subpack folder and the subpack folder would be inside the pack1 folder. For a class in another package to access class A, you need to import the package and subpackage. For example: package another_package; import pack1.subpack.a;... 6

7 9.9 Data Encapsulation 1. In general we want to encapsulate the state of a class. What this means is that we do not want to allow a client (another class using your class) to directly change the values of instance variables. To make the data in a class encapsulated, we make all instance variables private and provide getters and setters as shown in the figure below. Not Encapsulated public class Box { public double length;... Box b = new Box(2,4,6); b.length = 10; Encapsulated public class Box { private double length; public void setlength(double length) { if( length > 0 ) this.length = length; public double getlength() { return length;... Box b = new Box(2,4,6); b.setlength(10); 2. You may say, what s the big deal? Why do I have to do all this extra work? Real systems are composed of many classes written by different teams and developers. Your classes may be used by other developers and vice versa. If your Box class is not encapsulated, you may know not to assign a negative value to the length, but others using your class may not know that. It is better to practice defensive programming, to take steps to make sure others use your classes correctly. One way to do this is to protect (encapsulate) the state of your classes. In addition to inadvertent misuse of a class, encapsulation also protects against deliberate misuse of a class. For example, you wouldn t define a BankAccount class with a public balance method because then clients could change the balance to any value they wanted. Instead, you would define a deposit method which logs the amount of the deposit in a database and updates the private balance. As an analogy, when you go to the store to purchase something and the cashier says, $10 please, you could just hand your wallet to the cashier in which case your wallet would be public: public class You { public double wallet; But of course, your wallet is private! public class You { private double wallet; public void paycashier(double amount) { // take money out of wallet and hand to cashier 7

8 3. When we want a property to be read-only (i.e. we allow a client to retrieve the value of a property, but not change it) we simply omit the setter. Homework: 3. Draw a class diagram for an encapsulated employee class that has a name and hourly pay rate and has a method that accepts the number of hours worked and returns the pay. The name is read-only. Also, write the code for this class Passing Objects to Methods 1. All variables in Java are passed by value. This means that when you pass an argument to a method, the method receives a copy of the argument. In the case of a reference variable, a copy of the pointer to the object is passed. 2. Consider the method on the right and what happens in memory when the code is executed as shown below. The calling method defines a box reference and when it is passed to the method, a local copy is made, b for use public static void shrinkbox( Box b ) { b.setlength( b.getlength()-1 ); inside the method. We use the local reference to manipulate the box. When the method finishes and control returns to the calling program, the reference b is no longer available (it is garbage collected), and we continue to use the box reference. 8

9 3. As another example is shown on the right. This method creates a new box, but as we see (below), it is short lived, when we return to the calling program, the original reference, box public static void changebox( Box b ) { b = new Box(9,9,9); Homework: 4. Modify the SavingsAccount class from homework problem 1 so that it has a method, mergeaccount that accepts another SavingsAccount object. This method should add the balance of this instance to the balance of the calling object if the two accountowners are the same. Write a main to test the class. 9

10 9.11 Array of Objects 1. Frequently, we say things like, we need an array of Boxes. Technically, the array of Boxes is really an array of references to Box objects. Below, boxes is a reference to an array that resides in memory. The array itself contains references to Box objects that reside elsewhere in memory. Box[] boxes = new Box[3]; boxes[0] = new Box(4,4,4); boxes[1] = new Box(9,9,9); boxes[2] = new Box(6,6,6); 2. Next we consider the case where we have two references to the same array and we use one reference to change an element in the array. As we saw earlier (in a different context), both references reflect the change as (of course) they are both pointing to the same array. Example (continued from above): 10

11 Homework: 5. Write a class, SavingsAccountTester with the following static methods: a. totalbalance accepts an array of SavingsAccount objects and returns the sum of the balance in each object. b. applyinterest accepts an array of SavingsAccount objects and an interest rate and applies this interest rate to all the objects. c. accountsreport accepts an array of SavingsAccount objects and returns a formatted string showing the name and balance of each account, one per line. The format should be like this: Gibson, $12, Watson, $6, Write a main to test the class Immutability 1. Sometimes it is useful to define a Class that doesn t allow the state to be changed. In other words, the state is set when the object is created, but can never be changed after that. Such a class (object) is called immutable. 2. Example This box class is immutable: public class ImmutableBox { private double length, width, height; public double getlength() { return length; public double getwidth() { return width; public double getheight() { return height; public ImmutableBox( double l, double w, double h ) { length = l; width = w; height = h; public double volume() { return public String tostring() {... 11

12 3. Example This student class is not immutable. The getscores method returns the array of scores, which is a reference variable. Thus, scores can be changed. public class Student { private String name; private int[] scores; private double average=0.0; public static void main(string[] args) { public Student(String name, int[] scores) { this.name = name; this.scores = scores; for(int score : scores) { average += score; average /= scores.length; public String getname() { return name; public int[] getscores() { return scores; public double getaverage() { return average; 4. Thus, the requirements for a class to be immutable are: All instance variables must be private. There are no setters (or other methods) that change the values of instance variables. No methods can return a reference to an instance variable that is a mutable reference type. 4. The String class is immutable. This means that a String can never be changed. When you change a string a new String is created and assigned to the reference as shown in the figure on the right. Code String s = "dog"; s += " and cat"; Memory 5. This means that we need to be aware that a String (unlike most objects) cannot be changed in a method. Consider the method shown on the right. Then, consider what happens in memory as the code is executed: public static void doesntchangestring(string str){ str += " and cat"; 12

13 Code Memory String s = "dog"; doesntchangestring(s); // Inside doesntchangestring() str += " and cat"; // Back in main If we did want to change a string, we could have the method return the changed string as shown on the right and the explanation of what is happening in memory as the code executes shown below: Code public static String changestring(string str){ str += " and cat"; return str; Memory String s = "dog"; s = changestring(s); // Inside changestring() str += " and cat"; return str; // Just after return 9.13 Scope of Variables 1. Read and understand 13

14 9.14 this 1. The this keyword is use to reference an item inside the object itself. It is sort of like using the pronoun my (my arm, my wallet, etc). 2. There are two common ways to use this, as the example below shows: We can use this to call another constructor in the same class. It must be the first line of the constructor. We can use this to differentiate between an instance variable and a parameter with the same name. Homework: 6. Modify the SavingsAccount class so that it has the following constructors: a. SavingsAccount() initializes the object to have a balance of 0 and an account owner, unknown. b. SavingsAccount(double initialbalance) initializes the object to have a balance of initialbalance and an account owner, unknown. c. SavingsAccount(String owner) initializes the object to have a balance of 0 and an account owner, accountowner. The constructor below already exists. The three above should call this constructor. SavingsAccount(String owner, double initialbalance) initializes the object to have a balance of initialbalance and an account owner, accountowner. 14

15 Miscellaneous Review Material 1. Java defines the % binary operator which provides the remainder when the two operands are divided. Some examples are shown on the right. Notice that x%y yields a value in the range: {0,1,2,, y 1. This can be useful as we show shortly. The % operator is also called the remainder operator and the modulus operator. Consider x%y, we typically speak this by saying, x mod y. 2. A problem that occurs regularly is determining if a number is odd or even. A useful trick is to take the number and mod it by 2. If the result is 0 then the number is even, otherwise it is odd. For example: int val = (int)(math.random()*1000); if(val%2==0) { // val is even else if(val%2==1) { // val is odd 0 % 5 = 0 1 % 5 = 1 2 % 5 = 2 3 % 5 = 3 4 % 5 = 4 5 % 5 = 0 6 % 5 = 1 7 % 5 = 2 8 % 5 = 3 9 % 5 = 4 10 % 5 = 0 0 % 8 = 0 1 % 8 = 1 2 % 8 = 2 3 % 8 = 3 4 % 8 = 4 5 % 8 = 5 6 % 8 = 6 7 % 8 = 7 8 % 8 = 0 9 % 8 = 1 10 % 8 = 2 3. Mod and integer division are useful together sometimes. For example, how do you translate seconds into minutes and seconds? int time = 143; int minutes = time/60; int seconds = time%60; 4. Example Suppose you have an array of integers, vals. Write a snippet of code to print the values 4 per line. Solution: Suppose that there are 14 values in the array. Then, The number of complete lines (rows) is: 14/4 = 3 The number of values in the last (incomplete) line (row) is: 14%4 = 2 15

16 Example 1. A dog has a name (which can t be changed) and a toughness (integer) that are initialized when the dog is first created. However, a dog can be created with just a name, in which case the toughness is set to 1. A dog can walk. When it walks it returns a message like this: dogname is walking. A dog can also bark by returning a message like: dogname is barking. A dog can also bark at another dog by returning a message like: dogname is barking at otherdogname. a. Model this situation with a class diagram. b. Write the code for this class. c. Write some code to test the class. d. Write a static method that accepts an array of dogs and has them all walk printing the results. e. Write a static method that accepts an array of dogs and has the first dog bark at all the other dogs printing the results. f. Write a static method that accepts an array of dogs and returns the dog that is the toughest (highest toughness). g. Write a static method that accepts an array of dogs and returns a new array that holds every other dog. For example, if the input is 5 dogs, then an array will be returned with the first, third, and fifth dogs. Or, if the input is 4 dogs, then it will return an array with the first and third dogs. h. Suppose you use the array returned in g to change the toughness of the first dog. Then, you print the toughness of the first dog in the array that was the input to g. What will this toughness be? i. Modify the classes to handle this situation: A dog can fight another dog. The one with the highest toughness wins. Dogs need to keep track of how many fights they have been in and how many they have won. 16

Chapter 7 Classes & Objects, Part B

Chapter 7 Classes & Objects, Part B Chapter 7 Classes & Objects, Part B These note present Dog simulation example that shows how we go about OO modeling. A number of new things are introduced. They also present the Person > BirthDate example.

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM This handout explains what you have to know for the first prelim. Terms and their meaning Below, we summarize the terms you should

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

ECOM 2324 COMPUTER PROGRAMMING II

ECOM 2324 COMPUTER PROGRAMMING II ECOM 2324 COMPUTER PROGRAMMING II Object Oriented Programming with JAVA Instructor: Ruba A. Salamh Islamic University of Gaza 2 CHAPTER 9 OBJECTS AND CLASSES Motivations 3 After learning the preceding

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

CMSC131. Creating a Datatype Class Continued Exploration of Memory Model. Reminders

CMSC131. Creating a Datatype Class Continued Exploration of Memory Model. Reminders CMSC131 Creating a Datatype Class Continued Exploration of Memory Model Reminders The name of the source code file needs to match the name of the class. The name of the constructor(s) need(s) to match

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information

VARIABLES AND TYPES CITS1001

VARIABLES AND TYPES CITS1001 VARIABLES AND TYPES CITS1001 Scope of this lecture Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Primitive types Every piece of data

More information

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types. Class #07: Java Primitives Software Design I (CS 120): M. Allen, 13 Sep. 2018 Two Types of Types So far, we have mainly been dealing with objects, like DrawingGizmo, Window, Triangle, that are: 1. Specified

More information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

More information

Chapter 3 Classes. Activity The class as a file drawer of methods. Activity Referencing static methods

Chapter 3 Classes. Activity The class as a file drawer of methods. Activity Referencing static methods Chapter 3 Classes Lesson page 3-1. Classes Activity 3-1-1 The class as a file drawer of methods Question 1. The form of a class definition is: public class {

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Anatomy of a Class Encapsulation Anatomy of a Method

Anatomy of a Class Encapsulation Anatomy of a Method Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

1. Which of the following is the correct expression of character 4? a. 4 b. 4 c. '\0004' d. '4' Practice questions: 1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4' 2. Will System.out.println((char)4) display 4? a. Yes b. No 3. The expression "Java

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

Basic Object-Oriented Concepts. 5-Oct-17

Basic Object-Oriented Concepts. 5-Oct-17 Basic Object-Oriented Concepts 5-Oct-17 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions, which could manipulate any data An object contains

More information

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators Course Name: Advanced Java Lecture 2 Topics to be covered Variables Operators Variables -Introduction A variables can be considered as a name given to the location in memory where values are stored. One

More information

Computer Science II Data Structures

Computer Science II Data Structures Computer Science II Data Structures Instructor Sukumar Ghosh 201P Maclean Hall Office hours: 10:30 AM 12:00 PM Mondays and Fridays Course Webpage homepage.cs.uiowa.edu/~ghosh/2116.html Course Syllabus

More information

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Basic Operations jgrasp debugger Writing Programs & Checkstyle Basic Operations jgrasp debugger Writing Programs & Checkstyle Suppose you wanted to write a computer game to play "Rock, Paper, Scissors". How many combinations are there? Is there a tricky way to represent

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT Object Oriented Programming Examiner s Report March 2017 A1. a) Explain what is meant by the following terms:

More information

CT 229 Fundamentals of Java Syntax

CT 229 Fundamentals of Java Syntax CT 229 Fundamentals of Java Syntax 19/09/2006 CT229 New Lab Assignment Monday 18 th Sept -> New Lab Assignment on CT 229 Website Two Weeks for Completion Due Date is Oct 1 st Assignment Submission is online

More information

System.out.print(); Scanner.nextLine(); String.compareTo();

System.out.print(); Scanner.nextLine(); String.compareTo(); System.out.print(); Scanner.nextLine(); String.compareTo(); Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 6 A First Look at Classes Chapter Topics 6.1 Objects and

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Encapsulation. Mason Vail Boise State University Computer Science

Encapsulation. Mason Vail Boise State University Computer Science Encapsulation Mason Vail Boise State University Computer Science Pillars of Object-Oriented Programming Encapsulation Inheritance Polymorphism Abstraction (sometimes) Object Identity Data (variables) make

More information

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal APCS A Midterm Review You will have a copy of the one page Java Quick Reference sheet. This is the same reference that will be available to you when you take the AP Computer Science exam. 1. n bits can

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

CS112 Lecture: Defining Instantiable Classes

CS112 Lecture: Defining Instantiable Classes CS112 Lecture: Defining Instantiable Classes Last revised 2/3/05 Objectives: 1. To describe the process of defining an instantiable class 2. To discuss public and private visibility modifiers. Materials:

More information

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on

More information

c) And last but not least, there are javadoc comments. See Weiss.

c) And last but not least, there are javadoc comments. See Weiss. CSCI 151 Spring 2010 Java Bootcamp The following notes are meant to be a quick refresher on Java. It is not meant to be a means on its own to learn Java. For that you would need a lot more detail (for

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Exam Duration: 2hrs and 30min Software Design

Exam Duration: 2hrs and 30min Software Design Exam Duration: 2hrs and 30min. 433-254 Software Design Section A Multiple Choice (This sample paper has less questions than the exam paper The exam paper will have 25 Multiple Choice questions.) 1. Which

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 5 Modified by James O Reilly Class and Method Definitions OOP- Object Oriented Programming Big Ideas: Group data and related functions (methods) into Objects (Encapsulation)

More information

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader Prelim 1 Solutions CS 2110, March 10, 2015, 5:30 PM 1 2 3 4 5 Total Question True False Short Answer Recursion Object Oriented Loop Invariants Max 20 15 20 25 20 100 Score Grader The exam is closed book

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

More information

CSCI 355 LAB #2 Spring 2004

CSCI 355 LAB #2 Spring 2004 CSCI 355 LAB #2 Spring 2004 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016

CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016 Name: USC NetID (e.g., ttrojan): CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016 There are 7 problems on the exam, with 50 points total available. There are 8 pages to the exam (4 pages double-sided),

More information

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while CSCI 150 Fall 2007 Java Syntax The following notes are meant to be a quick cheat sheet for Java. It is not meant to be a means on its own to learn Java or this course. For that you should look at your

More information

Quarter 1 Practice Exam

Quarter 1 Practice Exam University of Chicago Laboratory Schools Advanced Placement Computer Science Quarter 1 Practice Exam Baker Franke 2005 APCS - 12/10/08 :: 1 of 8 1.) (10 percent) Write a segment of code that will produce

More information

CS 113 MIDTERM EXAM 2 SPRING 2013

CS 113 MIDTERM EXAM 2 SPRING 2013 CS 113 MIDTERM EXAM 2 SPRING 2013 There are 18 questions on this test. The value of each question is: 1-15 multiple choice (3 pts) 17 coding problem (15 pts) 16, 18 coding problems (20 pts) You may get

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

STUDENT LESSON A5 Designing and Using Classes

STUDENT LESSON A5 Designing and Using Classes STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

CPS122 Lecture: From Python to Java

CPS122 Lecture: From Python to Java Objectives: CPS122 Lecture: From Python to Java last revised January 7, 2013 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

PIC 20A The Basics of Java

PIC 20A The Basics of Java PIC 20A The Basics of Java Ernest Ryu UCLA Mathematics Last edited: November 1, 2017 Outline Variables Control structures classes Compilation final and static modifiers Arrays Examples: String, Math, and

More information

9 Working with the Java Class Library

9 Working with the Java Class Library 9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a

More information

CS18000: Problem Solving And Object-Oriented Programming

CS18000: Problem Solving And Object-Oriented Programming CS18000: Problem Solving And Object-Oriented Programming Class (and Program) Structure 31 January 2011 Prof. Chris Clifton Classes and Objects Set of real or virtual objects Represent Template in Java

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

Java Foundations Certified Junior Associate

Java Foundations Certified Junior Associate Java Foundations Certified Junior Associate 习题 1. When the program runs normally (when not in debug mode), which statement is true about breakpoints? Breakpoints will stop program execution at the last

More information

Defensive Programming

Defensive Programming Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 211: Methods, Memory, Equality

CS 211: Methods, Memory, Equality CS 211: Methods, Memory, Equality Chris Kauffman Week 2-1 So far... Comments Statements/Expressions Variable Types little types, what about Big types? Assignment Basic Output (Input?) Conditionals (if-else)

More information

Notes on Chapter Three

Notes on Chapter Three Notes on Chapter Three Methods 1. A Method is a named block of code that can be executed by using the method name. When the code in the method has completed it will return to the place it was called in

More information

COMP 401 Spring 2013 Midterm 1

COMP 401 Spring 2013 Midterm 1 COMP 401 Spring 2013 Midterm 1 I have not received nor given any unauthorized assistance in completing this exam. Signature: Name: PID: Please be sure to put your PID at the top of each page. This page

More information

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course : Advanced Java Concepts + Additional Questions from Earlier Parts of the Course 1. Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... In what order

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

COE318 Lecture Notes Week 4 (Sept 26, 2011)

COE318 Lecture Notes Week 4 (Sept 26, 2011) COE318 Software Systems Lecture Notes: Week 4 1 of 11 COE318 Lecture Notes Week 4 (Sept 26, 2011) Topics Announcements Data types (cont.) Pass by value Arrays The + operator Strings Stack and Heap details

More information

CS 2340 Objects and Design - Scala

CS 2340 Objects and Design - Scala CS 2340 Objects and Design - Scala Objects and Operators Christopher Simpkins chris.simpkins@gatech.edu Chris Simpkins (Georgia Tech) CS 2340 Objects and Design - Scala Objects and Operators 1 / 13 Classes

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Datatypes, Variables, and Operations

Datatypes, Variables, and Operations Datatypes, Variables, and Operations 1 Primitive Type Classification 2 Numerical Data Types Name Range Storage Size byte 2 7 to 2 7 1 (-128 to 127) 8-bit signed short 2 15 to 2 15 1 (-32768 to 32767) 16-bit

More information

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness. Methods There s a method in my madness. Sect. 3.3, 8.2 1 Example Class: Car How Cars are Described Make Model Year Color Owner Location Mileage Actions that can be applied to cars Create a new car Transfer

More information

CS 121 Intro to Programming:Java - Lecture 7 Professor Robert Moll (+ TAs) CS BLDG 276-545-4315 moll@cs.umass.edu course web page below http://twiki-edlab.cs.umass.edu/bin/view/moll121/webhome Announcements

More information

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes 1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist

More information

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating

More information

BM214E Object Oriented Programming Lecture 8

BM214E Object Oriented Programming Lecture 8 BM214E Object Oriented Programming Lecture 8 Instance vs. Class Declarations Instance vs. Class Declarations Don t be fooled. Just because a variable might be declared as a field within a class that does

More information

CS 61B Discussion 5: Inheritance II Fall 2014

CS 61B Discussion 5: Inheritance II Fall 2014 CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation

More information