Introduction to Object-Oriented Programming

Similar documents
Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming

Classes Classes 2 / 35

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

Classes Classes 2 / 36

Introduction to Object-Oriented Programming

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

CS 2340 Objects and Design - Scala

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

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

Practice Midterm 1. Problem Points Score TOTAL 50

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

4CCS1PRP, Programming Practice 2012 Lecture 6: Arrays - Part 1

Introduction to Object-Oriented Programming

Java Programming: from the Beginning

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

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

CSSE 220 Day 8. Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop. Check out ArraysAndLists from SVN

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

CSSE 220. Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop. Check out ArraysListPractice from SVN

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

CIS133J. Working with Numbers in Java

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

egrapher Language Reference Manual

Arrays. Eng. Mohammed Abdualal

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

Handout 4 Conditionals. Boolean Expressions.

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

CSE 214 Computer Science II Java Classes and Information Hiding

CIS*2430 (Fall 2012) Miterm Exam (I) Solutions

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

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

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Introduction to Object-Oriented Programming

*Java has included a feature that simplifies the creation of

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

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

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

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

COSC 123 Computer Creativity. Java Lists and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Java Programming Language. 0 A history

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

Introduction to Programming Using Java (98-388)

CS 1316 Exam 1 Summer 2009

Flow of Control: Loops. Chapter 4

Give one example where you might wish to use a three dimensional array

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved.

Arrays in Java Using Arrays

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

CS 2340 Objects and Design

CSE 142 Su01 Final Exam Sample Solution page 1 of 7

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

Full file at

Java Identifiers, Data Types & Variables

Getting started with Java

CSE 374 Programming Concepts & Tools

Pace University. Fundamental Concepts of CS121 1

CS111: PROGRAMMING LANGUAGE II

CS1150 Principles of Computer Science Arrays

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Values and Variables 1 / 30

CONDITIONAL EXECUTION

CHAPTER 7 OBJECTS AND CLASSES

CSC 1214: Object-Oriented Programming

Introduction to Object-Oriented Programming

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

Classes. 1 Data Abstraction. 2 A Complex Number ADT

CIS 110 Fall 2016 Introduction to Computer Programming 13 Oct 2016 Midterm Exam Answer Key

17 Hello world 18 Type: String: literal 19 Standard API: System: out.println() 20 Hello world 21 Statement 22 Statement: simple statements are ended w

CP122 CS I. Iteration

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

EXERCISES SOFTWARE DEVELOPMENT I. 04 Arrays & Methods 2018W

Lecture 3. Lecture

Controls Structure for Repetition

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

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Arrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops)

CS260 Intro to Java & Android 03.Java Language Basics

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

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.

JAVA OPERATORS GENERAL

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar

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

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

COMP 110 Introduction to Programming. What did we discuss?

CS 231 Data Structures and Algorithms, Fall 2016

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

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

Introduction to Object-Oriented Programming

Clean Formatting. Christopher Simpkins Chris Simpkins (Georgia Tech) CS 2340 Objects and Design CS / 1

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

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

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

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.

CMPT 125: Lecture 3 Data and Expressions

1 Lexical Considerations

CS 106 Introduction to Computer Science I

Building Java Programs

Transcription:

Introduction to Object-Oriented Programming Arrays, Part 1 of 2 Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Arrays, Part 1 of 2 1 / 14

Modeling Aggregates As you ve seen, you can get pretty far with "scalar" data. But many phenomena we wish to model computationally are aggregates, or collections, for example: scores on assignments in a class, word counts in a document, or pixel colors in a bitmap image. Today we ll learn Java s most basic facility for modeling such phenomena: arrays. CS 1331 (Georgia Tech) Arrays, Part 1 of 2 2 / 14

Arrays Java Arrays (JLS 10): are objects, are dynamically allocated (e.g., with operator new), and have a fixed number of elements of the same type. CS 1331 (Georgia Tech) Arrays, Part 1 of 2 3 / 14

Creating Arrays Consider the following array creation expression (JLS 10.3): double[] scores = new double[5]; This declaration: allocates a 5-element array, the 5 in the example above can be any expression that is unary promotable to an int (JLS 5.6.1) stores the address of this new array in scores, and initializes each value to it s default value (0 for numeric types, false for boolean types, and null for references, JLS 4.12.5). CS 1331 (Georgia Tech) Arrays, Part 1 of 2 4 / 14

Array Declarations The preceding array definition double[] scores = new double[5]; could be split into a declaration and initialization: double[] scores; scores = new double[5]; Also, you can put the [] on the type or the variable name when delaring an array. These two declarations are equivalent: double[] scores; double scores[]; Generally, it s better style to put the [] on the type. CS 1331 (Georgia Tech) Arrays, Part 1 of 2 5 / 14

Mixed Declarations Note that you can mix aray declarations with declarations of variables having the same element type. The declaration line: double scores[], average; creates an array of double reference named scores, and a double variable named average What s the size of the scores array declared above? CS 1331 (Georgia Tech) Arrays, Part 1 of 2 6 / 14

Array Objects After the definition: double[] scores = new double[5]; scores points to an array object in memory that can be visualized as: 0 1 2 3 4 0.0 0.0 0.0 0.0 0.0 The indexes of scores range from 0 to 4. The size of arrays are stored in a public final instance variable named length scores.length == 5; What is the type and value of the expression above? CS 1331 (Georgia Tech) Arrays, Part 1 of 2 7 / 14

Accessing Array Elements Array elements are accessed with an int-promotable expression enclosed in square brackets ([]) double[] scores = new double[5]; scores[0] = 89; scores[1] = 100; scores[2] = 95.6; scores[3] = 84.5; scores[4] = 91; scores[scores.length - 1] = 99.2; Will this line compile? If so, what will happen at runtime? scores[scores.length] = 100; CS 1331 (Georgia Tech) Arrays, Part 1 of 2 8 / 14

Initializing Arrays You can provide initial values for (small) arrays String[] validsuits = {"diamonds", "clubs", "hearts","spades"; What is validsuits.length? What is validsuits[1]? You can also use a loop to initialize the values of an array: int[] squares = new int[5]; for (int i = 0; i < squares.length; ++i) { squares[i] = i*i; What is squares[4]? CS 1331 (Georgia Tech) Arrays, Part 1 of 2 9 / 14

Traversing Arrays Arrays and for statements go hand-in-hand: double[] scores = new double[5]; for (int i = 0; i < 5; ++i) { System.out.printf("scores[%d] = %.2f%n", i, scores[i]); You can also use the enhanced for loop: for (double score: scores) { System.out.println(score); Read the enhanced for loop as for each element of the array.... Why use for-each instead of traditional for?... CS 1331 (Georgia Tech) Arrays, Part 1 of 2 10 / 14

Traditional for Versus for-each In cases where you don t need the index, use the enhanced for loop. Consider: double sum = 0.0; for (int i = 0; i < scores.length; ++i) { sum += scores[i]; In the code above, scores.length is used only for bounding the array traversal, and the index i is only used for sequential array access. Those are two things we can mess up. The enhanced for loop is cleaner: double sum = 0.0; for (double score: scores) { sum += score; Also note how our naming conventions help to make the code clear. You can read the loop above as for each score in scores. CS 1331 (Georgia Tech) Arrays, Part 1 of 2 11 / 14

Array Initialization and Access Gotchas Because arrays are allocated dynamically, this will compile: double[] scores = new double[-5]; but will produce an error at run-time: Exception in thread "main" java.lang.negativearraysizeexception at ArrayBasics.main(ArrayBasics.java:4) Also, array access expressions are evaluated and checked at run-time. So, in the same way that accessing an array with an index the size of the array produces a run-time error, negative indexes like: scores[-1] = 100; produce: Exception in thread "main" java.lang.arrayindexoutofboundsexception: -1 at ArrayBasics.main(ArrayBasics.java:23) CS 1331 (Georgia Tech) Arrays, Part 1 of 2 12 / 14

Arrays as Method Parameters - main We ve already seen an array parameter: public static void main(string[] args) We can use this array just like we use any other array. public class Shout { public static void main(string[] args) { for (String arg: args) { System.out.print(arg.toUpperCase() + " "); System.out.println(); See also CourseAverage.java CS 1331 (Georgia Tech) Arrays, Part 1 of 2 13 / 14

Closing Thoughts Arrays are our first collection classes (but are not Java Collection classes). Arrays are objects, so array objects are created with operator new and array variables can have the value null. Arrays have sugar to add convenience and make them syntactically similar to C s arrays. CS 1331 (Georgia Tech) Arrays, Part 1 of 2 14 / 14