PeerWise Study. Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Constants Using Classes and Objects

Similar documents
Using Classes and Objects. Lecture 7. Midterms Save the Dates! Extra Credit Survey

Midterms Save the Dates!

Midterms Save the Dates!

Midterms Save the Dates!

Midterms Save the Dates!

Midterms Save the Dates!

Midterms Save the Dates!

Midterms Save the Dates!

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Midterms Save the Dates!

Midterms Save the Dates!

! Rest of Chap 2 ! 2.3-4, ! Rest of Chap 4 ! ! Things that do not vary. ! unlike variables. ! will never change. !

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Fall 2017 CISC124 9/16/2017

Survey #2. Assignment #3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings. Static Interface Types.

Survey #2. Teen Talk Barbie TM Reloaded. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Partially Filled Arrays ArrayLists

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Survey #2. Variable Scope. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings. Scope Static.

Full file at

Introduction to the course and basic programming concepts

Survey #2. Programming Assignment 3. Final Exam. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

Survey #2. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Expressions and Casting

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

CEN 414 Java Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

printf( Please enter another number: ); scanf( %d, &num2);

Announcements. 1. Forms to return today after class:

COMP Primitive and Class Types. Yi Hong May 14, 2015

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

CMPT 125: Lecture 3 Data and Expressions

Programming with Java

CS 231 Data Structures and Algorithms, Fall 2016

Tutorials. Tutorial every Friday at 11:30 AM in Toldo 204 * discuss the next lab assignment

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

Chapter 1. Introduction to Computers and Programming. M hiwa ahmad aziz

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

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

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CS 251 Intermediate Programming Java Basics

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Java Fall 2018 Margaret Reid-Miller

Topic 4 Expressions and variables

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CIS 110: Introduction to Computer Programming

! This week: Chapter 6 all ( ) ! Formal parameter: in declaration of class. ! Actual parameter: passed in when method is called

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COSC 243. Data Representation 3. Lecture 3 - Data Representation 3 1. COSC 243 (Computer Architecture)

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Introduction to Software Development (ISD) David Weston and Igor Razgon

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Topic 1: Introduction

Introduction to Programming Using Java (98-388)

Chapter 2. Elementary Programming

Lecture 02, Fall 2018 Friday September 7

Introduction to Java Unit 1. Using BlueJ to Write Programs

Java Basics Lecture: January 26, 2012 (On-line Lecture 1)

Getting started with Java

Information Science 1

Chapter 2 Elementary Programming

Topic 2: Introduction to Programming

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Introduction to Computer Programming

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

C++ for Java Programmers

Computer Science II Lecture 1 Introduction and Background

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Lab5. Wooseok Kim

Kickstart Intro to Java Part I

Primitive Data, Variables, and Expressions; Simple Conditional Execution

1/11/2010 Topic 2: Introduction to Programming 1 1

COMP 202 Java in one week

Programming. Syntax and Semantics

Lecture Set 2: Starting Java

These are notes for the third lecture; if statements and loops.

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Midterms Save the Dates!

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CSE 582 Autumn 2002 Exam 11/26/02

Lecture Set 2: Starting Java

Zheng-Liang Lu Java Programming 45 / 79

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Lecture 1. Course Overview, Python Basics

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

Princeton University. Computer Science 217: Introduction to Programming Systems. Data Types in C

Transcription:

University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Constants Using Classes and Objects Lecture 4 Some slides borrowed from Kurt Eiselt, Tamara Munzner, and Steve Wolfman. Some learning goals from Beth Simon. PeerWise Study PeerWise is a system designed to facilitate students helping each other learn. This term s 111 sections are being studied to evaluate how effective PeerWise really is. You (Section 206) have been randomly selected as the treatment group : You will get access to the PeerWise system. (Details later.) You will be required (3% of course grade) to complete some activities on PeerWise. You have the right to opt out. You must email me by noon, January 21, to opt out. Email me your full name, student ID number, and say that you opt out. If you opt out, you will be denied access to PeerWise, you will not be required to do the activities, and you will be marked as if you were in Section 205. Readings Your textbook is Big Java (3rd Ed). Labs and Tutorials This week is Lab #2. It has a pre-lab! This Week s Reading: Ch 2.6-2.10, Finish Ch 4 Midterms Save the Dates! Midterm #1 is 5:30-6:30pm on February 10 (Tuesday) in Woodward IRC 2 Midterm #2 is 6-7pm on March 11 (Wednesday) in Woodward IRC 2 You must notify me well in advance (I will specify deadlines as the dates approach) if you have an unavoidable conflict with a midterm. Learning Goals By the end of the next several lectures you will be able to Explain the concepts of class, object, and method as used in computer programming. Find pre-defined classes in the Java library, understand the documentation, and use the methods for basic classes. Write programs that use common Java classes like BigInteger, String, and Scanner. 1

Learning Goals By the end of class today you will be able to Describe what classes, objects, and methods are. Find the on-line documentation for Java s library of pre-defined classes. Use constructors to create new objects, and explain why this is necessary. Explain what syntax, runtime, and logical errors are. Last Time We got more comfortable with the Java primitive types and operators. We learned the rules for when Java will convert types automatically. We learned how to force conversion ( cast ) from one type to another. We learned how to declare constants and the rationale for doing so. Finishing Off from Last Time We got more comfortable with the Java primitive types and operators. We learned the rules for when Java will convert types automatically. We learned how to force conversion ( cast ) from one type to another. We learned how to declare constants and the rationale for doing so. Casting Casting: force Java to convert from one type to another, even with information loss Converting from real to integer int shoes = (int) 1.5; Truncation: fractional part thrown away int shoes = (int) 1.75; int shoes = (int) 1.25; Rounding: must be done explicitly shoes = Math.round(1.99); Converting Between Types // Feet.java Author: Tamara // What type of things can be put on feet? public class Feet int shoes = 2; int socks = (int) 1.75; System.out.println("shoes = " + shoes + " socks = " + socks); int toes = Math.round(1.99); System.out.println("toes = " + toes); What s wrong? Let s try it Converting Between Types // Feet2.java Author: Tamara // What type of things can be put on feet? public class Feet2 int shoes = 2; int socks = (int) 1.75; System.out.println("shoes = " + shoes + " socks = " + socks); long toes = Math.round(1.99); System.out.println("toes = " + toes); 2

Or Tell Java with a Type Cast // Feet2.java Author: Tamara // What type of things can be put on feet? public class Feet2 int shoes = 2; int socks = (int) 1.75; System.out.println("shoes = " + shoes + " socks = " + socks); int toes = (int) Math.round(1.99); System.out.println("toes = " + toes); Questions? Motivation for Constants Suppose we want to write a program to compute the distance in miles to various stars, for which we know the distance in lightyears. What Changes, What Doesn t? // Vroom.java Author: Tamara // Playing with constants public class Vroom double lightyears, milesaway; lightyears = 4.35; // to Alpha Centauri milesaway = lightyears * 186000 *60*60*24*365; milesaway " + milesaway); lightyears = 68; // to Aldebaran milesaway = lightyears * 186000 *60*60*24*365; milesaway " + milesaway); Constants Things that do not vary unlike variables will never change Syntax: final typename variablename; final typename variablename = value; Constant names in all upper case Java convention, not compiler/syntax requirement Programming With Constants double lightyears, milesaway; final int LIGHTSPEED = 186000; final int SECONDS_PER_YEAR = 60*60*24*365; lightyears = 4.35; // to Alpha Centauri milesaway = lightyears * LIGHTSPEED * SECONDS_PER_YEAR; miles " + milesaway); lightyears = 68; // to Aldebaran milesaway = lightyears * LIGHTSPEED * SECONDS_PER_YEAR; miles " + milesaway); 3

Programming With Constants double lightyears, milesaway; final int LIGHTSPEED = 186000; final int SECONDS_PER_YEAR = 60*60*24*365; final double ALPHACENT_DIST = 4.35; // to AlphaCentauri final double ALDEBARAN_DIST = 68; // to Aldebaran lightyears = ALPHACENT_DIST; milesaway = lightyears * LIGHTSPEED * SECONDS_PER_YEAR; miles " + milesaway); lightyears = ALDEBARAN_DIST; Avoiding Magic Numbers magic numbers : numeric constants directly in almost always bad idea! hard to understand hard to make changes typos possible use constants instead milesaway = lightyears * LIGHTSPEED * SECONDS_PER_YEAR; miles " + milesaway); Questions? Using Classes and Objects Primitive Data Types: Numbers Type Size Min Max byte 1 byte -128 127 short 2 bytes -32,768 32,767 int 4 bytes -2,147,483,648 2,147,483,647 long 8 bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807 float 4 bytes approx -3.4E38 (7 sig.digits) approx 3.4E38 (7 sig.digits) double 8 bytes approx -1.7E308 (15 sig. digits) approx 1.7E308 (15 sig. digits) Six primitives for numbers fixed size, so finite capacity integer vs. floating point Operators and Operands Programming is all about specifiying data that is to be manipulated or acted upon operations that can act upon data order in which operations are applied to data So far: specify data using primitive data types come with pre-defined operations like +, -, *, and / 4

Programming with Classes What if data we want to work with is more complex than these few primitive data types? Programming with Classes What if data we want to work with is more complex than these few primitive data types? We can make our own data type: specifies nature of data we want to work with operations that can be performed on that kind of data (Other people can make data types, too, and we can use their work.) Object-Oriented Terminology For historical reasons, there are special terms for these new data types we create: The new data types are called classes. Values with the new data type are called objects. The operators for the new data type are called methods. (The programming style we are teaching, which is the dominant style in industry today, is called object-oriented programming.) Primitive Types vs. Classes Primitive Types Classes Pre-defined in Java Written by other programmers or by you Simplest things, e.g., int Can be arbitrarily complex Operators: +, -, Values belong to types. E.g., 3 is an int, 3.14159 is a double Methods Objects belong to classes E.g., a Toyota Prius is a car. Class Libraries Before making new class yourself, check to see if someone else did it already libraries written by other programmers many built into Java Examples (built into Java) BigInteger (java.math.biginteger) lets you compute with arbitrarily big integers. Date (java.util.date) lets you get the current time. Calendar (java.util.calendar) does fancy date computations. Appendix C in your book lists common ones. API Documentation Online Java library documentation at http://java.sun.com/javase/6/docs/api let s take a look! Everything we need to know: critical details and often many things far beyond current need Classes in libraries are often referred to as Application Programming Interfaces or just API 5

Example: BigInteger Let s write a simple program to print out how much money you d make if your compensation package is a combination of salary and stock options. GetRichQuick public class GetRichQuick public static void main(string[] args) int salary = 123456; int stockoptions = 10000; int profitpershare = 30; int optioncompensation = stockoptions * profitpershare; int totalcompensation = salary + optioncompensation; GetRichQuick 2 public class GetRichQuick public static void main(string[] args) int salary = 111222333444555666777888999; int stockoptions = 10000000000000000000000; int profitpershare = 3000000000000000000000; int optioncompensation = stockoptions * profitpershare; int totalcompensation = salary + optioncompensation; GetRichQuick w/ BigInteger import java.math.biginteger; //Tell Java to use BigInteger pkg public class GetRichQuick public static void main(string[] args) int salary = 111222333444555666777888999; int stockoptions = 10000000000000000000000; int profitpershare = 3000000000000000000000; int optioncompensation = stockoptions * profitpershare; int totalcompensation = salary + optioncompensation; GetRichQuick w/ BigInteger import java.math.biginteger; //Tell Java to use BigInteger pkg public class GetRichQuick public static void main(string[] args) BigInteger salary = 111222333444555666777888999; BigInteger stockoptions = 10000000000000000000000; BigInteger profitpershare = 3000000000000000000000; BigInteger optioncompensation = stockoptions * profitpershare; BigInteger totalcompensation = salary + optioncompensation; GetRichQuick: Constructors import java.math.biginteger; //Tell Java to use BigInteger pkg public class GetRichQuick public static void main(string[] args) BigInteger salary = new BigInteger( 111222333444555666777888999 ); BigInteger stockoptions = new BigInteger( 10000000000000000000000 ); BigInteger profitpershare = new BigInteger( 3000000000000000000000 ); BigInteger optioncompensation = stockoptions * profitpershare; BigInteger totalcompensation = salary + optioncompensation; 6

GetRichQuick: Methods import java.math.biginteger; //Tell Java to use BigInteger pkg public class GetRichQuick public static void main(string[] args) BigInteger salary = new BigInteger( 111222333444555666777888999 ); BigInteger stockoptions = new BigInteger( 10000000000000000000000 ); BigInteger profitpershare = new BigInteger( 3000000000000000000000 ); BigInteger optioncompensation = stockoptions.multiply(profitpershare); BigInteger totalcompensation = salary.add(optioncompensation); Recap: Using classes Import the name of the class you want: import java.math.biginteger; Declare variables using the class name: BigInteger salary; Create values (objects) of the new type/class by using constructors: salary = new BigInteger( 111222333 ); Operate on the objects using methods: totalcompensation = salary.add(bonus); Recap: Using classes Import the name of the class you want: import java.math.biginteger; Declare variables using the class name: BigInteger salary; Create values (objects) of the new type/class by using constructors: salary = new BigInteger( 111222333 ); Operate on the objects using methods: totalcompensation = salary.add(bonus); Literals With the primitive types, how do you create values with that type? E.g., how do we create integer values? 1. You type some digits, like 3, or 42 2. You combine integer-valued things with operators that work on integers, e.g., 3+42*(a-b) Literals With the primitive types, how do you create values with that type? E.g., how do we create integer values? 1. You type some digits, like 3, or 42 2. You combine integer-valued things with operators that work on integers, e.g., 3+42*(a-b) A bunch of digits are an integer literal. It s the basic way to create an integer value More Literals How about a value of type double? 1. You type a bunch of digits with a decimal point, and optionally the letter e or E followed by an exponent 2. You can combine doubles with operators that work on doubles. 7

More Literals How about a value of type double? 1. You type a bunch of digits with a decimal point, and optionally the letter e or E followed by an exponent 2. You can combine doubles with operators that work on doubles. Long Literals How about values of type long? 1. You type a bunch of digits followed by the letter l or L 2. You combine previously created longs Those are literals! Literals General Pattern To create values of a primitive type: 1. There s some way to type a literal 2. There are operators that create values of the given type. Literals for Classes? Classes are like primitive types, except they can be defined any way you like, and they can be much more complex. How to create a value (an object) of a given class? 1. Invent some way to type a literal??? 2. Operators that create objects of that class (methods). Constructors! A constructor is the equivalent of a literal for a class. It s how you create a new object that belongs to that class. Examples: new BigInteger( 999999 ) new Rectangle(10, 20, 30, 40) new UBCStudent( Alan Hu,12345678, ) Constructor Syntax The reserved word new Followed by the name of the class Followed by an open parenthesis ( Followed by any parameters (information needed to construct the object) Followed by a closing parenthesis ) 8

Using Constructors Use a constructor just as you d use a literal. Example: For the int type: int a = 3; For the BigInteger class: BigInteger a = new BigInteger( 3 ); Primitive Types vs. Classes Primitive Types Classes Pre-defined in Java Written by other programmers or by you Simplest things, e.g., int Can be arbitrarily complex Operators: +, -, Values belong to types. E.g., 3 is an int, 3.14159 is a double Literals Methods Objects belong to classes E.g., you are a UBC Student Constructors Change of Gears Program Development Use an editor to create your Java program often called source used interchangeably with program or instructions in the computer world Another program, a compiler or an interpreter, translates source into target language or object, which is often machine language Finally, your computer can execute object insight source object results editing translating executing Syntax Rules to dictate how statements are constructed. Example: open bracket needs matching close bracket If program is not syntactically correct, cannot be translated by compiler Different than humans dealing with natural languages like English. Consider statement t t with incorrect syntax (grammar) for weeks. rained in Vancouver it hasn t we still have pretty good shot at figuring out meaning Semantics What will happen when statement is executed Programming languages have well-defined semantics, no ambiguity Different than natural languages like English. Consider statement: Mary counted on her computer. How could we interpret this? Programming languages cannot allow for such ambiguities or computer would not know which interpretation to execute 9

Errors Computers follows our instructions exactly If program produces the wrong result, it s the programmer s fault unless the user inputs incorrect data then cannot expect program to output correct results: Garbage in, garbage out (GIGO) Debugging: process of finding and correcting errors Unfortunately can be very time consuming! compile-time error Errors insight source object results editing translating executing Error at compile time (during translation) you did not follow syntax rules that say how Java elements must be combined to form valid Java statements Errors run-time error compile-time error compile-time error Errors run-time error logical error insight source object results editing translating executing insight source object results editing translating executing Error at run time (during execution) Source compiles Syntactically (structurally) correct But program tried something computers cannot do like divide a number by zero. Typically program will crash: halt prematurely Logical error Source compiles Object runs But program may still produce incorrect results because logic of your program is incorrect Typically hardest problems to find Questions? 10