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

Size: px
Start display at page:

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

Transcription

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

2 Announcements Assignment 2 posted and due on 30 th of May (23:30). Extra class tomorrow - 13:05 to 15:25 in TR0100. Midterm Exams : June 4 th (12:35 14:35) Rooms : 1B45 and 306 (Burnside) Final Exams : June 26 th (14:00 17:00) Room : MAAS 112

3 Review Loops 1. In a group of nested loops, which loop is executed the most number of times? A. The outermost loop B. The innermost loop C. All loops are executed same number of times Answer B 2. What value is stored in x at the end of this loop? for (x = 1; x <= 5; x++) A. 1 B. 4 C. 6 D. 5 Answer C

4 Review While Loops int x = 0; Step 1 Initialize Condition Fail while (x < 4) { } System.out.println("Write this again"); x++; Step 2 Condition Check Step 3 Loop body Execution Once the condition fails

5 For Loops for (int x = 0; x < 4; x++) { Step 1 Initialize Step 2 Condition Check Review Step 4 Update Condition Fail System.out.println("Write this again"); Step 3 Loop body Execution } Once the condition fails

6 Review Array of Scores of 8 students: int [ ] scores = {100, 95, 25, 99, 39, 100, 100, 90} scores Indices [0] [1] [2] [3] [4] [5] [6] [7] Here is an array with 8 values in it. Each spot of the array has a value and an index. The value is any legitimate value of the type of the array, in this case int. The index is an integer. Interestingly the counting starts from 0 instead of 1. To get or set values of an array, we will use a similar syntax to a normal variable, except we have to specify which value of the array we wish to get or set. We do this by using the index.

7 Creating Array (Method 1) int[] myarray = {1, 5, 6, 3}; Review 1) Allocate this memory. Find a free spot in memory that has enough space to hold four integers. 2) Store the address of the beginning of the memory that was just allocated into the variable myarray. myarray 3) Set values to this newly allocated memory. myarray

8 Review Creating Array (Method 2) This method is useful when we don t know the values that needs to be saved in the array: int[] myarray; Variable myarray is created to point to an array. myarray = new int[4]; myarray myarray[0] = 1; myarray Indices 1 [0] [1] [2] [3]

9 This Lecture Reference Types Reference vs Primitive Types Multidimensional Arrays Methods One step at a time.

10 Adding to our vocabulary - break break is used to stop the execution of a loop before all the iterations are completed. Example: int i; for(i=0; i<10;i++) { if(i==5) break; } System.out.println(i); break statement is useful in situations like searching in an array for a value and exiting the loop once we find it.

11 Objects Arrays, Scanners, and Strings are Objects. You can tell because you need new to create them. (Well, except Strings. Strings are special.) In fact, except for the primitive data types (the ones that start with lowercase, like int, double, float, byte, boolean, etc.), everything in Java is an Object. Objects are data bundled with methods to work with the data, and properties.

12 Methods and Properties of Objects Some String methods:.equals(),.length(),.tolowercase() Some Scanner methods:.nextline(),.nextint(),.nextdouble() In general: object.method_name() Arrays have no methods. Instead, they have a property called length.length Because this is not a method, there is no () after

13 Reference Types

14 Reference Types vs Primitive Types When we write int x = 10; 10 x what we are technically doing is the following: 1) Creating a space in memory that will store an int 2) Specifying that whenever we use the identifier x later in our program, we want to access that memory location. 3) Storing the value of 10 into that memory location.

15 Objects Using Reference Types The variables of objects, including arrays, don't directly store the values of the objects. Instead, they store a reference to the location in memory containing the value. Think of this as storing an address, which points to where the data is actually located in memory.

16 When we write Reference Types vs Primitive Types int x[] = {10, 3, 5}; what we are technically doing is the following: 1) Creating a space in memory that will store the address of an int array. 2) Specifying that whenever we use the identifier x later in our program, we want to access that space in memory (which stores an address). 3) Creating an array somewhere else in memory. That array will store the values 10, 3, and 5 and have length of 3. That array must be located somewhere in memory. Call that address a. 4) Setting the value of x to be a (In other words, the value of a is stored into the space of memory reserved for the variable x).

17 Why references can get Confusing? There are some interesting consequences of storing addresses into variables instead of the values int[] x = {1, 2, 3}; int x = 5; int[] y = x; int y = x; y[0] = 2; y = 10; System.out.println(x[0]); System.out.println(x); What will the above print? 1. 2! Because changing y[0] also changes x[0]. x and y are reference types Because x and y are primitive types in here.

18 Addresses One Step at a time Memory Values int[] x = {1,2,3} The {1, 2, 3} creates an array in memory. The address of the start of this spot in memory is 1000.

19 Addresses One Step at a time Memory Values int[] x = {1,2,3} int[] x creates a variable of type int array. This means we create space in memory to store the address of an int array. In this case, we use the storage space in memory of 2004, to store the address x

20 Addresses One Step at a time Memory Values int[] x = {1,2,3} int[] y = x; x y This means: 1) Create space in memory to store an int[] variable 2) Store into that int[] variable the value of the expression x

21 Addresses One Step at a time Memory Values int[] x = {1,2,3} int[] y = x; y[0] = 2; x y This means: 1) Assign to the first value of the array referred to by y, the value of the expression 2

22 Can also be seen as x y int[] x = {1,2,3} int[] y = x; y[0] = 2;

23 Consequences: Equality int[] arr1 = {1, 2, 3}; int[] arr2 = {1, 2, 3}; System.out.println(arr1 == arr2); Here the addresses stored in arr1 and arr2 variables are getting compared. Not the values. This is also why we have to use.equals() to compare the values of Strings.

24 Why so Confusing!!? Why would one EVER make things so complicated? It turns out there are some very good reasons that will be crucial to the idea of object oriented programming. One useful feature is the ability to pass addresses of data means it's easier to share (and modify!) data between methods! We will see an example about how this helps once we learn about methods.

25 Try it out!! Write some code that actually copies an array of ints (i.e., not just make it point to the same part of memory). e.g., int[] arr1 = {1, 4, 3, 6, 7}; int[] arr2; // make arr2 have a copy of the data in arr1

26 Common Array Problems 1 Referring to an index that doesn't exist. ArrayIndexOutOfBounds exception int[] x = {1, 2, 3}; System.out.println(x[-1]); System.out.println(x[3]);

27 Common Array Problems 2 Trying to do operations on a null pointer. NullPointerException String[] names = new String[35]; System.out.println(names[0].length());

28 Multidimensional Arrays So far, the elements of all the arrays we have seen have been simple values: primitive types or Strings. Such arrays are one-dimensional However, we can create arrays whose elements are themselves one-dimensional arrays Such an array is really an array of arrays These arrays are two-dimensional arrays (or 2D arrays)

29 Two Dimensional Arrays Elements in a two dimensional array are accessed using two indices. The first index specifies the one-dimensional array containing the element we want to access. The second index specifies the element we want to access within the one-dimensional array specified by the first index.

30 Creating 2D Arrays To create an array using an initializer list, you could write: type[] variablename = {exp1, exp2, exp3,...}, where exp1, exp2, exp3, etc all evaluated to type Well, in this case type is just an array. But we need array of arrays, int[][] board = { {1,2,3}, {1,4}, {6,2} } This is creating an array of int[]. The first array in the array is {1,2,3} the second is {1,4} and the third is {6,2}

31 Creating a 2D Array int[][] board = { {1,2,3}, {1,4}, {6,2} } board board[0] board[1] board[2] We can use new operator to create multidimensional arrays. Example: type[][] variablename= new type[size_1][size_2];

32 Accessing a 2D Array int[][] x = new int[3][4]; //creates an array which contains 3 arrays of size 4. x[0][1] = 3; //assigns to the 2nd spot of the 1st array, the value 3; x[2][3] = 10; //assigns to the 4th spot of the 3rd array, the value of 10; x[10][2] = 5; //causes an array out of bounds exception int[] y = x[2]; //stores into y the address of the 3rd array

33 Two Dimensional Arrays What would be printed??? int [][] x = {{1,2,3},{4,5,2,7},{9,3,5,2,6}}; System.out.println(x.length); System.out.println(x[2].length); System.out.println(x[0]); System.out.println(x[0][1]);

34 String (More about Strings)

35 String vs char[] A String is just a fancy version of char[] both store an array of char values. A String has in addition: Useful methods like.equals(),.tolowercase() A special way to be created, using "" syntax (So we don't have to go {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd'} as for a char[].)

36 More String Methods.charAt(int i) Gets the ith char of a String (starting from 0).substring(int a, int b) Gets the substring starting at position a ending just before position b..compareto(string other).indexof(char c).tolowercase().touppercase() Tells you which String comes first, orthographically. Gets the index of the first occurrence of c Gets a lower-case version of the String. Gets an upper-case version of the String

37 A Note on Describing Methods When you see something like:.substring(int a, int b) This means this is a method that: 1. takes two inputs (or arguments, parameters). 2. the first is of type int 3. the second is of type int as well You call the method by: "some string".substring(1, 4) The "int"s are just there as reminders. Don't type them in!

38 Try it out!! Write some code that turns a String into a format that is like a name i.e., the first letter is capitalized, and all subsequent ones are not. "bob" "Bob" "BOB" "Bob" "BoB" "Bob" "bob" "Bob" Hint: use the methods Character.isLowerCase(char ch) and/or Character.isUpperCase(char ch) to check the case of a char.

39 Caesar Cipher Used in the ancient Roman army to obscure important messages ATTACKATMIDNIGHT* DWWDFNDWPLGQLJKW Encrypt by shifting all letters by three positions A (1 st letter) D (4 th letter) T (20 th letter) W (23 rd letter) *Ancient Romans didn't use lowercase letters, or spaces

40 Try it out!! Implement the encryption algorithm for a Caesar cipher Steps: Read each character of plaintext (String.charAt(int i)) Convert it to its numerical value (by casting) Add 3 Tricky: implement wrap-around (e.g., Z C) Convert it back to a char, and save it or print it out

41 String[] args So what exactly is args there for? public static void main(string[] args) Another way to pass input data to a program Command line: java NameOfClass arg1 arg2 argn DrJava: run NameOfClass arg1 arg2 argn Examples of uses: Name of file to open when you run the program

42 Command-line Calculator This program takes three arguments. The first represents an int, the second is a single character, in {'+', '-', '*', or '/'}, and the third is another int. It prints the result of computing the calculation. e.g., run Calc run Calc 88 / 5 17 run Calc 2 *

43 Methods

44 Calling Methods You have been calling a lot of methods already Some examples? String.equals() String.length()

45 Using Java Libraries The JDK comes with many libraries, which contain classes and methods for you to use. String library Math library Swing library (used for graphics) Libraries for networking

46 Math Library Contains useful and common methods you can use off-the-shelf (i.e., don't have to write yourself) Also, constants like E or PI How do you access them? import java.lang.math;

47 Documentation Read the Application Programming Interface (API) for the specification of a library. e.g., Math library: html What information do you get from an API?

48 Sample Entry static double abs(double a) Returns the absolute value of a double value. Name of the method

49 Sample Entry static double abs(double a) Returns the absolute value of a double value. The number and type of input arguments The name of the method together with the number and type of input arguments is called the signature of the method.

50 Sample Entry static double abs(double a) Returns the absolute value of a double value. Description of what the method does.

51 Sample Entry static double abs(double a) Returns the absolute value of a double value. The return type of the method

52 Sample Entry static double abs(double a) Returns the absolute value of a double value. This keyword means this method does not have to be called on a particular object. Don't worry too much about it for now.

53 Sample Entry static double abs(double a) Returns the absolute value of a double value. Based on this API entry, we know that we call use this method with something like: Math.abs(-4.0) and that this expression evaluates into the value 4.0 with type double.

54 Sample Entry static double abs(double a) Returns the absolute value of a double value. We also know that Math.abs("5.0") would result in an error.

55 Try it out!! Give the input arguments (with types), and return types of the following Math library methods, and describe what they do. Math.pow Math.random Math.max

56 Summary Reference Types Multidimensional Arrays Introduction to Methods

COMP-202: Foundations of Programming. Lecture 7: Strings and Methods Jackie Cheung, Winter 2015

COMP-202: Foundations of Programming. Lecture 7: Strings and Methods Jackie Cheung, Winter 2015 COMP-202: Foundations of Programming Lecture 7: Strings and Methods Jackie Cheung, Winter 2015 Announcements Quiz 2 due tonight at 11:59pm New grades policy: lowest quiz mark dropped Assignment 2 due in

More information

COMP-202: Foundations of Programming. Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016 Review: for Loops for (initialization; condition; update) { Happens once per loop only, before the first check

More information

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice CONTENTS: Arrays Strings COMP-202 Unit 5: Loops in Practice Computing the mean of several numbers Suppose we want to write a program which asks the user to enter several numbers and then computes the average

More information

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.

More information

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 4: Methods Jackie Cheung, Winter 2016 Announcements Quiz 1 postponed: Due Jan 26 at 11:59pm Assignment 1 postponed: Due on Feb 1 at 11:59pm 2 Review What is

More information

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

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon

More information

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue General Loops in Java Look at other loop constructions Very common while loop: do a loop a fixed number of times (MAX in the example) int

More information

Last Class. More on loops break continue A bit on arrays

Last Class. More on loops break continue A bit on arrays Last Class More on loops break continue A bit on arrays public class February2{ public static void main(string[] args) { String[] allsubjects = { ReviewArray, Example + arrays, obo errors, 2darrays };

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 13: Recursion Sandeep Manjanna, Summer 2015 Announcements Final exams : 26 th of June (2pm to 5pm) @ MAASS 112 Assignment 4 is posted and Due on 29 th of June

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb 9 2006 based on slides by Kurt Eiselt http://www.cs.ubc.ca/~tmm/courses/cpsc111-06-spr

More information

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

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

COMP 250 Winter 2011 Reading: Java background January 5, 2011

COMP 250 Winter 2011 Reading: Java background January 5, 2011 Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP

More information

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

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]

More information

Java Classes: Math, Integer A C S L E C T U R E 8

Java Classes: Math, Integer A C S L E C T U R E 8 Java Classes: Math, Integer A C S - 1903 L E C T U R E 8 Math class Math class is a utility class You cannot create an instance of Math All references to constants and methods will use the prefix Math.

More information

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent Programming 2 Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent information Input can receive information

More information

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a Spring 2017 Name: TUID: Page Points Score 1 28 2 18 3 12 4 12 5 15 6 15 Total: 100 Instructions The exam is closed book, closed notes. You may not use a calculator, cell phone, etc. i Some API Reminders

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

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

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

CS 251 Intermediate Programming Java Basics

CS 251 Intermediate Programming Java Basics CS 251 Intermediate Programming Java Basics Brooke Chenoweth University of New Mexico Spring 2018 Prerequisites These are the topics that I assume that you have already seen: Variables Boolean expressions

More information

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

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011 Java Tutorial Ashkan Taslimi Saarland University Tutorial 3 September 6, 2011 1 Outline Tutorial 2 Review Access Level Modifiers Methods Selection Statements 2 Review Programming Style and Documentation

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

More information

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

McGill University School of Computer Science COMP-202A Introduction to Computing 1 McGill University School of Computer Science COMP-202A Introduction to Computing 1 Midterm Exam Thursday, October 26, 2006, 18:00-20:00 (6:00 8:00 PM) Instructors: Mathieu Petitpas, Shah Asaduzzaman, Sherif

More information

CS S-08 Arrays and Midterm Review 1

CS S-08 Arrays and Midterm Review 1 CS112-2012S-08 Arrays and Midterm Review 1 08-0: Arrays ArrayLists are not part of Java proper 08-1: Arrays Library class Created using lower-level Java construct: Array Arrays are like a stripped-down

More information

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class? Administration Objects and Arrays CS 99 Summer 2000 Michael Clarkson Lecture 6 Read clarified grading policies Lab 6 due tomorrow Submit.java files in a folder named Lab6 Lab 7 Posted today Upson Lab closed

More information

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

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming Exam 1 Prep Dr. Demetrios Glinos University of Central Florida COP3330 Object Oriented Programming Progress Exam 1 is a Timed Webcourses Quiz You can find it from the "Assignments" link on Webcourses choose

More information

COMP1006/ Summer Tutorial 1

COMP1006/ Summer Tutorial 1 COMP1006/1406 - Summer 2016 - Tutorial 1 Objectives: Basic Java programming: input, output, arrays, Strings, control flow. Play Computer [10 minutes] Each tutorial will have a play computer problem. In

More information

Example: Computing prime numbers

Example: Computing prime numbers Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will

More information

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want

More information

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

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005 Lecture 8 Classes and Objects Part 2 MIT AITI June 15th, 2005 1 What is an object? A building (Strathmore university) A desk A laptop A car Data packets through the internet 2 What is an object? Objects

More information

A Foundation for Programming

A Foundation for Programming 2.1 Functions A Foundation for Programming any program you might want to write objects functions and modules build bigger programs and reuse code graphics, sound, and image I/O arrays conditionals and

More information

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

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference

More information

CS 302: Introduction to Programming

CS 302: Introduction to Programming CS 302: Introduction to Programming Lectures 2-3 CS302 Summer 2012 1 Review What is a computer? What is a computer program? Why do we have high-level programming languages? How does a high-level program

More information

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

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

COMP-202: Foundations of Programming. Lecture 10: Method Overloading and Passing Objects to Methods. Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 10: Method Overloading and Passing Objects to Methods. Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 10: Method Overloading and Passing Objects to Methods. Sandeep Manjanna, Summer 2015 Announcements Assignment 3: Due on 14 th of June at 11:30 pm. Midterm grades

More information

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Announcements PS 4 is ready, due next Thursday, 9:00pm Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Room TBD Scope: Lecture 1 to Lecture 9 (Chapters 1 to 6 of text) You may bring a sheet of paper (A4, both

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++ Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and

More information

Primitive vs Reference

Primitive vs Reference Primitive vs Reference Primitive types store values Reference types store addresses This is the fundamental difference between the 2 Why is that important? Because a reference type stores an address, you

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

G52CPP C++ Programming Lecture 3. Dr Jason Atkin G52CPP C++ Programming Lecture 3 Dr Jason Atkin E-Mail: jaa@cs.nott.ac.uk 1 Revision so far C/C++ designed for speed, Java for catching errors Java hides a lot of the details (so can C++) Much of C, C++

More information

Java Basic Programming Constructs

Java Basic Programming Constructs Java Basic Programming Constructs /* * This is your first java program. */ class HelloWorld{ public static void main(string[] args){ System.out.println( Hello World! ); A Closer Look at HelloWorld 2 This

More information

COMP-202: Foundations of Programming. Lecture 9: Classes and Objects Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 9: Classes and Objects Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 9: Classes and Objects Sandeep Manjanna, Summer 2015 Announcements Assignment 3: Due on 14 th of June at 11:30 pm. Small Software Glitch Costing Huge The spacecraft

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables COMP-202 Unit 2: Java Basics CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables Assignment 1 Assignment 1 posted on WebCt and course website.

More information

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016 More Tutoring Help The Engineering Peer Tutoring Services (EPTS) is hosting free tutoring sessions

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables COMP-202 Unit 2: Java Basics CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables Tutorial 0 Help with setting up your computer to compile and

More information

Lecture 15. Arrays (and For Loops)

Lecture 15. Arrays (and For Loops) Lecture 15 Arrays (and For Loops) For Loops for (initiating statement; conditional statement; next statement) // usually incremental { body statement(s); The for statement provides a compact way to iterate

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang Object Oriented Programming and Design in Java Session 2 Instructor: Bert Huang Announcements TA: Yipeng Huang, yh2315, Mon 4-6 OH on MICE clarification Next Monday's class canceled for Distinguished Lecture:

More information

Variables, Types, Operations on Numbers

Variables, Types, Operations on Numbers Variables, Types, Operations on Numbers CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Updated 9/6/16 1 Summary Variable declaration, initialization,

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

BM214E Object Oriented Programming Lecture 7

BM214E Object Oriented Programming Lecture 7 BM214E Object Oriented Programming Lecture 7 References References Revisited What happens when we say: int x; double y; char c;??? We create variables x y c Variable: Symbol plus a value Assume that we

More information

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

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

VARIABLES AND TYPES CITS1001

VARIABLES AND TYPES CITS1001 VARIABLES AND TYPES CITS1001 Scope of this lecture Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Primitive types Every piece of data

More information

Practice exam for CMSC131-04, Fall 2017

Practice exam for CMSC131-04, Fall 2017 Practice exam for CMSC131-04, Fall 2017 Q1 makepalindrome - Relevant topics: arrays, loops Write a method makepalidrome that takes an int array, return a new int array that contains the values from the

More information

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

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software. CISC-124 20180129 20180130 20180201 This week we continued to look at some aspects of Java and how they relate to building reliable software. Multi-Dimensional Arrays Like most languages, Java permits

More information

COMP-202: Foundations of Programming

COMP-202: Foundations of Programming COMP-202: Foundations of Programming Lecture 3: Basic data types Jackie Cheung, Winter 2016 Review: Hello World public class HelloWorld { } public static void main(string[] args) { } System.out.println("Hello,

More information

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS 152: Data Structures with Java Hello World with the IntelliJ IDE CS 152: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Electrical and Computer Engineering building

More information

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Primitive Data, Variables, and Expressions; Simple Conditional Execution Unit 2, Part 1 Primitive Data, Variables, and Expressions; Simple Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Overview of the Programming Process Analysis/Specification

More information

Assignment 2.4: Loops

Assignment 2.4: Loops Writing Programs that Use the Terminal 0. Writing to the Terminal Assignment 2.4: Loops In this project, we will be sending our answers to the terminal for the user to see. To write numbers and text to

More information

Variables and Java vs C++

Variables and Java vs C++ Variables and Java vs C++ 1 What can be improved? (variables) public void godirection(string directionname) { boolean wenttoroom = false; for (Direction direction : currentroom.getdirections()) { if (direction.getdirectionname().equalsignorecase(directionname))

More information

Variable initialization and assignment

Variable initialization and assignment Variable initialization and assignment int variable_name; float variable_name; double variable_name; String variable_name; boolean variable_name; Initialize integer variable Initialize floating point variable

More information

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8 CS 302: INTRODUCTION TO PROGRAMMING Lectures 7&8 Hopefully the Programming Assignment #1 released by tomorrow REVIEW The switch statement is an alternative way of writing what? How do you end a case in

More information

HW1 due Monday by 9:30am Assignment online, submission details to come

HW1 due Monday by 9:30am Assignment online, submission details to come inst.eecs.berkeley.edu/~cs61c CS61CL : Machine Structures Lecture #2 - C Pointers and Arrays Administrivia Buggy Start Lab schedule, lab machines, HW0 due tomorrow in lab 2009-06-24 HW1 due Monday by 9:30am

More information

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

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016 Announcements Final is scheduled for Apr 21, 2pm 5pm GYM FIELD HOUSE Rows 1-21 Please submit course evaluations!

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

PROGRAMMING STYLE. Fundamentals of Computer Science I

PROGRAMMING STYLE. Fundamentals of Computer Science I PROGRAMMING STYLE Fundamentals of Computer Science I Documentation and Style: Outline Meaningful Names Comments Indentation Named Constants Whitespace Compound Statements Documentation and Style Most programs

More information

Last Name: Circle One: OCW Non-OCW

Last Name: Circle One: OCW Non-OCW First Name: AITI 2004: Exam 1 June 30, 2004 Last Name: Circle One: OCW Non-OCW Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot

More information

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

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 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

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

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Writing a Simple Java Program Intro to Variables Readings Your textbook is Big Java (3rd Ed). This Week s Reading: Ch 2.1-2.5, Ch

More information

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

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

CSCI 355 Lab #2 Spring 2007

CSCI 355 Lab #2 Spring 2007 CSCI 355 Lab #2 Spring 2007 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Using Java Classes Fall 2018 Margaret Reid-Miller

Using Java Classes Fall 2018 Margaret Reid-Miller Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class

More information

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012) COE318 Lecture Notes: Week 3 1 of 8 COE318 Lecture Notes Week 3 (Week of Sept 17, 2012) Announcements Quiz (5% of total mark) on Wednesday, September 26, 2012. Covers weeks 1 3. This includes both the

More information

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

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

1 class Lecture2 { 2 3 Elementray Programming / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 41 / 68 Example Given the radius

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

Topics. Chapter 5. Equality Operators

Topics. Chapter 5. Equality Operators Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

More information

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

More information

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 Review What is the difference between a while loop and an if statement? What is an off-by-one

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

CSE 413 Final Exam. June 7, 2011

CSE 413 Final Exam. June 7, 2011 CSE 413 Final Exam June 7, 2011 Name The exam is closed book, except that you may have a single page of hand-written notes for reference plus the page of notes you had for the midterm (although you are

More information

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

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information