CS171:Introduction to Computer Science II

Similar documents
CS171:Introduction to Computer Science II

Chapter 2 Elementary Programming

Introduction to Programming Using Java (98-388)

Chapter 2. Elementary Programming

The Java language has a wide variety of modifiers, including the following:

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

JAVA OPERATORS GENERAL

Chapter 2 Primitive Data Types and Operations. Objectives

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

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

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Chapter 2 ELEMENTARY PROGRAMMING

Object-Oriented Programming

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

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Course Outline. Introduction to java

Important Java terminology

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Lecture Set 4: More About Methods and More About Operators

Zheng-Liang Lu Java Programming 45 / 79

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Lecture Set 4: More About Methods and More About Operators

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

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

Lecture 5: Methods CS2301

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Prof. Navrati Saxena TA: Rochak Sachan

CompSci 125 Lecture 11

CompuScholar, Inc. 9th - 12th grades

Operators and Expressions

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution


Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Chapter 2 Elementary Programming

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Homework #3 CS2255 Fall 2012

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

ECE 122. Engineering Problem Solving with Java

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

CS 106 Introduction to Computer Science I

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

Simple Java Reference

CS2141 Software Development using C/C++ C++ Basics

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

TeenCoder : Java Programming (ISBN )

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

Lecture 1 Java SE Programming

Information Science 1

JAVA Programming Concepts

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

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

Object Oriented Programming with Java

Controls Structure for Repetition

Chapter 2 Primitive Data Types and Operations

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Control Structures (Deitel chapter 4,5)

CT 229. Java Syntax 26/09/2006 CT229

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

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

Computer Science is...

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Programming with Java

CS 170, Section /3/2009 CS170, Section 000, Fall

CEN 414 Java Programming

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

COMP 202 Java in one week

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

CIS133J. Working with Numbers in Java

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

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

Chapter 2: Using Data

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

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

Variables and Operators 2/20/01 Lecture #

Chapter 2 Primitive Data Types and Operations

COMP 202. Java in one week

Information Science 1

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

CS1150 Principles of Computer Science Loops (Part II)

CS111: PROGRAMMING LANGUAGE II

Java Basic Programming Constructs

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 2: Using Data

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Chapter 2: Data and Expressions

CS 106 Introduction to Computer Science I

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Chapter 2: Data and Expressions

Transcription:

CS171:Introduction to Computer Science II Department of Mathematics and Computer Science Li Xiong 1/24/2012 1

Roadmap Lab session Pretest Postmortem Java Review Types, variables, assignments, expressions Control flow statements Methods Arrays OO and Inheritance 1/24/2012 2

Lab Session Option 1: Monday 10-11am Option 2: Monday 5-6pm (selected) Option 3: Friday 10-11am First lab session: Eclipse and debugging lab

Debugging Debugging - finding and correcting errors Approaches Hand-trace the program Insert print statements to show the values of the variables or the execution flow System.out.println( radius = + radius); Use a debugger utility

Programming Errors SyntaxErrors Detected by the compiler E.g. variable not initialized RuntimeErrors Causestheprogramtoabort E.g.arrayindexoutofbounds LogicErrors Produces incorrect result

Roadmap Lab session Pretest Postmortem Java Review Types, variables, assignments, expressions Control flow statements Methods Arrays OO and Inheritance 1/24/2012 6

Pretest Postmortem Question Topics #correct answers 1 Loops; post increment operator 15/31 2 Arithmetic operations - division; modulo 17/31 3 Object variables; null references 2/31 4 Integer variables 23/31 5 Object variables 23/31 6 Loops; arrays; problem solving 8/31 7a) Inheritance 28/31 7b) Inheritance; class constructor 11/31 7c) Methods; overloading; polymorphism 1/31 7d) Inheritance; problem solving 7/31

Roadmap Lab session Pretest Postmortem Java Review Types, variables, assignments, expressions Control flow statements Methods Arrays OO and Inheritance 1/24/2012 8

Data Types Primitive types 6 numeric types 4 integral types: byte, short, int, long 2 floating point types: float, double 1 character type: char 1 boolean type: boolean Reference types Class types, interface types, array types Special null types

Variables A variable is a name for a location in memory used to hold a data value. Type, name and contents Using a variable Declaring a variable type and name Instructs the compiler to reserve a portion of main memory to hold a particular type of value referred by a particular name Assign a value to a variable Use a variable in an expression A variable cannot be used if it is not declared or initialized The left hand side of the assignment operator is always a variable and the right hand side is an expression

Using Variables Declaring a variable int count; Assign a value to a variable count = 0; Declaring and initializing in one step int count = 0; Using a variable in an expression count += 1; count ++;

Primitive data types vs. object data types Variables of primitive data types store the actual value Variables of object types store the reference to the object int i = 1; Circle c = new Circle(); 12

The null Value If a data field of a reference type does not reference any object, the data field holds a special value: null Circle c; double r = c.getradius(); 13

Question A variable, intx stores: A. A reference to an int B. An integer value C. The identifier, x D. Lots of goodies for every good Java-slave 1/24/2012 14

Question A variable, BankAccountx stores: A reference to an object of the BankAccountclass An object of the BankAccountclass The identifier, x Even more goodies than a mere intx 1/24/2012 15

Question Which of the following will always correctly check whether an object variable objcontains a null reference? A) obj.equals(null); A) obj.equals(null); B) null == obj; C) obj= null; D) null.equals(obj); E) None of the above

Expressions An expression is a combination of one or more operators and operands that perform a calculation Operands might be numbers, variables, or expressions Arithmetic expressions int score = score 10 * latedays Boolean expressions boolean islate = submissiondate <= duedate;

Numeric Operators Name Meaning Example Result + Addition 34 + 1 35 - Subtraction 34.0 0.1 33.9 * Multiplication 300 * 30 9000 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2 Division performs integer division when both operands are integers

Question If a and b are intssuch that b!= 0 then which of the following expressions is always equivalent to a%b? A) a-(a/b)*b B) (a/b)*b C) a-a/b D) (double)a/b- a/b 1/24/2012 19

Shortcut Assignment Operators Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8

Increment and Decrement Operators Operator Name Description ++var preincrement The expression (++var) increments varby 1 and evaluates to the newvalue in varafterthe increment. var++ postincrement The expression (var++) evaluates to the original value in varand increments varby 1. --var predecrement The expression (--var) decrements varby 1 and evaluates to the newvalue in varafterthe decrement. var-- postdecrement The expression (var--) evaluates to the original value in varand decrements varby 1.

Increment and Decrement Operators, cont. int i = 10; Same effect as int newnum = 10 * i++; int newnum = 10 * i; i = i + 1; int i = 10; Same effect as int newnum = 10 * (++i); i = i + 1; int newnum = 10 * i;

The Boolean Expressions A Boolean expression evaluates to a Boolean value Comparison operators: compare a pair of values (numbers, characters, boolean values) boolean happy = grade > 90; Boolean operators: perform logic operations (boolean values) boolean happy = (grade > 90) && (workhours < 2); 23

Comparison Operators Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to!= not equal to 24

Comparing objects == compares references Check whether an object variable contains a null reference equals() method compares contents The default implementation of the equals method in the Object class: public boolean equals(object obj) { return (this == obj); Java classes such as String override equals() method so that it compares the content of two objects. It is a good idea to override equals() method for your own classes 25

Roadmap Lab session Pretest Postmortem Java Review Types, variables, assignments, expressions Control flow statements Methods Arrays OO and Inheritance 1/24/2012 26

Simple if Statements if (booleanexpression) { statement(s); if (!passedtest ) { System.out.println( I ll write good code! ); Boolean Expression false! passedtest false true true Statement(s) System.out.println( I ll write good code! ); (A) (B) 27

The if...else Statement if (booleanexpression) { statement(s)-for-the-true-case; else { statement(s)-for-the-false-case; 28

World Without Loops is Painful System.out.println( I will write good code! ); System.out.println( I will write good code! ); System.out.println( I will write good code! ); System.out.println( I will write good code! ); System.out.println( I will write good code! ); System.out.println( I will write good code! ); System.out.println( I will write good code! ); 9/21/2010 CS170, Section 000, Fall 2010 29

A Better Approach: Loops int count=0; while (count < 100){ System.out.println( I will write good code! ); count++; 9/21/2010 CS170, Section 000, Fall 2010 30

whileloop Flow Chart while (loop-continuation-condition){ // loop-body; Statement(s); intcount = 0; while (count < 100) { System.out.println( I ll write good code!"); count++; count = 0; Loop Continuation Condition? false (count < 100)? false true Statement(s) (loop body) true System.out.println("I ll write good code!"); count++; (A) (B) 31

do-whileloop Statement(s) (loop body) true do { // Loop body; Statement(s); while (loop-continuation-condition); Loop Continuation Condition? false 32

forloops for (initial-action; loop-condition; action-after-each-iteration) { // loop body; Statement(s); for(int count=0; count < 100; count++ ){ System.out.println( I will write good code! ); 9/21/2010 CS170, Section 000, Fall 2010 33

forloops for (initial-action; loopcontinuation-condition; action-after-each-iteration) { // loop body; Statement(s); for (inti= 0; i< 100; i++) { System.out.println( I ll write good code!"); Initial-Action i = 0 Loop Continuation Condition? false (i < 100)? false true Statement(s) (loop body) true System.out.println( "I ll write good code"); Action-After-Each-Iteration i++ (A) (B) 34

Which loop to use? Use the one that is most intuitive and comfortable for you. A for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition. 35

Question What is the output of the following code fragment?. int sum = 1; for (int i = 0; i <= 5; sum = sum + i++); System.out.print(sum); 1/24/2012 36

Bonus question What is the value of x after the following statements? intx = 0, j = 0; boolean done = false; while(!done) { for (inti= 0; i<5; i++) { j = j + i; if (j > 12) { x = j; done = true; 1/24/2012 37

Roadmap Lab session Pretest Postmortem Java Review Types, variables, assignments, expressions Control flow statements Methods Arrays OO and Inheritance 1/24/2012 38

Levels of Abstraction: Software Design Old times: computer programs manipulated primitive types such as numbers and characters Methods: Encapsulate routine computations to black boxes Object-oriented programming: Encapsulate data fields and methods to black boxes

Example Computing sum intsum = 0; intn=5; for (inti = 1; i <= n; i++ ) { sum += i; System.out.println( sum is: + sum);

Example -Print the sums of 1 10, 25 35, 40 50 public static void main(string[] args) { intsum = 0; for (int i = 1; i <= 10; i++) { sum += i; System.out.println("The sum of 1-10 is: " + sum); sum = 0; for (int i = 25; i <= 30; i++) { sum += i; System.out.println("The sum of 25-30 is: " + sum); for (int i = 40; i <= 50; i++) { sum += i; System.out.println("The sum of 40-50 is: " + sum); 9/30/2010 CS170, Section 000, Fall 2010 41

Using a method Sum If there was a method sumthat would take two input integer arguments, startandend, and would add up and returnsum of numbers fromstarttoend The program could be re-written much easier as: public static void main(string[] args) { System.out.println("sum(1, 10) is: " + sum(1, 10) ); // 1+2+...+10 System.out.println("sum(25, 30) is: " + sum(25, 30) ); //25+26+...+30 System.out.println("sum(40, 50) is: " + sum(40, 50) ); //40+41+...+50 9/30/2010 CS170, Section 000, Fall 2010 42

Defining a Method sum public static intsum(intstart, intend) { intsum = 0; for (inti = start; i <= end; i++) { sum += i; return sum; // return is required 9/30/2010 CS170, Section 000, Fall 2010 43

Defining and Using Methods Define a method give a definition of what the method is to do modifier returntype methodname(list of parameters) { collection of statements; Call or invoke a method use a method methodname(list of parameters) 44