MIDTERM REVIEW. midterminformation.htm

Similar documents
Part (II): In the body method main : Write the call to method formatname and have the return value stored in the variable formatted.

CPSC 219 Extra review and solutions

Fundamentals of Programming Data Types & Methods

Introduction to Programming Using Java (98-388)

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Programming II (CS300)

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Introduction To Java Programming

Introduction To Java Programming

Introduction To Java Programming

We now start exploring some key elements of the Java programming language and ways of performing I/O

Object Oriented Programming. Java-Lecture 1

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

Introduction To Java Programming

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Introduction To Java Programming

AP Computer Science Unit 1. Programs

H212 Introduction to Software Systems Honors

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Programming with Java

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

Computational Expression

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

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

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

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

Lecture Set 2: Starting Java

OBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com

A+ Computer Science -

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lecture Set 2: Starting Java

Selected Questions from by Nageshwara Rao

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Lecture 7: Classes and Objects CS2301

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Chapter 4: Loops and Files

Object Oriented Programming

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

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

Computer Science II (20082) Week 1: Review and Inheritance

A variable is a name for a location in memory A variable must be declared

CMSC131. Introduction to your Introduction to Java. Why Java?

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Object Oriented Programming

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Chapter 4 Defining Classes I

Programming II (CS300)

Elementary Programming

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Java Identifiers, Data Types & Variables

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

Reading Input from Text File

Lecture 02, Fall 2018 Friday September 7

Chapter 2. Elementary Programming

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

University of Palestine. Mid Exam Total Grade: 100

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS 106 Introduction to Computer Science I

CS 201, Fall 2016 Sep 28th Exam 1

Assignment 1 due Monday at 11:59pm

Using Java Classes Fall 2018 Margaret Reid-Miller

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

Chapter 4: Loops and Files

Object-Oriented Programming in Java

Computer Science II (20073) Week 1: Review and Inheritance

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Midterm Exam CS 251, Intermediate Programming March 12, 2014

Operations. I Forgot 9/4/2016 COMPUTER SCIENCE DEPARTMENT PICNIC. If you forgot your IClicker, or your batteries fail during the exam

Classes. Classes as Code Libraries. Classes as Data Structures

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

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

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Full file at

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling

BM214E Object Oriented Programming Lecture 7

Midterms Save the Dates!

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

An overview of Java, Data types and variables

Midterm Examination (MTA)

Introduction To Object- Oriented Programming

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

CS 231 Data Structures and Algorithms, Fall 2016

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Chapter 6 Introduction to Defining Classes

Today s Agenda. Quick Review

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

EECS168 Exam 3 Review

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

COMP 202 Java in one week

COMP 110 Introduction to Programming. What did we discuss?

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.

Transcription:

MIDTERM REVIEW http://pages.cpsc.ucalgary.ca/~tamj/233/exams/ midterminformation.htm 1

REMINDER Midterm Time: 7:00pm - 8:15pm on Friday, Mar 1, 2013 Location: ST 148 Cover everything up to the last lecture before the reading week Review: Practice questions are available under the Midterm section on the course website Review slides Instructor s office hour: 1pm - 3pm in MS lab 2

INTRODUCTION TO JAVA Lecture 2-6 + sample code Tutorial 2-4 Quiz 1 Assignment 1 3

concept JAVA The program is compiled on one machine and can be run on any platform with the appropriate Java interpreter. bytecode Java interpreter Computer program e.g., Java program Java compiler (javac) bytecode bytecode 4

JAVA How does Java different from C++ and Python in terms of compilation and execution? (Hints: the two steps that you must perform to run your code.)

VARIABLE AND EXPRESSION What are the values of each variable after executing the following statements double num = 1.005e2; int x = 2; float y = (int) num * (float) x; int z = x++ * 3 - --x; System.out.println("x = " + ++x); System.out.println("y = " + y); System.out.println("z = " + z--);

concept SWITCH In C++/Java, the switch statement is an alternative to nested IF statement It produces simpler code for certain case. Format: switch (<name of the variable to be tested>) case <possible value>: body of this case break; case <possible value>: body of this case break;... default: body of the default case The variable can be of type byte, char, short, int, or long. The value must match the type of the variable for a valid comparison. The break is used to separate the cases. 7

SWITCH What are the values of each variable after executing the following statements int code = 416; switch (code) case 403: System.out.println("Calgary"); break; case 708: System.out.println("Edmonton"); break; case 416: System.out.println("Toronto"); break; case 604: System.out.println("Vancouver"); break; default: System.out.println("Unknown area code:" + code);

SWITCH What are the values of each variable after executing the following statements int code = 416; switch (code) case 403: System.out.println("Calgary"); case 708: System.out.println("Edmonton"); case 416: System.out.println("Toronto"); case 604: System.out.println("Vancouver"); default: System.out.println("Unknown area code:" + code);

SWITCH What are the values of each variable after executing the following statements int code = 416; switch (code) case 403: System.out.println("Calgary"); case 708: System.out.println("Edmonton"); break; case 416: System.out.println("Toronto"); case 604: System.out.println("Vancouver"); break; default: System.out.println("Unknown area code:" + code);

concept IF STATEMENTS IF statement Format: if (logical expression) body of if remainder of the program IF-ELSE statement Format: if (logical expression) body of if else body of else remainder of the program IF-ELSE-IF statement Format: if (logical expression) body of if else if (logical expression) body of else-if... else if (logical expression) body of else-if else body of else remainder of the program 11

IF STATEMENTS Re-write the following statement using the if-else-if construct int code = 416; switch (code) case 403: System.out.println("Calgary"); case 708: System.out.println("Edmonton"); break; case 416: System.out.println("Toronto"); case 604: System.out.println("Vancouver"); break; default: System.out.println("Unknown area code:" + code);

concept LOOPS while loop format initialization while (logical expression) body update control remainder of the program do-while loop format: initialization do body update control while (logical expression); remainder of the program for loop format: for (initialization; logical expression; update control) body remainder of the program 13

LOOPS How many times the loop body will be executed? int num = 100; int total = 0; int i = 0; do total = total + i; i++; while (i <= num); Re-write the above code segment using the for loop construct. Re-write the above code segment using the while loop construct. 14

concept JAVA I/O: INPUT Input from command-line: <type> <variable name> = args[0]; <type> <variable name> = args[1]; User input: import java.util.scanner;... Scanner <name of scanner> = new Scanner(System.in); <type> <variable name> = <name of scanner>.<method>();... Useful Scanner methods: nextint(); nextlong(); nextfloat(); nextdouble(); nextline(); Input from a file: import java.io.*;... String <filename> = args[0]; // Getting the file name from the command line FileReader <filereader> = new FileReader(<filename>); // Open the file for read BufferedReader <buffer> = new BufferedReader(<filereader>); // Initialize the buffer String line = null; // Read each line of the file do line = <buffer>.readline();... while (line!= null); // Checks for EOF 15

concept JAVA I/O: OUTPUT Format: System.out.print(<string or variable name> + <string or variable name> +..); OR System.out.println(<string or variable name> + <string or variable name> +..); An escape character (backslash \) is use to indicate that the character is part of the string rather than part of the instruction. Escape Meaning \\ Backslash (keeps \) \ Double quote (keeps ) \n Newline, end of line \t Horizontal tab...... Format Output // formatting integer output System.out.printf/format( %<field width>d, <int variable>); // formatting string output System.out.printf/format( %<field width>s, <String variable>); // formatting floating point output System.out.printf/format( %<field width>.<precision>f, <float/double variable>); 16

Try to print: I said, "Don't do it" JAVA I/O

OOP: CLASSES AND INFO ENCAPSULATION Lecture 7-14 + sample code Tutorial 5-7 Quiz 2 Assignment 2 18

concept CLASSES A class is an abstract data type (ADT) that consists of attributes (fields) and methods (functions) that operate on the data. Format: public class <name of the class> instance fields/attributes (fields) instance methods An object (instance) is a variable of a class, and the declaration is called instantiation. Format: <class name> <object name> = new <class name> (); Encapsulation: information hiding Accessor methods Mutator methods (e.g., get method) (e.g., set method) public methods Private members public methods 19 Public members

concept MEMBERS Members: Data members: Methods: Accessing members A private members can only accessed by class methods (within the class) Accessing data members: Access methods: this.<name> this.<method name> (arg1, arg2,...); A public data member can be accessed by the object and class methods (both within and outside the class) Accessing data members: <object name>.<name> // outside the class Access methods: <access modifier> <type> <name>; this.<name> public or private, but typically private <access modifier> <return type> <method name> (<type> <param1>, <type> <param2>,...) <Body of the method> <object name>.<method name> (arg1, arg2,...); // within the class // outside the class this.<method name> (arg1, arg2,...); 20 // within the class

CLASSES Complete the code as instructed by the comments in formatname() and main(). public class MyFormatter private String first; private String last; private Scanner in; public MyFormatter () first = null; last = null; in = new Scanner(System.in); public void promptnames () System.out.print("Enter first name: "); first = in.nextline(); System.out.print("Enter last name: "); last = in.nextline(); public String formatname () String name; // Call promptnames() // Name format: <last><tab><first> return name; public class Driver public static void main (String [] args) MyFormatter aformatter = new MyFormatter(); String formatted; // call formatname() and store results in formatted System.out.println(formatted); 21

INFORMATION HIDING Write an accessor/get and mutator/set method for the following class definition. public class Student private int identificationnumber; public Student () identificationnumber = -1; // Accessor // Mutator 22

concept SCOPE class definition Attributes: variables or constants declared inside the body of a class definition, but outside the body of any class method Local variables: variables or constants declared within the body of a class method In general, the scope of a variable, constant, or method is the inner-most block where it is originally declared, starting from the declaration public class <class name> // Attributes attributes: declared inside a class definition, but outside the body of any method // Methods <access modifier> <return type> <method name> (<type> <param1>, <type> <param2>,..) while (<condition>)... if (<condition>)... body of a method else... <access modifier> <return type> <method name> (<type> <param1>, <type> <param2>,..)... body of a method 23

SCOPE OF ATTRIBUTES AND LOCAL VARIABLES Identify the body of a class definition, the body of a method, attributes, and local variables For each attribute and local variable, identify its scope. 1 public class Car 2 3 public String model; 4 private int odometer; 5 public void addtoodometer(int city, int road) 6 7 odometer += city + road; 8 9 private String plate; 10 public void setplate(string plate) 11 12 plate = plate; 13 14 24

concept CONSTRUCTOR & METHOD OVERLOAD A constructor is a special method that: has the same name as the class itself is invoked when creating the object (e.g., Student alice = new Student()) can be redefined by the programmers (e.g., you can specify how you want to initialize each data member) Format: default constructor (provided by the language by default) public <class name> (<type> <param1>, <type> <param2>,...) // body of the constructor Overload methods are the methods with the same method name, but different method signature (the list of parameters) Commonly shared by methods with similar implementation for different tasks 25

METHOD OVERLOAD Assuming the following methods are already included in the same class definition: public double method() public void method(int) Identify invalid method overload: public void method() public int method() private void method() public int method(int, int) public int method(int) 26

concept SELF REFERENCE For every (non-static) method of an object, there exists a reference to the object itself (keyword this) this(): invoke the constructor of a class It is usually used when overloading the constructor. Example: public Student () firstname = ""; this.firstname = ""; lastname = ""; studentid = 0; grade1 = 0.0; grade2 = 0.0; public Student (String firstname, String last) this(); firstname = firstname; this.firstname = firstname; lastname = last; public Student (String first, String last, int id) this(first, last); studentid = id; 27 equivalent not the same (shadowing)

SELF REFERENCE & METHOD OVERLOAD What is the output of the following program? public class Tracer private int x; private int y; public Tracer() x = 7; y = 13; public Tracer(int x, int y) this(); this.x = x; y = y * 2; public void display() System.out.println(x + " " + y); public void method() int x = 2; x = x * 10; y = x + y; public void method(int a) x = a; y = this.y * 2; public class Driver public static void main(string [] args) Tracer atracer = new Tracer(); atracer.display(); atracer = new Tracer(888,666); atracer.display(); atracer.method(); atracer.display(); atracer.method(707); atracer.display(); 28

ARRAYS Lectures 15-17 + sample code Tutorials 8 29

concept OPERATIONS: CREATE Declaration: creating only a reference to the array. Format: <type>[] <array name>; Allocation: allocate a contiguous memory space Format: <array name> = new <type> [<# of elements>]; Access: an array is really a list of indexed elements Format: <array name> [index] Modify: modifying array elements Format: <array name> [index] =...; Common operations: initialization, adding, removing, searching, and displaying They all share the general loop construct <type>[] <array name> = new <type> [<# of elements>]; int next = 0; // to keep track of the next free space in the array... for (int i = 0; i < arr.length; i++) // accessing or modifying individual elements // and algorithms for different operations. or next, depending on the algorithm 30

public class Manager public final static int MAX = 10; public static final int EMPTY = -1; private int [] salaries; private int lastelement; // Note this is the lastelement, not next public Manager () lastelement = EMPTY; salaries = new int [MAX]; for (int i = 0; i < MAX; i++) salaries[i] = EMPTY; public boolean isempty () if (lastelement <= EMPTY) return true; else return false; public boolean isfull () if ((lastelement+1) == MAX) return true; else return false; public void display () for (int i = 0; i <= lastelement; i++) System.out.println(salaries[i]); System.out.println(""); // Adds new elements to the end of the list. public void add (int asalary) lastelement++; if (isfull() == false) salaries[lastelement] = asalary; else System.out.println("Can't add: list is already full"); // Returns index of first matching salary or EMPTY if no matches. private int indexat (int asalary)... return index; // Use indexat() to find the matching salary, and then remove it public void remove (int asalary)... 31

concept ARRAYS OF OBJECTS Declaration + allocation format: <class name>[] <array name> = new <class name>[# of objects]; Each element in the array is a reference. By default, all references are set to null. Access an array element: Initialization format: <array name>[index] for (int i = 0; i < <array name>.length; i++) <array name>[i] = new <class name>(...); <addr. of obj.> <addr. of obj.>...... <addr. of obj.> <actual object> <actual object> <actual object>... 32

ARRAYS OF OBJECTS Modify the code in main() so that an array of SIZE Car objects is created. Set the price of each car as follows: 10000, 20000, 30000,... (the price is increased by 10000 from one car to the next in the array) Display the attributes of each car object, one car per line with the format: <model information> <price> public class Car private String model; private int price; public Car () setmodel("no name"); setprice(-1); public String getmodel () return model; public int getprice () return price; public void setmodel (String amodel) model = amodel; public void setprice (int aprice) price = aprice; public class Start public static void main(string [] args) final int SIZE = 10; int i; Car[] mycollections; 33