Lecture 4. Strings, Wrappers, & Containers

Similar documents
String is a Class; Quoted Text is an Object

Lecture 8. Reviewing Methods; Wrapper Classes

Lecture 7. Strings & Stepwise Refinement

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

JAVA.LANG.INTEGER CLASS

8/25/17. Demo: Create application. CS2110, Recita.on 1. Arguments to method main, Packages, Wrapper Classes, Characters, Strings.

Strings! Today! CSE String Methods!

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

CSE1710. Big Picture. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

York University Fall 2001 / Test #1 Department of Computer Science

"Hello" " This " + "is String " + "concatenation"

Announcements for the Class

Review of Java. or maybe not

Java Strings Java, winter semester

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

C a; C b; C e; int c;

CS112 Lecture: Characters and Strings

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

Java By Abstraction - Test-B (Chapters 1-6)

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

c) And last but not least, there are javadoc comments. See Weiss.

Inf1-OOP. Data Types. A Foundation for Programming. type value set operations. Overview. Using Data Types 1. Image Processing

Notes from the Boards Set BN19 Page

Formatting Output & Enumerated Types & Wrapper Classes

CSE1710. Big Picture. Today is last day covering Ch 6. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

H212 Introduction to Software Systems Honors

Designing data types. Fundamentals of Computer Science I

CS162: Introduction to Computer Science II. Primitive Types. Primitive types. Operations on primitive types. Limitations

More non-primitive types Lesson 06

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

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

CS162: Introduction to Computer Science II

Object-Oriented Programming

More on variables and methods

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

From C++ to Java. Duke CPS

AP Computer Science. Strings. Credit: Slides are modified with permission from Barry Wittman at Elizabethtown College

C Sc 127A Practice Test 2 SL Name 150pts

Introduction to Programming Using Java (98-388)

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

Classes and Objects Part 1

CSE 21 Intro to Computing II. JAVA Objects: String & Scanner

Chapter 10: Text Processing and More about Wrapper Classes

Chapter 10. Object-Oriented Thinking

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

C++ basics Getting started with, and Data Types.

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

CSC Java Programming, Fall Java Data Types and Control Constructs

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

Lecture 10. Overriding & Casting About

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Array. Prepared By - Rifat Shahriyar

Using Classes and Objects. Chapter

Data Types and Variables

Lecture 13. Call Stacks & Debugging

Abstract Classes Interfaces

CST141 Thinking in Objects Page 1

Pointers (continued), arrays and strings

Dynamic Data Structures and Generics

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

Pointers (continued), arrays and strings

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Strings

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

ECE 122. Engineering Problem Solving with Java

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

appreciate the difference between a char and a string understand and use the String class methods

Readings for This Lecture

CS 200 Using Objects. Jim Williams, PhD

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Programming Language Concepts: Lecture 2

Class Libraries and Packages

0. What is the capital of Canada? (4pts) a. Toronto b. Quebec c. Ottawa d. Vancouver e. Calgary f. Not sure

CS/ENGRD 2110 FALL Lecture 3: Fields, getters and setters, constructors, testing

COMP-202 Unit 8: Basics of Using Objects

Brief Summary of Java

Bruce Merry. IOI Training Dec 2013

Value vs. reference semantics

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

חומר עזר לבחינה במבוא למדעי המחשב // Indicates whether some other object is "equal to" // this one. boolean equals(object other)

CS 11 java track: lecture 1

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

Announcements for this Lecture

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Timing for Interfaces and Abstract Classes

Chapter 9 Abstract Classes and Interfaces

Inf1-OOP. Data Types. A Foundation for Programming. type value set operations. Overview. Using Data Types 1. Image Processing

Using Java Classes Fall 2018 Margaret Reid-Miller

CS100J Prelim 1 22 February 2007

Java Primer 1: Types, Classes and Operators

CS 1110: Introduction to Computing Using Python Lists and Sequences

STUDENT LESSON A10 The String Class

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Lecture 12. Lists (& Sequences)

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

Arrays and Strings. Arrays - homogeneous indexed collections Selection sort as array example. String class, revisited

JAVA WRAPPER CLASSES

Transcription:

Lecture 4 Strings, Wrappers, & Containers

Announcements for This Lecture Readings pp. 175 181 Sections 2.5, 3.1.2-3.1.3 Also Section 5.2 PLive (optional): Lesson 2-5 Lessons 5-1 and 5-2 Assignments Assignment 1 due FRIDAY! Before Midnight!!! Will get back by Sunday Revise if you are told Start New Assignment No code; written only Meant to do while you revise Scan and submit via CMS (or use a drawing program) 2/4/13 Strings, Wrappers & Containers 2

String is a Class; Quoted Text is an Object String s = "abc d"; Indexed characters: 01234 abc d s.length() is 5 s.charat(2) is 'c' s.substring(2) is "c d" s.substring(1,3) is "bc" @3e9cff "abc d" length() charat(int) substring(int) substring(int, int) indexof(string) lastindexof(string) s String @3e9cff not a field fields are hidden 2/4/13 Strings, Wrappers & Containers 3

String Has a Lot of Useful Methods String s = "abc d"; Indexed characters: 01234 abc d See text pp. 175 181 Look in CD ProgramLive Look at API specs for String s.substring(2,4) is "c " (NOT "c d") s.substring(2) is "c d" " bcd ".trim() is "bcd" (trim beginning and ending blanks) s.indexof("bc") is 1 (index or position of first occurrence of in "bc" or -1 if none) 2/4/13 Strings, Wrappers & Containers 4

String Variables Hold Folder Names Create two Strings String s = "hello"; s @3e9cff @3e9cff String t = "hello"; Do not use == to test equality of s and t s == t tests if same object Not useful for Strings Use equals() instead s.equals(t) tests if they have the same text t "hello" equals(string) @01a2ed @01a2ed "hello" String String equals(string) 2/4/13 Strings, Wrappers & Containers 5

String as a Container Data arranged in a list List of characters Access characters by position, not field name Method: charat(int) Position starts at 0 How about other lists? List of ints? List of Points? String s = "abc d"; 0 1 2 3 4 a b c d String s = "one\ntwo"; 0 1 2 3 4 5 6 o n e \n t w o 2/4/13 Strings, Wrappers & Containers 6

Containers Container: an object that holds a list of objects But cannot hold primitive values (e.g. int, double, etc.)! Java has several container classes The are all in package java.util! Generic classes: type depends on what is contained Put contained type in < > Example: Vector Vector<String>: Vector that holds String objects Vector<Rhino>: Holds Rhino objects Vector<Vector<String>>:???? Vector<int>: NOT ALLOWED! 2/4/13 Strings, Wrappers & Containers 7

Wrappers: Turn Primitives into Objects Want Vector<int> int is primitive type, not class Need to convert an int value (e.g. 9) into an object Integer: a wrapper class Contains or wraps one value Value cannot be changed: it is immutable Many useful static features Integer.MAX_VALUE Integer.parseInt(String) @01a2ed??? 5 Integer Integer Integer(int) Integer(String) tostring() equals(object) intvalue() MAX_VALUE MIN_VALUE tostring(int) tobinary(int) valueof(string) parseint(string) 2/4/13 Strings, Wrappers & Containers 8

Each Primitive Type Has a Wrapper When you need to treat a primitive value as an object, then just wrap the value in an object of the wrapper class. Primitive Type Wrapper Class int Integer long Long float Float double Double char Character boolean Boolean Integer k= new Integer(63); Each wrapper class has: Instance methods (e.g. equals, constructors, tostring) Static variables and methods (for useful computations) int j= k.intvalue(); You don't have to memorize the methods of the wrapper classes. But be aware of them. See Section 5.1 and PLive 5-1 and 5-2 for more. 2/4/13 Strings, Wrappers & Containers 9

Boxing and Unboxing Modern (post 1.4) Java boxes/unboxes Boxing: Automatically add a wrapper Integer s = 4; Same as Integer s = new Integer(4); Unboxing: Automatically remove a wrapper int x = new Integer(4); Same as int x = new Integer(4).intValue(); Type is determined by the variable assigned 2/4/13 Strings, Wrappers & Containers 10

Boxing and Unboxing Modern (post 1.4) Java boxes/unboxes Boxing: Automatically add a wrapper Integer s = 4; Same as Integer s = new Integer(4); Unboxing: Automatically remove a wrapper int x = new Integer(4); Same as int x = new Integer(4).intValue(); Type is determined by the variable assigned 2/4/13 Strings, Wrappers & Containers 11

Example: Vector Create an empty vector instance (of Strings) import java.util.vector; Vector vec = new Vector<Integer>(); Add some strings to it vec.add(new Integer(2)); // Adds 2 at position 0 vec.add(new Integer(7)); // Adds 7 at position 1 vec.add(new Integer(-3)); // Adds -3 at position 2 Get the String at position 1 vec.get(1) // Function call, gives 7 Search vector for number 5 vec.indexof(new Integer(5)) // Not found; gives -1 2/4/13 Strings, Wrappers & Containers 12

Vectors Can Add and Remove Do the following: import java.util; Vector vec = new Vector<String>(); vec.add("abc"); vec.add("def"); vec.add("ghi"); vec.add("jkl"); vec.remove(1); 0 1 2 3 "abc" "def" "ghi" "jkl" After all this, what is the value of vec.get(2)? A: Function gives "abc" B: Function gives "ghi" C: Function gives "jkl" D: I have no clue 2/4/13 Strings, Wrappers & Containers 13

Arrays Array: an object that holds a fixed number of values of the same type Type of an array is written: <type>[] (e.g. int[]) Declare a variable x that holds the name of an array of ints: <type> <name>; (e.g., int[] x;) Elements of array x are numbered: 0, 1, 2,, n 1 To refer to an element of an array: <var>[<index>] (e.g. x[3]) x[0] x[1] x[2] x[3] x @4e0a1 5 7 4-2 This array contains 4 values of type int @4e0a1 int[] 2/4/13 Strings, Wrappers & Containers 14

Arrays Array length is a field of the object x.length [not x.length()] The length field is final: it never changes after the array is created Length is not part of the array type An int[] variable can hold arrays of different lengths at different times Declaring x does not create array As an object it starts out null Need a special new-expression: new <type>[<length>] " (e.g. x = new int[3];) 0 1 2 3 x 0 1 2 @4e0a1 length 4 5 7 4-2 @13fc8 @4e0a1 @13fc8 5 7 4 int[] 2/4/13 Strings, Wrappers & Containers 15

Overview of Array Syntax int[] x; Create a variable named x to hold an int[] value x @4e0a1 int[] x = new int[4]; x[2] = 5; x[0] = 4; int k = 3; x[k] = 2 * x[0]; x[k 2] = 6; Create array object of length 4; put name in x Assign 5 to element 2 and 4 to element 0 Assign 8 to x[3] and 6 to x[1] 0 1 2 3 k @4e0a1 0 0 0 0 3-4 6 5-8 int 2/4/13 Strings, Wrappers & Containers 16

Arrays vs. Vectors vs. Strings Declaration int[] a; (contains ints) Creation a = new int[n]; (size fixed forever) Reference x = a[i]; Change a[i] = x; Declaration Vector<Integer> v; (contains Integers) Creation v= new Vector<Integer>(); (can be resized at will) Reference x= v.get(i); Change v.set(i, x); Declaration String s; (contains chars) Creation s = foo ; (contents fixed forever) Reference c = s.charat(i); Cannot Change Variables a[0], a[1], are at successive locations in memory. Element type can be class or primitive type. Storage layout unspecified (but really, it is an array). Element type can only be a class type. Storage layout unspecified (but really, it is an array) Element type is always char. 9/14/12 Strings, Wrappers & Containers 17

Array Initializers Initializing a newly created array: int[] c= new int[5]; c[0]= 5; c[1]= 4; c[2]= 7; c[3]= 6; c[4]= 5; Instead, use an array initializer: new int[] { 5, 4, 7, 6, 5 } no size goes here (implied by length of initializer list) In a declaration, short form is available: int[] c;" c= new int[] { 5, 4, 7, 6, 5 }; int[] c= new int[] { 5, 4, 7, 6, 5 }; int[] c= { 5, 4, 7, 6, 5 }; create array of 5 ints initialized with default (0) types must agree with array s type 2/4/13 Strings, Wrappers & Containers assign new values to elements create array of 5 ints and initialize all elements all three do the same thing 0 1 2 3 x @4e0a1 5 4 7 6 4 5 @4e0a1 int[] 18

Array Initialization Example public class ArrayDemo { public static final String[] months= " new String[]{"January","February","March","April","May", " "June","July","August","September","October," "November","December"}; } /**Yields: the month name, given its number m * Precondition: 1 <= m <= 12 */ public static String themonth(int m) { } return months[m 1]; e.g. ArrayDemo.theMonth(4) returns months[3], or "April". Variable months is: static: object assigned is created only once public: can be seen outside class ArrayDemo final: it cannot be changed once initialized 2/4/13 Strings, Wrappers & Containers 19