CSE 373. Data Types and Manipulation; Arrays. slides created by Marty Stepp

Similar documents
AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

AP Computer Science A. Return values

Lecture 6: While Loops and the Math Class

Building Java Programs

Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs

Building Java Programs

Building Java Programs

Topic 12 more if/else, cumulative algorithms, printf

Building Java Programs

Building Java Programs

AP Computer Science. Arrays. Copyright 2010 by Pearson Education

Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs

AP CS Java Syntax Summary: (version 4)

CS 112 Introduction to Programming

CS 112 Introduction to Programming

AP CS Java Syntax Summary: (version 3)

Topic 21 arrays - part 1

Building Java Programs

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

Midterm Exam 2 Thursday, November 15th, points (15% of final grade) Instructors: Jim Williams and Marc Renault

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CSE 143 Lecture 1. Arrays (review) slides created by Marty Stepp

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.

Redundant recipes. Building Java Programs Chapter 3. Parameterized recipe. Redundant figures

CS 112 Introduction to Programming

Building Java Programs Chapter 3

A variable is a name for a location in memory A variable must be declared

We now start exploring some key elements of the Java programming language and ways of performing I/O

Lecture 9: Arrays. Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp. Copyright (c) Pearson All rights reserved.

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

String is a Class; Quoted Text is an Object

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

C08c: A Few Classes in the Java Library (II)

Topic 23 arrays - part 3 (tallying, text processing)

CSE 331. Mutation and immutability

Building Java Programs

Topic 13 procedural design and Strings

Building Java Programs Chapter 4

Computational Expression

Lecture 8: The String Class and Boolean Zen

COMP102: Test. 26 April, 2006

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

Full file at

Lecture 4. Strings, Wrappers, & Containers

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Final Examination

Chapter 10: Text Processing and More about Wrapper Classes

AP Computer Science A

What did we talk about last time? Math methods boolean operations char operations

CITS1231 Web Technologies. JavaScript Math, String, Array, Number, Debugging

Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name:

Eng. Mohammed Abdualal

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

AP CS Java Syntax Summary: (version 5)

Class Library java.lang Package. Bok, Jong Soon

OOP-Lecture Java Loop Controls: 1 Lecturer: Hawraa Sh. You can use one of the following three loops: while Loop do...while Loop for Loop

Types and Expressions. Chapter 3

Computational Expression


Text processing. Readings: 4.4

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


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

Using Java Classes Fall 2018 Margaret Reid-Miller

Computer Science 145 Midterm 1 Fall 2016

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Object-Oriented Programming

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

CST242 Strings and Characters Page 1

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

More on variables and methods

ECE 122 Engineering Problem Solving with Java

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Text processing. Characters. The charat method. Fun with char! char vs. String. Text processing. Readings: 4.4 (pg ) 'h' is a char

Data Conversion & Scanner Class

CSE143 Midterm Summer Name of Student: Section (e.g., AA): Student Number:

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

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination

CSc 110, Spring Lecture 11: return values and math

Classes and Objects Part 1

What did we talk about last time? Examples switch statements

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

CS 302: Introduction to Programming

Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

Building Java Programs

Number Representation & Conversion

Programming with Java

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

Lesson 4 Utility classes: Math, String, I/O

Lesson:9 Working with Array and String

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

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

ESc101 : Fundamental of Computing

Primitive Data Types: Intro

Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal

Transcription:

CSE 373 Data Types and Manipulation; Arrays slides created by Marty Stepp http://www.cs.washington.edu/373/ University of Washington, all rights reserved. 1

Numeric data type kind of number memory (bits) range examples byte integer 8-128.. 127 (byte) 5 char character (integer) 16 \u0000.. \uffff 'a', '\u2603' float real number 32-3.4e38.. 3.4e38 3.14f, 1.1e7f double real number 64-1.8e308.. 1.8e308 3.14, 6.022e23 int integer 32-2 31.. 2 31 42, -17, 0xff long integer 64-2 63.. 2 63 42L, 21874109487L short integer 16-2 15.. 2 15 (short) 42 2

The Math class Method name Math.abs(value) Math.ceil(value) Math.floor(value) Description absolute value rounds up rounds down Math.log10(value) logarithm, base 10 Math.max(value1, value2) Math.min(value1, value2) Math.pow(base, exp) larger of two values smaller of two values base to the exp power Math.random() random double between 0 and 1 Math.round(value) Math.sqrt(value) Math.sin(value) Math.cos(value) Math.tan(value) Math.toDegrees(value) Math.toRadians(value) nearest whole number square root sine/cosine/tangent of an angle in radians convert degrees to radians and back Constant Description Math.E 2.7182818... Math.PI 3.1415926... 3

Wrapper classes wrapper: an object whose sole purpose is to hold a primitive value. often used with Java collections, since they can store only objects useful wrapper class behavior: string -> primitive: parsetype primitive -> wrapper: valueof wrapper -> primitive: typevalue MIN_VALUE, MAX_VALUE Primitive Type boolean byte char double float int long short Wrapper Type Boolean Byte Character Double Float Integer Long Short Character: isalphabetic, isdigit, isletter, islowercase, isuppercase, iswhitespace, tolowercase, touppercase Integer: tostring(int radix), parseint(str, radix) 4

Interesting integers factorial: n! is the product of 1.. n inclusive, e.g. 4! = 1*2*3*4=24 prime number: only divisible by 1 and itself prime factorization: e.g. 180 = 2*2*3*3*5 perfect number: equals sum of its factors (e.g. 6=1+2+3) greatest common divisor(gcd) Euclid's algorithm: GCD(a, b) = GCD(b, a mod b) least common multiple(lcm) LCM(a, b) = (a*b)/ GCD(a, b) Fibonacci: sum of the previous two: 1, 1, 2, 3, 5, 8, 13, 21,... 5

BigInteger and BigDecimal can represent arbitrarily large integers and real numbers import java.math.*; BigInteger(String) abs() add(biginteger), divide(biginteger), multiply(biginteger), subtract(biginteger) equals(biginteger), compareto(biginteger) gcd(biginteger) isprobableprime(certainty), nextprobableprime() pow(int exponent) tostring() valueof(long) constructor absolute value returns new big integer result comparing two BigIntegers greatest common divisor checks whether integer is prime; gets next prime current integer exponentiation BigInteger-> String converts primitive into BigInteger 6

Text data: String and char String: A type of objects representing character sequences. char : A primitive type representing single characters. A Stringis stored internally as an array of char String s = "Hi Ya!"; index 0 1 2 3 4 5 value 'H' 'i' ' ' 'Y' 'a' '!' It is legal to have variables, parameters, returns of type char surrounded with apostrophes: 'a' or '4' or '\n' or '\'' char initial = 'J'; System.out.println(initial); // J System.out.println(initial + " Joyce"); // J Joyce 7

String methods Method name contains(str) equals(str) equalsignorecase(str) indexof(str) length() replace(a, b) split(separator) startswith(str), endswith substring(index1, index2) tolowercase(), tolowercase Description whether the given string is found within this one whether two strings contain the same characters whether two strings contain the same characters, ignoring upper vs. lower case index where the start of the given string appears in this string (-1 if not found) number of characters in this string replace all occurrences of string awith b split string into array by the given separator text whether it contains str's characters at start/end the characters from index1(inclusive) to index2 (exclusive); if index2 omitted, grabs till end of string a new string with all lower/uppercase letters 8

Comparing char values Get the characters of a string with the charatmethod. You can compare chars with ==,!=, and other operators: String word = console.next(); char last = word.charat(word.length() - 1); if (last == 's') { System.out.println(word + " is plural."); } // prints the alphabet for (char c = 'a'; c <= 'z'; c++) { System.out.print(c); } 9

char vs. int Each charis mapped to an integer value internally Called an ASCII value 'A' is 65 'B' is 66 ' ' is 32 'a' is 97 'b' is 98 '*' is 42 Mixing char and int causes automatic conversion to int. 'a' + 10 is 107, 'A' + 'A' is 130 To convert an intinto the equivalent char, type-cast it. (char) ('a' + 2) is 'c' 10

char vs. String "h"is a String, but 'h'is a char (they are different) A Stringis an object; it contains methods. String s = "h"; s = s.touppercase(); // "H" int len = s.length(); // 1 char first = s.charat(0); // 'H' A charis primitive; you can't call methods on it. char c = 'h'; c = c.touppercase(); // ERROR s = s.charat(0).touppercase(); // ERROR What is s + 1? What is c + 1? What is s + s? What is c + c? 11

Mutable StringBuilder A StringBuilder object holds a mutable array of characters: append(value) method StringBuilder() StringBuilder(capacity) StringBuilder(text) delete(start, end) deletecharat(index) replace(start, end, text) charat(index), indexof(str), lastindexof(str), length(), substring(start, end) public String tostring() description new mutable string, either empty or with given initial text appends text/value to string's end removes character(s), sliding subsequent ones left to cover them remove start-end and add text there mirror of methods of String class returns an equivalent normal String 12

String + implementation The following code runs surprisingly slowly. Why? String s = ""; for (int i = 0; i < 40000; i++) { s += "x"; } System.out.println(s); Internally, Java converts the loop into the following: for (int i = 0; i < 40000; i++) { StringBuilder sb = new StringBuilder(s); sb.append("x"); s = sb.tostring(); // why is the code slow? } 13

Tokenizing strings w/ Scanner import java.util.*; Scanner(String), Scanner(File), Scanner(InputStream) next() nextline() hasnext() Method nextint(), nextdouble() hasnextline() hasnextint(), hasnextdouble() constructor Description reads a one-word String from the input reads a one-line String from the input reads an int/double from the input and returns it returns trueif there is a next token returns trueif there are any more lines of input returns trueif there is a next token and it can be read as an int/double 14

Arrays array: An object that stores many values of the same type. element: One value in an array. index: A 0-based integer to access an element from an array. length: Number of elements in the array. index 0 1 2 3 4 5 6 7 8 9 value 12 49-2 26 5 17-6 84 72 3 length = 10 element 0 element 4 element 9 15

Array declaration type[] name = new type[length]; Length explicitly provided. All elements' values initially 0. int[] numbers = new int[5]; index 0 1 2 3 4 value 0 0 0 0 0 type[] name = {value, value, value}; Infers length from number of values provided. Example: int[] numbers = {12, 49, -2, 26, 5, 17, -6}; index 0 1 2 3 4 5 6 value 12 49-2 26 5 17-6 16

Accessing elements; length name[index] name[index] = value; name.length // access // modify Legal indexes: between 0and the array's length -1. numbers[3] = 88; for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } System.out.println(numbers[-1]); // exception System.out.println(numbers[7]); // exception index 0 1 2 3 4 5 6 value 12 49-2 88 5 17-6 17

The Arrays class Class Arraysin package java.utilhas useful static methods for manipulating arrays: Method name binarysearch(array, value) copyof(array, length) equals(array1, array2) fill(array, value) sort(array) tostring(array) Description returns the index of the given value in a sortedarray (< 0 if not found) returns a new array with same elements returns trueif the two arrays contain the same elements in the same order sets every element in the array to have the given value arranges the elements in the array into ascending order returns a string representing the array, such as "[10, 30, 17]" 18