BM214E Object Oriented Programming Lecture 4

Similar documents
Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

PROGRAMMING FUNDAMENTALS

Introduction to Programming Using Java (98-388)

Lecture Set 4: More About Methods and More About Operators

Control Structures in Java if-else and switch

Object-Oriented Programming

Full file at

1.00 Lecture 4. Promotion

1007 Imperative Programming Part II

Program Fundamentals

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

CS111: PROGRAMMING LANGUAGE II

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

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Java Bytecode (binary file)

Midterms Save the Dates!

Lecture Set 4: More About Methods and More About Operators

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

Introduction to Java

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Control Structures in Java if-else and switch

Getting started with Java

BM214E Object Oriented Programming Lecture 8

Lecture 5: Methods CS2301

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

CS 112 Introduction to Programming

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

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

CS 231 Data Structures and Algorithms, Fall 2016

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

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

CS11 Java. Fall Lecture 1

CS 251 Intermediate Programming Java Basics

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

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

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Intro. Scheme Basics. scm> 5 5. scm>

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

( &% class MyClass { }

CS Week 5. Jim Williams, PhD

Controls Structure for Repetition

Selected Questions from by Nageshwara Rao

Java is an objet-oriented programming language providing features that support

Programming Language Basics

COP 3330 Final Exam Review

CS171:Introduction to Computer Science II

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

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

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Pace University. Fundamental Concepts of CS121 1

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

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

COS 140: Foundations of Computer Science

Chapter 2: Using Data

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

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

Following is the general form of a typical decision making structure found in most of the programming languages:

COMP6700/2140 Data and Types

CS-201 Introduction to Programming with Java

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

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

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

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS111: PROGRAMMING LANGUAGE II

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Chapter 3. Selections

Basics of Java Programming

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

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

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

Expressions and Assignment

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

Variables and literals

Values and Variables 1 / 30

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Zheng-Liang Lu Java Programming 45 / 79

Elementary Programming

3. Java - Language Constructs I

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

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

DM550 Introduction to Programming part 2. Jan Baumbach.

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

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Chapter 2: Using Data

CMPT 125: Lecture 3 Data and Expressions

CSC 1214: Object-Oriented Programming

Fall 2017 CISC124 9/16/2017

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

Kickstart Intro to Java Part I

Transcription:

BM214E Object Oriented Programming Lecture 4

Computer Numbers Integers (byte, short, int, long) whole numbers exact relatively limited in magnitude (~10 19 ) Floating Point (float, double) fractional often approximations (0.33333) larger magnitude (~10 308 ) actually holds signed mantissa & exponent 6.023 x 10 23

List of Data Types Primitive Type Default Value boolean false char '\u0000' (null) byte (byte) 0 short (short) 0 int 0 long 0L float 0f double 0d void N/A Note: At times, the Java Language Specification refers to void as a primitive, though other parts (e.g., s. 14.7) say void is not a primitive as in C/C++. One cannot cast to a void type in Java.

Data Type Ranges Type Size Min Max Default boolean char 1 false* true* 16 false '\u0000' (null) byte 8-128 127 (byte) 0 short 16-32,768 32,767 (short) 0 int 32-2,147,483,648 2,147,483,647 0 long 64-9,223,372,036,854,775,808 9,223,372,036,854,775,807 float 32 Approx ±3.4E+38 with 7 significant digits 0.0F double 64 Approx ±1.7E+308 with 15 significant digits 0.0D void * Not truly min and max. 0L

Understanding Casting Last class, we covered some basics of casting. Sometimes an explicit cast is required, sometimes it s not. OK! Compiles ERROR Explicit cast needed int x = 10; float f1 = x; float f2 = 11.234f; int y = f2; Which one requires a cast to compile? Why?

Understanding Casting To understand when we need casting, let s look closely at an example. Let s work with these two types and identifiers: int x; char c; The real question is, How BIG are these data types in memory?

Sizes of Data Types A char is 2 bytes, and an int is 4 bytes. So when we code the following: int x; char c; We get: Symbol Picture of Memory x 0000 0000 0000 0000 0000 0000 0101 0110 c 0000 0000 0100 0001 Each block is one byte

So Will a char fit into an int? Will an int fit into a char? Symbol Picture of Memory x c

Explicit Casting: Intentional Loss of Precision int x = 45; char c = A ; c = (char) x; // cast needed Symbol Picture of Memory x c cast needed!

Testing Yourself What happens when we do this: int someint = 2000; long longnumber; longnumber = (long) someint; Is that cast legal? Is that cast required?

Another Example float f; int i, j; i = 9; j = 2; f = i / j; f = (float) i / j; f = i / (float) j; Returns 4 because of integer truncation! If that is not what was intended, Three possible solutions f = (float) i / (float) j;

Another example We also have to consider how Java preserves the sign of a value through casting. Consider the bytes used for an int. The highest bit is used for a sign (plus or minus, through a 0 or 1). int Sign bit 31 bits for data

Casting and Sign Casting is not just chopping one data type into another. The VM doesn t merely throw away half of the information. The sign is preserved. Preserves sign bit byte int

Another Example Suppose we had some very, very old data, where the date was expressed in a int (four byte) format, such as: 19231029 1923 10 (October) 29 This is very crude, but some old data source (e.g., tape archives) might have this format.

public class CutData { public static void main(string[] args) { int idate = 19231029; // this is how it was read in byte byday = (byte) (idate % 100); System.out.println ("The day was " + byday); idate = idate / 100; byte bymonth = (byte) (idate % 100); System.out.println ("The month was " + bymonth); idate = idate / 100; short syear = (short) idate; Explicit Cast needed System.out.print ("The year was = " + syear); } } // CutData

When working in the opposite direction (accumulating bytes and shorts into an int), no casting is needed, because we do not lose precision or information. public class PackDate { public static void main(string[] args) { byte month = 10; byte day = 29; short year = 1923; int date = year * 10000 + month * 100 + day; } System.out.println ("The date = " + date); } // PackDate

Shorthand Operators counter = counter + 1; OR counter++; counter = counter - 1; OR counter--; counter = counter + 2; OR counter = counter * 5; OR counter+=2; counter*=5; Last two examples: perform operation first (e.g. counter+2) then performs the assignment. Quick Review

Caution Before we can talk about methods in Java, we need to look at programming languages in general, from a very high level. Don t be alarmed by some of the syntax on the following slides. The big picture is what s important, not the coding details...

Programming Paradigms Procedural Programming Imperative assignment used to create state, and procedures manipulate state. e.g., C, Assembly, Pascal int y; int x = 3; y = manipulatedata(x); Functional Programming Functions (procedures that do not depend on outside data) are used to provided data. e.g., Lisp (defun check-member (input-item input-list) (cond ((null input-list) nil) ((equal input-item (first input-list)) T) (T (check-member input-item (rest input-list)))))

Programming Paradigms Object-Oriented Programming All data exists in objects; interaction occurs only between objects. Even numbers are objects that know how to add themselves. e.g., SmallTalk: array array := Array new: 5. rect := 0@0 corner: 8@9. 1 to: array size do: [ :item rect origin: item@item. array at: item put: rect copy ]. There are other paradigms, but these three help explain where Java comes from Where does Java fit? Object-oriented, but not 100% OO, since it contains primitives, and tolerates some (hopefully small) degree of procedural programming.

Java Methods There exists in Java a single construct, the method, for both procedures and functions: when a procedure is called for, specify the return type void before method name public void printhelloworld( ) { System.out.println( Hello World! ); } // printhelloworld Note the comment Note: All methods must have parentheses for parameters... even if no parameters!

Java Methods Single construct (method) for both procedures and functions: when a function is called for, specify the appropriate return type before method name public float average (float num1, float num2, float num3) { float answer; answer = (num1 + num2 + num3) / 3; return (answer); } // of average

A Java requirement: Writing Methods: A Larger Look --Each method belongs to an object (or class). --It must be unambiguous which object or class that is when a method is called. --To run an application program, there must be a class whose name is that of the program and that class must have a method called main. for command line parameters visible to all nothing returned public static void main (String[ ] argv) a class method, not an instance method method name

class A { public static void main(... } class B { public static void main(... } class C { public static void main(... } Each class may have its own main method. You pick the one you wish to run when invoking the JVM. This fact becomes critical when we learn to write debug test mains.

Method Signatures The signature of a method consists of the name of the method and the number and types of formal parameters to the method. A class may not declare two methods with the same signature, or a compile time error occurs. --Java Language Specification s.8.4.2 Method overloading occurs where identically named methods have subtle variations in the method parameters. public int getcube(int num){ return num*num*num; } public int getcube(float num){ return (int)(num*num*num); } public int getcube(double num){ return (int) (num*num*num); } Java lets you overload instead.

Methods: Common Mistakes public float average (float num1, float num2, float num3); { float answer; answer = (num1 + num2 + num3)/ 3; return (answer); } // average Note ending semicolon -- could be viewed as abstract method (more on abstract methods later) -- results in unhelpful error message about abstract methods (more on this later) -- EASY mistake to make!

Where Do Methods Go? Just like the main method we saw last time, any method we create must appear in classes, as either class or instance members. More on creating classes and objects shortly... For now, just know that methods belong in a class. i.e. They are defined inside a class.

OO Programming Note Already, we ve covered one of the most important aspects of Object Oriented (OO) programming: Data and methods belong together in a class. Right now, it s sufficient that you know that variables and methods belong in classes. Later, we ll see how this enables us to encapsulate state (the variables) with behavior (the methods).

Questions?

Conditionals

Java: Decision Statements if (condition) single statement; else single statement; or: if (condition) { statements; } else { statements; }

Examples Java: What happens here? int testgrade = 65; boolean passing = true; if (testgrade < 60) passing = false; System.out.println( Is + testgrade + passing? +passing);

Boolean and Relational Operators Boolean: Java: AND && OR NOT! Relational: equal to == not equal to!= less than < less than or equal to <= greater than > greater than or equal to >= Note: Assignment =

Example if (enrolled && passing) { // etc. } Java also supports short-circuiting, where only part of a boolean will be evaluated, as necessary: if (enrolled(studentnum) getpassing(studentnum)) { // etc. }

A bit of code public static void main(string args[]) { int quiz1 = 42; int quiz2 = 99; if(ispassing(quiz1) && ispassing(quiz2)) System.out.println( Passed both quizzes ); } public static boolean ispassing(int testgrade) { boolean passing = true; if (testgrade < 60) passing = false; System.out.println( Is + testgrade + passing? + passing); return passing; }

Final Answer? Is 42 passing? false a Is 42 passing? false Is 99 passing? true b

Multiple Selections via switch Use if construct for one selection. Use if/else construct for double selection. Use switch construct for multiple selection. (e.g., situations appropriate for if-elseif-elseif-else) Note: Useful when making a selection among multiple values of the same variable. Not useful when selecting among values of different variables.

Switch switch (<variable>) { case <value>: // whatever code you want break; case <value>: // whatever code you want break; default: // whatever code you want break; }

Multiple Selections via switch Note the optional default case at the end of the switch statement. It is optional only in terms of syntax. switch (inumber) { case 1: System.out.println ( One ); This would break; work without case 2: the default, System.out.println ( Two ); but would break; be poor case 3: technique System.out.println ( Three ); break; default: System.out.println( Not 1, 2, or 3 ); break; // Needed??? } // switch In practice you should always include a default case statement.

How many days? if(month == 4 month == 6 month == 9 month == 11) numdays = 30; else if(month == 2) { numdays = 28; if(leap) numdays = 29; } else numdays = 31;

Switch switch (month) { case 4: case 6: case 9: case 11: numdays = 30; break; case 2: numdays = 28; if(leap) numdays = 29; break; default: /* Good idea? */ numdays = 31; }

Multiple Selections via switch--notes The switch statement can be used with the following types: int, char, short, byte String (Java SE 7 and later) The case values must all be of the same type. The case values must all be FINAL constants.

switch (grade) { case A : case a : countofagrades++; break; case B : case b : countofbgrades++; break; case C : case c : countofcgrades++; break; case D : case d : countofdgrades++; break; case F : case f : countoffgrades++; break; default: } same System.out.println( Invalid grade ); break; if (grade== A grade== a ) countofagrades++; else if (grade== B grade== b ) countofbgrades++; else if (grade== C grade== c ) countofcgrades++; else if (grade== D grade== d ) countofdgrades++; else if (grade== F grade== f ) countoffgrades++; else System.out.println ( Invalid grade ); Multiple Selections via switch (assume these variables exist and have value)

Before we go too far... We often take liberties with good coding practice just to fit material onto a slide. Your coding style should reflect clearly and unambiguously what the code is supposed to do. Keep in mind your two audiences The machine Other programmers

If Style 1 if(<boolean expression>) { // code if true } else { // code if false }

If Style 2 if(<boolean expression>) { // code if true } // comment else { // code if false } // comment

Conditional Assignment boolean b; int count; <boolean>? <true condition> : <false condition> b = checkcompletion(); count = (b)? 3 : 1; Must resolve to boolean If true...... if false Note: This is not any faster. It s less readable. It exists only for recovering C hackers

A Semi Partial Conditional Summary Control structures Two kinds of conditional (summary) if {... } else {... } branch on boolean expression switch (...) { case...; break; default:... } branch on constant value don t forget to break!!

Questions?