CS 211: Methods, Memory, Equality

Similar documents
Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

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

Fundamentals of Programming Data Types & Methods

Object Oriented Programming. Java-Lecture 6 - Arrays

Introduction to the Java Basics: Control Flow Statements

Loops. CSE 114, Computer Science 1 Stony Brook University

Full file at

Example: Monte Carlo Simulation 1

Introduction to Programming Using Java (98-388)

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

CS 211: Existing Classes in the Java Library

PROGRAMMING FUNDAMENTALS

CS Week 5. Jim Williams, PhD

AP Computer Science Unit 1. Programs

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Getting started with Java

CS 231 Data Structures and Algorithms, Fall 2016

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

CS 251 Intermediate Programming Java Basics

CS 112 Introduction to Programming

CSCI 355 Lab #2 Spring 2007

CSCI 1103: Static Methods

CS171:Introduction to Computer Science II

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

Controls Structure for Repetition

CS 211: Potpourri Enums, Packages, Unit Tests, Multi-dimensional Arrays Command Line Args

AP COMPUTER SCIENCE A

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Accelerating Information Technology Innovation

! Theoretical examples: ! Examples from Java: ! data type: A category of data values. " Example: integer, real number, string

Java Basic Programming Constructs

CS1150 Principles of Computer Science Loops (Part II)

Expressions & Flow Control

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CSCI 355 LAB #2 Spring 2004

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

CS159. Nathan Sprague

Midterm Examination (MTA)

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

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

Introduction to Java Applications

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Lecture 22: Java. Overall Structure. Classes & Objects. Every statement must end with ';' Carl Kingsford, , Fall 2015

CMPS 12A - Winter 2002 Final Exam A March 16, Name: ID:

Flow Control. CSC215 Lecture

CSCI 1103: Introduction

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

CSC Java Programming, Fall Java Data Types and Control Constructs

CS 222: Pointers and Manual Memory Management

H212 Introduction to Software Systems Honors

ECE 122. Engineering Problem Solving with Java

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

Array. Prepared By - Rifat Shahriyar

CS111: PROGRAMMING LANGUAGE II

CS18000: Programming I

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

CS111: PROGRAMMING LANGUAGE II

CompSci 125 Lecture 11

Bjarne Stroustrup. creator of C++

CS 1302 Chapter 9 (Review) Object & Classes

Variables and Java vs C++

CS 310: Hashing Basics and Hash Functions

CS 177 Recitation. Week 8 Methods

Arrays. Eng. Mohammed Abdualal

Introduction to C Language (M3-R )

CS1150 Principles of Computer Science Arrays

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

CS S-08 Arrays and Midterm Review 1

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

AP Computer Science A Unit 2. Exercises

DM550 Introduction to Programming part 2. Jan Baumbach.

Lecture Set 4: More About Methods and More About Operators

Object Oriented Programming Exception Handling

Topic 5: Enumerated Types and Switch Statements

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

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

CS 302 Week 9. Jim Williams

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

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

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

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

CS 177 Week 15 Recitation Slides. Review

CSCI 1103: Input with TextIO

Object-Oriented Programming

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really

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

We would like guidance on how to write our programs beyond simply knowing correlations between inputs and outputs.

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

CP122 CS I. Iteration

Computer Science is...

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Java Programming Language. 0 A history

Lecture Transcript While and Do While Statements in C++

Transcription:

CS 211: Methods, Memory, Equality Chris Kauffman Week 2-1

So far... Comments Statements/Expressions Variable Types little types, what about Big types? Assignment Basic Output (Input?) Conditionals (if-else) Iteration (loops) Aggregate data (arrays) Function Declarations (main) Library System

Functions / Methods Are parameterized code Referred to as methods in java jargon Give me some stuff (arguments) I ll give you something back (return value) Java: specify types for arguments and return User return to finish function and give value back Immediately ends function (even inside loop) Useful for project 1

Method Basics Live inside classes, see MethodDemo.java public class MethodDemo{ // Sum up an array public static int sumintarray(int a[]){ int sum = 0; for(int i=0; i<a.length; i++){ sum += a[i]; return sum;... For now, use the magic word static for functions Omitting static changes the meaning of functions significantly We ll start doing that soon

Legacy of the void Sometimes a method gives nothing as an answer. Return type is void In void methods, return is optional public static void downhere(){ System.out.println("Calling down here"); // no return required static int anumber = 0; public static void maybeincrease(int myarg){ if(myarg <= 0){ return; // return immediately anumber++; System.out.println(aNumber); return; // optional return

Playing with Functions It s easy to play with static functions in DrJava s interactive loop. Make sure to use ClassName.functionName(param,parm2). Welcome to DrJava. Working directory is... > HighlyComposite.numDivisors(5) 2 > HighlyComposite.numDivisors(6) 4 > HighlyComposite.numDivisors(8) 4 > HighlyComposite.highlyComposite(6) true > HighlyComposite.highlyComposite(8) false >

Early Exit from Code Blocks Based on structure of code, may want to end some execution early break; immediately finishes the loop in which it is placed return; or return answer; immediately finishes the method in which it appears

break Exits a Loop int guess, correct = 22; while(true){ guess = input.nextint(); if(guess == correct){ System.out.println("You guessed right"); break; System.out.println("You guessed wrong"); System.out.println("Game over"); There is also a continue which skips to the next loop iteration which is sometimes useful

return Exits a Method // Locate the index at which the integer // query appears in the array arr; throw // an exception if query is not present public static int locate(int [] arr, int query){ for(int i=0; i<arr.length; i++){ if(arr[i] == query){ return i; throw new RuntimeException("query "+query+" not in array");

What s the difference between #1 and #2? Defined Used public static void doubler1(int x){ x = 2*x; public static void doubler2(int x[]){ x[0] = 2*x[0]; public static void main(string args[]){ int r = 10; int s[] = {20; doubler1(r); System.out.println(r); doubler2(s); System.out.println(s[0]); Code is in Doubler.java To understand the difference, we need to draw memory diagrams of the function call stack and heap

Two Kinds of types: Primitive and References Primitives Little types are primitives int, double, char, boolean, long, short, float... Live directly inside a memory cell Each primitive type has its own notion of a zero value: know what they are as all arrays are initialized to these values Only a small number of primitive types, can t make new ones References Big types including types you ll create String, Scanner, File, Sauce, Exception,... And all arrays Contents of memory cell refer to another spot in memory where the thing actually resides Usually refer to a heap location Identical to a pointer but operations are limited Have a single zero-value: null which points nowhere

Another Tricky Example What s the difference? What gets printed? Defined Used public static boolean intequals1(int x, int y){ return x==y; public static boolean intequals2(int x[], int y[]){ return x==y; public static void main(string args[]){ boolean result; int a=1, b=1; result = intequals1(a,b); System.out.println(result); int aa[]={20, bb[]={20; result = intequals2(aa,bb); System.out.println(result); result = aa==bb; System.out.println(result);

Equality == does shallow comparisons: compare the contents of two memory boxes. Many times this is not what is desired Instead want a deep comparison which compares multiple parts For that will typically have x.equals(y) methods Can also write static functions that do similar things Array Equality Write a function public static boolean intarrayequals(int x[], int y[]) which checks whether two integer arrays are deeply equal to one another. Write a function public static boolean intarrayidentical(int x[], int y[]) which checks whether two integer arrays are the same array.

Array and Function Practice Good exercises: functions that manipulate arrays BJP4 Self-Check 7.28: arraymystery5 BJP4 Exercise 7.6: stdev BJP4 Exercise 7.12: priceisright BJP4 Exercise 7.13: longestsortedsequence