CS1001 Lecture 14.

Slides:



Advertisements
Similar presentations
1 CS1001 Lecture Overview Java Programming Java Programming.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
JavaScript, Third Edition
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CSC Programming I Lecture 5 August 30, 2002.
Sahar Mosleh California State University San MarcosPage 1 A for loop can contain multiple initialization actions separated with commas Caution must be.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CPS120: Introduction to Computer Science Operations Lecture 9.
Data Types, Variables, and Arithmetic JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
1 CS1001 Lecture Overview Java Programming Java Programming Arrays Arrays.
Data Types, Variables, and Arithmetic Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
Variables, Operators, and Expressions
Information and Computer Sciences University of Hawaii, Manoa
Expressions and Assignment Statements
Array in C# Array in C# RIHS Arshad Khan
Selection (also known as Branching) Jumail Bin Taliba by
More important details More fun Part 3
EGR 2261 Unit 4 Control Structures I: Selection
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
The Selection Structure
Arrays, 2-D Arrays, and ArrayList
User input We’ve seen how to use the standard output buffer
Lecture 07 More Repetition Richard Gesick.
Java Programming: From Problem Analysis to Program Design, 4e
Stack Data Structure, Reverse Polish Notation, Homework 7
Arrays, For loop While loop Do while loop
Object Oriented Programming COP3330 / CGS5409
Expressions Chapter 4 Copyright © 2008 W. W. Norton & Company.
2.1 Parts of a C++ Program.
Java - Data Types, Variables, and Arrays
Chapter 2 Edited by JJ Shepherd
Chapter 2: Basic Elements of Java
A First Book of ANSI C Fourth Edition
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
Java Programming Arrays
Arrays in Java What, why and how Copyright Curt Hill.
C Operators, Operands, Expressions & Statements
Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays
3 Control Statements:.
Java Programming Control Structures Part 1
Arrays ICS2O.
Testing and Repetition
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
CISC/CMPE320 - Prof. McLeod
Expressions and Assignment
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Chapter 2: Introduction to C++.
Boolean Expressions to Make Comparisons
Data Structures and Algorithms Introduction to Pointers
Primitive Types and Expressions
Review of Previous Lesson
How do you do the following?
SPL – PS2 C++ Memory Handling.
Presentation transcript:

CS1001 Lecture 14

Overview Java Programming Arrays

Goals Understand the basics of Java programming Control Statements and Arrays

Assignments Brookshear: Ch 4, Ch 5 (Read) Read linked documents on these slides (slides will be posted in courseworks)

Arithmetic Operators: +, -, /, * , % The precedence of operators and parentheses work the same way as in algebra. m % n means the remainder when m is divided by n (e.g. 17 % 5 is 2). % has the same rank as / and * Same-rank binary operators are performed in order from left to right. *, /, and % have the same rank. There is also the unary operator -, e.g. a = -a; All unary operators have a higher rank than binary operators and are executed first.

Arithmetic (cont’d) The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions. If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int. If an expression has several binary operators of the same rank with no parentheses, the intermediate results are calculated from left to right. For example: x = a / b * c; is the same as temp = a / b; x = temp * c;

Arithmetic (cont’d) Caution: if a and b are ints, then a / b is truncated to an int… 17 / 5 gives 3 3 / 4 gives 0 …even if you assign the result to a double: double ratio = 2 / 3; This is another place to be very careful. Integer truncation can be useful, too. For example, find the whole number of weeks in a given number of days or the number of whole hours in a given number of minutes: int fullWeekCount = dayCount / 7; System.out.println(mins / 60 + " hours and " + mins % 60 + " minutes."); The double type of the result doesn’t help: ratio still gets the value 0.0.

Arithmetic (cont’d) To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2 / 3.0; double factor = (double) m / (double) n; double factor = m / (double) n; double r2 = k / 2.0; double r2 = (double) k / 2; Another reason for symbolic constants: if you declare a symbolic constant as a double, then casts to double are unnecessary and arithmetic errors are avoided. A few redundant casts are OK, and they make your code self-documenting. Casts

Arithmetic (cont’d) Caution: the range for ints is from -231 to 231-1 (about -2·109 to 2·109) Overflow is not detected by the Java compiler or interpreter n = 8 10^n = 100000000 n! = 40320 n = 9 10^n = 1000000000 n! = 362880 n = 10 10^n = 1410065408 n! = 3628800 n = 11 10^n = 1215752192 n! = 39916800 n = 12 10^n = -727379968 n! = 479001600 n = 13 10^n = 1316134912 n! = 1932053504 n = 14 10^n = 276447232 n! = 1278945280 109 is OK, but 1010 is already wrong. When you eventually overflow and hit the leftmost bit in an integer variable, the number becomes negative because this is the sign bit. 12 factorial is OK but 13 factorial is wrong, which is not immediately obvious if you don’t see the preceding factorial values. Java has a type long that uses eight bytes and can hold integer values from -263 to 263‑1.

Arithmetic (cont’d) Use compound assignment operators: a = a + b; a += b; a = a - b; a -= b; a = a * b; a *= b; a = a / b; a /= b; a = a % b; a %= b; Use increment and decrement operators: a = a + 1; a++; a = a - 1; a--; a = a + b; gives away a novice. But so does a += a + b++; Do not use these in larger expressions

Review: What is a variable? What is the type of variable that holds an object? What is a variable? A named container that can hold a value. What is the type of a variable that holds an object? The class to which the object belongs. What is meant by the scope of a variable? The area in the source code where the variable is visible. What is the scope of a field? The whole class. What is the scope of a local variable? From its declaration down to the closing brace of the block in which it is declared. Is it OK to give the same name to variables in different methods? Yes, and moreover it is desirable if their roles are similar. Is it OK to give the same name to a field and to a local variable of the same class? Never.

Review (cont’d): What is the range for ints? When is a cast to double used? Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? When is a cast to int used? Should compound assignment operators be avoided? What is the range for ints? from -231 to 231 - 1. When is a cast to double used? When the operands are ints but we want the correct result as a double. (Be sure to cast an individual operand, not the final result.) Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? 0 (5/9 gives 0 first, the rest doesn’t matter). When is a cast to int used? To truncate the double result of a calculation and store it in an int. Should compound assignment operators be avoided? On the contrary, they should be used, but not inside fancy expressions.

Objectives: Learn about arrays and when to use them Learn the syntax for declaring and initializing arrays Learn how to access array’s size and elements This chapter is only an introduction. More on arrays in Section 11.6, “Iterations and Arrays,” and in Chapter 12.

What is an Array An array is a block of consecutive memory locations of the same data type. Individual locations are called array’s elements. Sometimes when we say “array’s element” we mean the value stored in that element. There is indeed some confusion in the usage of “element.” In some situations, the word refers to the location in an array, as in “set the value of the k-th element.” In other situations it refers to a value stored in the array, as in “find the smallest element.” This dual usage is somewhat similar to the situation with the term “variable.” This is no big deal, as long as everyone understands the difference between a location and a value stored in it. 1.39 1.69 1.74 0.0 An array of doubles

What is an Array (cont’d) Rather than treating each element as a separate named variable, the whole array gets one name. Specific array elements are referred to by using array’s name and the element’s number, called index or subscript. The idea is not to save names, of course, but to be able to handle an array’s elements uniformly, using algorithms. 1.39 1.69 1.74 0.0 o is array’s name c[0] c[1] c[2] c[3]

Indices (Subscripts) In Java, an index is written within square brackets following array’s name (e.g., a[k]). Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1]. An index can have any int value from 0 to array’s length - 1. The convention of starting indices from 0 comes from C. It is easy to get used to.

Indices (cont’d) We can use an int variable or any expression that evaluates to an int value as an index: a [3] a [k] a [k - 2] a [ (int) (6 * Math.random()) ] That’s the beauty of it: the index may be a variable calculated at run time; it can be used in algorithms.

Indices (cont’d) In Java, an array is declared with fixed length that cannot be changed. Java interpreter checks the values of indices at run time and throws IndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1. arr = new int[newSize]; does not really resize arr: it simply throws away the old array and allocates a new one with default values. “Throws an exception” means reports a run-time error with rather detailed information about where in the code it occurred and aborts the program.

Why Do We Need Arrays? The power of arrays comes from the fact that the value of a subscript can be computed and updated at run time. Before (no arrays): After (with arrays): int sum = 0; sum += score0; sum += score1; … sum += score999; int n = 1000; int sum = 0, k; for (k = 0; k < n; k++) sum += scores[k]; Without arrays it would be difficult to process a collection of items algorithmically. Difficult but possible: with linked lists (one of the subjects in Java Methods AB). 1000 times!

Why Arrays? (cont’d) Arrays give direct access to any element — no need to scan the array. Before (no arrays): After (with arrays): if (k == 0) display (score0); else if (k == 1) display (score1); else … // etc. display (scores[k]); “Direct access” means you can go directly to where the item is stored (like a particular track on a CD), as opposed to scanning from the beginning to find an item (as on a tape).

Arrays as Objects In Java, an array is an object. If the type of its elements is anyType, the type of the array object is anyType[ ]. There are two ways to declare an array: The difference becomes significant only when several variables are declared in one statement: int [ ] a, b; // both a, b are arrays int a [ ], b; // a is an array, b is not anyType [ ] arrName; This has several implications: you have to create (initialize) it before you can use it, it is passed to methods as a reference, etc. You can pass an array to any method that expects an Object type of argument. If you want to test it, try: Object x = new int[100]; or anyType arrName [ ];

Arrays as Objects (cont’d) As with other objects, the declaration creates only a reference, initially set to null. An array must be created before it can be used. There are two ways to create an array: arrName = new anyType [ length] ; Brackets, not parens! The second form, with a list of initial values, is not in the AP subset. or arrName = new anyType [ ] { val1, val2, …, valN };

Declaration and Initialization When an array is created, space is allocated to hold its elements. If a list of values is not given, the elements get the default values. scores = new int [10] ; // length 10, all values set to 0 words = new String [10000]; // length 10000, all values set to null As for fields: 0 for numbers, false for booleans, null for objects. The elements get default values even if an array is a local variable. You can think of an array’s elements as sort of like its “fields.”

Initialization (cont’d) An array can be declared an initialized in one statement: int scores [ ] = new int [10] ; // length 10 private double gasPrices [ ] = { 1.49, 1.69, 1.74 }; String words [ ] = new String [10000]; String cities [ ] = {"Atlanta", "Boston", "Cincinnati" }; Nothing new here: this is true for any object.

Initialization (cont’d) Otherwise, initialization can be postponed until later: String words [ ]; // not yet initialized ... words = new String [ console.readInt() ]; private double gasPrices [ ]; // not yet initialized … gasPrices = new double [ ] { 1.52, 1.69, 1.75 }; If you try to use it, (e.g., arr.length or arr[k]), you’ll get a null reference exception.

Array’s Length The length of an array is determined when that array is created. The length is either given explicitly or comes from the length of the {…} initialization list. The length of an array arrName is referred to in the code as arrName.length. length appears like a public field (not a method) in an array object. As opposed to String, where length() is a method.

Review: Why are arrays useful? What types of elements can an array have? How do we refer to an array’s element in Java? What happens if an index has an invalid value? How do we refer to the length of an array? Why are arrays useful? They allow a program to process a collection of related values algorithmically. What types of elements can an array have? Any data type that a variable can have. How do we refer to an array element in Java? whateverArrayName[index]. What happens if an index has an invalid value? The program reports a run-time error (throws IndexOutOfBoundsException). How do we refer to the length of an array? whateverArrayName.length

Sorting

Alternate Sorting Algorithm (Selection Sort) main(String[] args) { int inputSize = args.length; int[] sortedArray = new int[inputSize]; for (i=0; i < inputSize; i++) { (1) Loop through args, find largest element and remember its index (ie for (int j = 0; …)) (2) Put the largest element into the ith location of sortedArray; (3) Delete (set to -1) the ith element of args } http://www.ee.unb.ca/brp/lib/java/selectionsort/