Why do we have to write a type for every variable in Java?

Similar documents
Last time s big ideas

Another interface: Comparable

CS 2230 CS II: Data structures. Meeting 21: trees Brandon Myers University of Iowa

== isn t always equal?

Where we are going (today)

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

Introduction to Programming Using Java (98-388)

CS212 Midterm. 1. Read the following code fragments and answer the questions.

CS 231 Data Structures and Algorithms, Fall 2016

PROGRAMMING FUNDAMENTALS

Programming Basics. Digital Urban Visualization. People as Flows. ia

Java Foundations. 7-2 Instantiating Objects. Copyright 2015, Oracle and/or its affiliates. All rights reserved.

CS 101 Exam 2 Spring Id Name

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

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Packaging Your Program into a Distributable JAR File

Key Java Simple Data Types

CS 2230 CS II: Data structures. Meeting 20: generic types, exceptions, higher order functions Brandon Myers University of Iowa

Where we are going (today)

CS 2630 Computer Organization. Meeting 10/11: data structures in MIPS Brandon Myers University of Iowa

CS201 - Assignment 3, Part 1 Due: Friday February 28, at the beginning of class

CS 101 Fall 2005 Midterm 2 Name: ID:

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal


Java Simple Data Types

Arrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003

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

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Lec 3. Compilers, Debugging, Hello World, and Variables

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

AP CS Unit 6: Inheritance Notes

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

Java Identifiers, Data Types & Variables

CS 2230 CS II: Data structures. Meeting 26: the Set ADT Brandon Myers University of Iowa

Introduction to Java

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

1. Find the output of following java program. class MainClass { public static void main (String arg[])

Question: Total Points: Score:

1.00 Lecture 8. Using An Existing Class, cont.

Question: Total Points: Score:

The high-level language has a series of primitive (builtin) types that we use to signify what s in the memory

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005

Where we are going (today)

Oracle 1Z Java SE 8 Programmer I. Download Full Version :

CS180. Exam 1 Review

CS 1331 Exam 1 ANSWER KEY

CMSC 341 Lecture 7 Lists

CS170 Introduction to Computer Science Midterm 2

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Chapter 6 Lab Classes and Objects

Object-Oriented Programming

CIS March 1, 2018

Sorting race.

DM550 Introduction to Programming part 2. Jan Baumbach.

CS 2230 CS II: Data structures. Limits of comparison sorting, beyond comparison sorting Brandon Myers University of Iowa

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

CHAPTER 7 OBJECTS AND CLASSES

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

Getting started with Java

H212 Introduction to Software Systems Honors

NATIONAL UNIVERSITY OF SINGAPORE

CS 251 Intermediate Programming Methods and Classes

Lecture 7 Objects and Classes

CS 251 Intermediate Programming Methods and More

Object-Oriented Programming Concepts

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Java and OOP. Part 2 Classes and objects

Section 003 Fall CS 170 Exam 2. Name (print): Instructions:

CS106A, Stanford Handout #18. Writing a Class

This exam is open book. Each question is worth 3 points.

Lecture #23: Conversion and Type Inference

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. and data-structures CS/ENGRD 2110 SUMMER 2018

Final Exam CS 152, Computer Programming Fundamentals December 5, 2014

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Computer Science II Data Structures

Final Exam. COMP Summer I June 26, points

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

Getting started with Java

CS 1331 Exam 1. Fall Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

Recitation 3 Class and Objects

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

CS 211: Methods, Memory, Equality

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux

Selected Questions from by Nageshwara Rao

C22a: Problem Solving using Recursion

CS 302 Week 9. Jim Williams

Unit 4: Classes and Objects Notes

Name Section Number. Sections 1-3 *** TURN OFF ALL ELECTRONIC DEVICES*** Bob Wilson

Java Simple Data Types

What is the return type of getnameofmonth?

Lab Assignment Three

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

COMPUTER APPLICATIONS

Problem Grade Total

Transcription:

Why do we have to write a type for every variable in Java?

Why do we have to write a type for every variable in Java? def first_letter(s): if len(s) > 0: return s[0] else: return "" # your test cases everything is ok! print first_letter("cs2230") print first_letter("hello world") print first_letter("") # the user's input print first_letter(4) Traceback (most recent call last): File "types.py", line 16, in <module> print first_letter(4) # breaks! File "types.py", line 4, in first_letter if len(s) > 0: TypeError: object of type 'int' has no len()

public class Types { public static void main(string[] args) { first_letter("cs2230"); first_letter("hello world"); first_letter(""); giving it an integer first_letter(4); wants a String public static String first_letter(string s) { if (s.length() > 0) { return s.substring(0,1); else { return ""; Before we run the Java program, we compile it. And the compiler says: Types.java:7: error: incompatible types: int cannot be converted to String first_letter(4);

Peer instruction socrative.com room: CS2230 public class Mystery { public static void main(string[] args) { int f = 22; int g = 1000; f = g + f; public static int stuff(int x) { return -x What is the result of trying to compile and run this program? a) runs fine b) error while compiling ( compile time error ) c) error while running ( runtime error )

Today s big ideas Two kinds of data in Java: primitives and objects We refer to an object using a reference There is a difference between passing objects and primitives to a method

CS 2230 CS II: Data structures Meeting 3: Objects and references Brandon Myers University of Iowa

An example from the doctor We need to build a system to track patients First, patients have a name and height (in inches) class Patient { String name; int height; defines the class Patient

Creating a patient class Patient { String name; int height; // constructor (says how to initialize a new Patient) Patient(String n, int h) { name = n; height = h; public static void main(string[] args) { // create a Patient Patient p1 = new Patient("Jane Doe", 65);

Updating a patient When patients come it for a check up, we want to update their height with the latest measurement class Patient { String name; int height; Patient(String n, int h) { name = n; height = h; void updateheight(int newheight) { height = newheight; method public static void main(string[] args) { Patient p1 = new Patient("Jane Doe", 65); p1.updateheight(70); call the method on p1

https://b.socrative.com/login/student/ Peer instruction public class MathStuff { static void squareit(int x) { x = x*x; public static void main(string[] args) { int a = 10; squareit(a); System.out.println(a); What does the program print to the console? a) a b) 10 c) 100 d) e) 10*10

https://b.socrative.com/login/student/ Peer instruction public class MathStuff { static void squareit(int[] x) { x[0] = x[0] * x[0]; public static void main(string[] args) { int[] a = new int[3]; a[0] = 10; squareit(a); System.out.println(a[0]); What does the program print to the console? a) a b) 10 c) 100 d) e) x[0]*x[0]

References let s work through that last example with diagrams public class MathStuff { static void squareit(int[] x) { x[0] = x[0] * x[0]; public static void main(string[] args) { > int[] a; a = new int[3]; a[0] = 10; squareit(a); System.out.println(a[0]); a

References public class MathStuff { static void squareit(int[] x) { x[0] = x[0] * x[0]; public static void main(string[] args) { int[] a; > a = new int[3]; a[0] = 10; squareit(a); System.out.println(a[0]); a array

References public class MathStuff { static void squareit(int[] x) { x[0] = x[0] * x[0]; public static void main(string[] args) { int[] a; a = new int[3]; > a[0] = 10; squareit(a); System.out.println(a[0]); 10 a array

References public class MathStuff { static void squareit(int[] x) { x[0] = x[0] * x[0]; public static void main(string[] args) { int[] a; a = new int[3]; a[0] = 10; > squareit(a); System.out.println(a[0]); 10 a array x

References public class MathStuff { static void squareit(int[] x) { > x[0] = x[0] * x[0]; public static void main(string[] args) { int[] a; a = new int[3]; a[0] = 10; squareit(a); System.out.println(a[0]); 100 a array x

References public class MathStuff { static void squareit(int[] x) { x[0] = x[0] * x[0]; public static void main(string[] args) { int[] a; a = new int[3]; a[0] = 10; squareit(a); > System.out.println(a[0]); 100 a array x

Section today

Today s big ideas Two kinds of data in Java: primitives and objects We refer to an object using a reference There is a difference between passing objects and primitives to a method

Today s big ideas When we want an array of objects, we store their references in the array It is important to distinguish between the specification and implementation of a class public and private control access to fields and methods

CS 2230 CS II: Data structures Meeting 3: Objects oriented programming Brandon Myers University of Iowa

Peer instruction https://b.socrative.com/login/student/ CS2230A class Doctor { void checkup(patient p) { Patient p2 = new Patient(p.name, p.height+10); p = p2; public static void main(string[] args) { Doctor d = new Doctor(); Patient georgia = new Patient("Georgia", 71); d.checkup(georgia); System.out.println(georgia.height); What does the program print to the console? a) 81 b) georgia.height c) Patient d) Georgia e) 71

Peer instruction: explanation class Doctor { void checkup(patient p) { Patient p2 = new Patient(p.name, p.height+10); p = p2; public static void main(string[] args) { Doctor d = new Doctor(); > Patient georgia = new Patient("Georgia", 71); d.checkup(georgia); System.out.println(georgia.height); georgia Patient( Georgia,71)

Peer instruction: explanation class Doctor { void checkup(patient p) { Patient p2 = new Patient(p.name, p.height+10); p = p2; public static void main(string[] args) { Doctor d = new Doctor(); Patient georgia = new Patient("Georgia", 71); > d.checkup(georgia); System.out.println(georgia.height); georgia Patient( Georgia,71) p

Peer instruction: explanation class Doctor { void checkup(patient p) { > Patient p2 = new Patient(p.name, p.height+10); p = p2; public static void main(string[] args) { Doctor d = new Doctor(); Patient georgia = new Patient("Georgia", 71); d.checkup(georgia); System.out.println(georgia.height); georgia Patient( Georgia,71) p p2 Patient( Georgia,81)

Peer instruction: explanation class Doctor { void checkup(patient p) { Patient p2 = new Patient(p.name, p.height+10); > p = p2; public static void main(string[] args) { Doctor d = new Doctor(); Patient georgia = new Patient("Georgia", 71); d.checkup(georgia); System.out.println(georgia.height); georgia Patient( Georgia,71) p p2 Patient( Georgia,81)

Peer instruction: explanation class Doctor { void checkup(patient p) { Patient p2 = new Patient(p.name, p.height+10); p = p2; public static void main(string[] args) { Doctor d = new Doctor(); Patient georgia = new Patient("Georgia", 71); d.checkup(georgia); > System.out.println(georgia.height); georgia Patient( Georgia,71)

How do we fix the program? Option A class Doctor { Patient checkup(patient p) { Patient p2 = new Patient(p.name, p.height+10); return p2; public static void main(string[] args) { Doctor d = new Doctor(); Patient georgia = new Patient("Georgia", 71); georgia = d.checkup(georgia); System.out.println(georgia.height); georgia Patient( Georgia,71) Patient( Georgia,81)

How do we fix the program? Option B class Doctor { void checkup(patient p) { p.height = p.height + 10; public static void main(string[] args) { Doctor d = new Doctor(); Patient georgia = new Patient("Georgia", 71); d.checkup(georgia); System.out.println(georgia.height); georgia Patient( Georgia,81)

Trust the boxes and arrows! Patient x = new Patient( Tiger,71) Patient y = new Patient( Elephant,100) x y Patient( Tiger,71) Patient( Elephant,100) assigning to a reference x = y x y Patient( Tiger,71) Patient( Elephant,100)

Trust the boxes and arrows! Patient x = new Patient( Tiger,71) Patient y = new Patient( Elephant,100) x y Patient( Tiger,71) Patient( Elephant,100) reading a field int z = x.height; x y Patient( Tiger,71) Patient( Elephant,100) z 71

Trust the boxes and arrows! Patient x = new Patient( Tiger,71) Patient y = new Patient( Elephant,100) x y Patient( Tiger,71) Patient( Elephant,100) writing a field x.height = 99; x y Patient( Tiger,99) Patient( Elephant,100)

Trust the boxes and arrows! Patient x = new Patient( Tiger,71) Patient y = new Patient( Elephant,100) x y Patient( Tiger,71) Patient( Elephant,100) reading a field and writing another field x.height = y.height; x y Patient( Tiger,100) Patient( Elephant,100)

Extend the patients application Now we want a database of Patients that can do two things Register a new Patient in the database (if we have room) Print our Patients names in alphabetical order

Specification of the PatientDatabase class class PatientDatabase { // Register a new Patient in the database // return false if out of space boolean registernewpatient(string name) {... // Print all patient names in alphabetical order void printnamesalphabetically() {... public static void main(string[] args) { PatientDatabase db = new PatientDatabase(100); db.registernewpatient("ron"); db.registernewpatient("hermoine"); db.registernewpatient("snape"); db.registernewpatient("harry"); db.printnamesalphabetically(); What a PatientDatabase needs to be able to do An example of using a PatientDatabase

class PatientDatabase { private Patient[] patients; private int numpatients; Let s implement the PatientDatabase with an array, which we ll keep sorted PatientDatabase(int maxpatients) { patients = new Patient[maxPatients]; numpatients = 0; // Register a new Patient in the database // return false if out of space boolean registernewpatient(string name) {... // Print all patient names in alphabetical order void printnamesalphabetically() {... EXAMPLE patients: Patient( Harry ) Patient( Hermione ) Patient( Ron ) numpatients: 3

Peer instruction https://b.socrative.com/login/student/ CS2230A Patient[] arr = new Patient[4]; Patient pa = new Patient("A", 1); Patient pb = new Patient("B", 2); arr[0] = pa; arr[2] = pb; arr[3] = pa; What is the result of running this code? (A) (B) Patient( A, 1) Patient( B, 2) Patient( B, 2) Patient( A, 1) (C) (D) Patient ( A,1) Patient ( B,2) Patient ( A,1) Patient( A, 1) Patient( B, 2) Patient( A, 1)

// Register a new Patient in the database boolean registernewpatient(string name) {... algorithm: insert new element at the the end, then swap until it is in the right place Harry Ron Snape registernewpatient( Hermione ) Harry Ron Snape Hermione Harry Ron Hermione Snape Harry Hermione Ron Snape

// Register a new Patient in the database (if we have space) boolean registernewpatient(string name) { if (numpatients == patients.length) return false; // since they haven't been measured we will give height=0 Patient newp = new Patient(name, 0); // start with the new patient at the end of the list patients[numpatients] = newp; numpatients+=1; // keep swapping the patient with the previous patient // until it is in alphabetical order int i = numpatients-1; while (i > 0 && patients[i].name.compareto(patients[i-1].name) < 0) { swappatients(i, i-1); i--; return true; Alice.compareTo( Bob ) à -1 Bob.compareTo( Alice ) à 1 we ll get to swappatients() next

class PatientDatabase { private Patient[] patients; private void swappatients(int a, int b) { Patient pa = patients[a]; Patient pb = patients[b]; patients[a] = pb; patients[b] = pa; boolean registernewpatient(string name) { while ( ) { swappatients(i, i-1);

class PatientDatabase { private Patient[] patients; private void swappatients(int a, int b) { Patient pa = patients[a]; Patient pb = patients[b]; patients[a] = pb; patients[b] = pa; swappatients() wouldn t make sense to outsiders! it is just an implementation detail used by registernewpatient() PatientDatabase could have been implemented with something other than an array sorted by names boolean registernewpatient(string name) { while ( ) { swappatients(i, i-1);

Peer instruction https://b.socrative.com/login/student/ CS2230A Making patients and swappatients private is most an example of which object-oriented design principle? A) Abstraction B) Encapsulation C) Modularity (page 61 of GTG) class PatientDatabase { private Patient[] patients; private void swappatients(int a, int b) { boolean registernewpatient(string name) { while ( ) { swappatients(i, i-1);

Implementation of the other method // Print all patient names in alphabetical order void printnamesalphabetically() { for (int i=0; i<numpatients; i++) { System.out.println(patients[i].name); (see the whole PatientDatabase class in PatientDatabase.java, and run the program for yourself)

https://b.socrative.com/login/student/ CS2230A Think-pair-share (peer instruction) Why is it important to distinguish between the specification and the implementation of a class? (short answer)

Today s big ideas When we want an array of objects, we store their references in the array It is important to distinguish between the specification and implementation of a class public and private control access to fields and methods