If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider:

Similar documents
Control Flow Statements

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Software Design and Analysis for Engineers

More sophisticated behaviour Lecture 09

APCS Semester #1 Final Exam Practice Problems

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

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

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

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

Introduction. C provides two styles of flow control:

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

The for Loop. Lesson 11

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

Flow Control. CSC215 Lecture

Import Statements, Instance Members, and the Default Constructor

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Lecture 4 CSE July 1992

1007 Imperative Programming Part II

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

G Programming Languages - Fall 2012

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

LOOPS. Repetition using the while statement

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

CS112 Lecture: Working with Numbers

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

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

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Chapter 2: Functions and Control Structures

Program development plan

Control Structures in Java if-else and switch

DCS/100: Procedural Programming

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

CSE 113 A. Announcements - Lab

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Introduction to the Java Basics: Control Flow Statements

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Le L c e t c ur u e e 3 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 Control Statements

Accelerating Information Technology Innovation

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

Test Results Schedule Miscellanea Control Structs. Add l Oper s Break Hands on Q & A Conclusion References Files

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CSE 142/143 Unofficial Style Guide

Control Structures in Java if-else and switch

Computer Programming I - Unit 5 Lecture page 1 of 14

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

CS110D: PROGRAMMING LANGUAGE I

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

Python Evaluation Rules

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

Variables and literals

Lecture 10 Declarations and Scope

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

Implementing an Algorithm for Boomerang Fraction Sequences in Python

Condi(onals and Loops

Starting to Program in C++ (Basics & I/O)

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.

Software Design and Analysis for Engineers

Chapter 4 Defining Classes I

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

CSC-140 Assignment 6

Loops. CSE 114, Computer Science 1 Stony Brook University

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

1.7 Limit of a Function

Introduction to Object-Oriented Programming

SCHEME AND CALCULATOR 5b

T H E I N T E R A C T I V E S H E L L

QUIZ Friends class Y;

Overview. Iteration 4 kinds of loops. Infinite Loops. for while do while foreach

Lecture 5 8/24/18. Writing larger programs. Comments. What are we going to cover today? Using Comments. Comments in Python. Writing larger programs

Lecture 19 CSE August You taught me Language, and my profit on t is I know how to curse. William Shakspere, The Tempest, I, ii.

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Design Patterns: State, Bridge, Visitor

Exceptions and Design

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Program Syntax; Operational Semantics

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

What did we talk about last time? Course overview Policies Schedule

Dealing with Bugs. Kenneth M. Anderson University of Colorado, Boulder CSCI 5828 Lecture 27 04/21/2009

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

CS1004: Intro to CS in Java, Spring 2005

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1

Arrays and while Loops. Lecture 15 - COMP110 - Spring 2018

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Transcription:

CS61B Summer 2006 Instructor: Erin Korber Lecture 5, 3 July Reading for tomorrow: Chs. 7 and 8 1 Comparing Objects Every class has an equals method, whether you write one or not. If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider: Reference equality, ==. Two objects are == only if they are the same object. Could also describe this by saying, two references are == if they point to the same object. Shallow structural equality Two objects are equals if all of their fields (instance variables) are ==. Deep structural equality Two objects are equals if all of their fields (instance variables) are equals. Logical equality Precisely what this means will depend on what you are dealing with. Example: Two Set objects are equals if they contain the same elements, even if they are stored in a different order. Example: You would probably want to say that the fractions 1/2 and 2/4 are equals, even though their numerators and denominators are different, since they represent the same value. You will want to decide which kind of equality to test for, depending on what seems most appropriate for your particular application. 1

2 The static keyword 2.1 static fields A static field is a single variable shared by a whole class of objects; its value does not vary from object to object. For example, if numberofhumans is the number of Human objects that have been constructed, it is not appropriate for each object to have its own copy of this number; every time a new Human is created, we would have to update every Human. If we declare a field static, there is just one field for the whole class. You may remember these from CS61A - they were called class variables. Example of a static field: class Human { public static int numberofhumans; public int age; public String name; public Human() { numberofhumans++; // The constructor increments the number by one. If we want to look at the variable numberofhumans from another class, we write it in the usual notation, but we prefix it with the class name rather than the name of a specific object. int k = Human.numberOfHumans; int k = john.numberofhumans; // Good. // This works too, but has nothing to // do with john specifically. Don t // do this; it s bad (confusing) style. System.out and Math.PI are other examples of static fields. 2.2 static methods Methods can be static too. A static method runs without any instance of the class. THERE IS NO this, since there is no object. Any attempt to reference this will cause a compile-time error. Static methods never use instance variable values - of course they can t, since there is no instance to get them from! 2

class Human {... public static void printhumans() { System.out.println(numberOfHumans); Now, we can call Human.printHumans() from another class. We could also call john.printhumans(), but it s bad style. The main() method is always static, because when we run a program, we are not passing an object in, so there are no instances around on which to call any non-static methods. 3 final Java s final keyword is used to declare something that can never be changed. For example: public final static int FEBRUARY = 2; If you ever after try to assign a value to FEBRUARY, you ll have a compiler error. If you find yourself repeatedly using a numerical value with some meaning in your code, you should probably turn it into a final constant. BAD: if (month == 2) GOOD: if (month == FEBRUARY) Why? Because if you ever need to change the numerical value assigned to February, you ll only have to change one line of code, rather than hundreds. It is a long-standing stylistic convention to put the names of constants in all caps - this was inherited from C. For any array x, x.length is a final field. (Why do you think this is?) final isn t just for variables - methods and classes can also be declared final. We ll talk about what exactly this does later, when we talk about inheritance. 3

4 Special loop constructs 4.1 break A break statement immediately exits the innermost loop statement enclosing the break, and continues execution at the code following the loop. Recall the takedog method from our Kennel example last week: void takedog(dog d) { boolean has_home = false; for(doghouse h : houses) { if (!has_home && h.canfitdog(d)) { h.resident = d; has_home = true; //**** if (!has_home) { System.out.println("Dog won t fit!"); You may have noticed that the for loop will keep repeating until the end of the array, even if we find a home for the dog in the beginning! We could prevent this from happening by using a break statement at the starred point in the code - this will cause the flow of control to exit the loop immediately at that point. WARNING: It s easy to forget exactly where break will jump to. For this reason, Java (unlike C) allows you to attach labels to any kind of enclosing statement, including if statements and any group of statements placed in braces. Then, break can jump to the end of any labeled enclosure that encloses the break statement - just give it the name of the label for the enclosure that you want to jump to the end of. Example: finding an item in a two-dimensional array of ints with labelled break: 4

public void findint(int[] a, int searchfor){ search: for (int i=0; i<a.length; i++;) { for (j = 0; j < arrayofints[i].length; j++) { if (arrayofints[i][j] == searchfor) { foundit = true; break search; if (foundit) { System.out.println("Found "+searchfor+" at "+i+", "+j); else { System.out.println(searchfor+ "not in the array"); Note that the break statement terminates the labeled statement; it does not transfer the flow of control to the label. The flow of control is transferred to the statement immediately following the labeled (terminated) statement (since it s the labelled enclosure that is being broken ). 4.2 continue The continue statement is used to skip the current iteration of a loop. The unlabeled form skips to the end of the innermost loop s body and evaluates the boolean expression that controls the loop, basically skipping the remainder of this iteration of the loop. Note that continue does NOT exit the loop - another iteration may commence, if the loop condition is satisfied. What s the difference between the following two loops? int i = 0; for (int i = 0; i < 10; i++) { while (i < 10) { if (condition(i)) { if (condition(i)) { continue; continue; call(i); call(i); i++; 5

Answer: when continue is called in the while loop, i++ is not executed. In the for loop, however, i is incremented with every iteration. Use break and continue sparingly. They make it more difficult for both you and others to read, understand, and debug your code. If you find a lot of them appearing in your code, you may want to rethink how you ve planned out control flow. 4.3 switch Some long chains of if-then-else clauses can be simplified by using a switch statement. switch is appropriate only if every condition tests whether a variable x is equal to some constant. switch (month) { if (month == 2) { case 2: days = 28; days = 28; else if ((month == 4) (month == 6) break; (month == 9) (month == 11)){ case 4: days = 30; case 6: else { case 9: days = 31; case 11: days = 30; break; default: days = 31; break; // These two code fragments do exactly the same thing. IMPORTANT: break jumps to the end of the switch statement. If you forget a break statement, the flow of execution will continue right through past the next case clause. If month == 12 in the following example, both Strings are printed: switch (month) { case 12: output("it s December."); // Just keep moving right on through. case 11: case 1: case 2: output("it s cold."); default: 6

However, this style of coding is hard to read and understand. If there s any chance that other people will need to read or modify your code (which is very common when you program for a business), don t code it like this. Use break statements in the switch, and use subroutines to reuse code or clarify the control flow. 4.4 return You ve already used return as a means for a function to return a value. It can have another purpose: to affect the flow of control of a program. It causes a method to end immediately, so that control returns to the calling method. A small example: public void mymethod(int x) { if (x == 10) { return; System.out.println("Thank goodness x isn t 10."); 7