Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Similar documents
Chapter 8 Strings. Chapter 8 Strings

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

Java Strings. Interned Strings. Strings Are Immutable. Variable declaration as String Object. Slide Set 9: Java Strings and Files

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

Chapter 9 Strings and Text I/O

Chapter 9 Strings and Text I/O

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

CC316: Object Oriented Programming

String related classes

Thinking in Objects. CSE 114, Computer Science 1 Stony Brook University

Eng. Mohammed Abdualal

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

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

Eng. Mohammed Abdualal

Chapter 4 Mathematical Functions, Characters, and Strings

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Lab 14 & 15: String Handling

Chapter 10 Thinking in Objects. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 10 Thinking in Objects. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.

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

Class Library java.lang Package. Bok, Jong Soon

String. Other languages that implement strings as character arrays

CS 1301 Ch 8, Part A

Creating Strings. String Length

MATHEMATICAL FUNCTIONS CHARACTERS, AND STRINGS. INTRODUCTION IB DP Computer science Standard Level ICS3U

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

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

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

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

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

Chapter 10: Text Processing and More about Wrapper Classes

Building Strings and Exploring String Class:

Lecture Notes K.Yellaswamy Assistant Professor K L University

STRINGS AND STRINGBUILDERS. Spring 2019

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

Java String Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace,

Module 4: Characters, Strings, and Mathematical Functions

Programming with Java

Chapter 4 Mathematical Functions, Characters, and Strings

Chapter 1-9, 12-13, 18, 20, 23 Review Slides. What is a Computer?

Using Java Classes Fall 2018 Margaret Reid-Miller

More non-primitive types Lesson 06

What is a Computer? Chapter 1-9, 12-13, 18, 20, 23 Review Slides


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

Object-Oriented Programming

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

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

Chapter 4. Mathematical Functions, Characters, and Strings

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

ing execution. That way, new results can be computed each time the Class The Scanner

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

5/23/2015. Core Java Syllabus. VikRam ShaRma

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

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

Reading Input from Text File

Lecture Set 2: Starting Java

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Lecture Set 2: Starting Java

Chapter 2 Elementary Programming

TEST (MODULE:- 1 and 2)

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

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

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

H212 Introduction to Software Systems Honors

Chapter 2 ELEMENTARY PROGRAMMING

Computational Expression

STUDENT LESSON A10 The String Class

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

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

Ohad Barzilay and Oranit Dror

Welcome to the Using Objects lab!

Index COPYRIGHTED MATERIAL

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Midterms Save the Dates!

Important Java terminology

Mathematics for Computer Graphics - Lecture 12

USING LIBRARY CLASSES

Chapter 2 Primitive Data Types and Operations. Objectives

Classes and Objects Part 1

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CST242 Strings and Characters Page 1

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

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

Programming with Java

Text User Interfaces. Keyboard IO plus


tostring() Method tostring() Method -Example tostring() Method -Example StringBufferClass StringBuffer class - Constructors

Chapter 2. Elementary Programming

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

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

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.

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

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

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

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Transcription:

CHAPTER 8 STRINGS Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract Classes Chapter 13 Graphics 10.4, Interfaces Chapter 14 Event-Driven Programming Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9 Chapter 17 Exceptions and Assertions Chapter 18 Binary I/O 1

OBJECTIVES To use the String class to process fixed strings ( 8.2). To use the Character class to process a single character ( 8.3). To use the StringBuilder/StringBuffer class to process flexible strings ( 8.4). To know the differences between the String, StringBuilder, and StringBuffer classes ( 8.2-8.4). To learn how to pass strings to the main method from the command line ( 8.5). To use the StringTokenizer, Scanner class 2

THE STRING CLASS Constructing a String: String message = "Welcome to Java ; String message = new String("Welcome to Java ); String s = new String(); Obtaining String length and Retrieving Individual Characters in a string (length, charat) String Concatenation (concat) Substrings (substring(index), substring(start, end)) Comparisons (equals, compareto) String Conversions (tolowercase) Finding a Character or a Substring in a String (indexof) Conversions between Strings and Arrays (tochararray) Converting Characters and Numeric Values to Strings(valueOf) 3

java.lang.string +String() +String(value: String) +String(value: char[]) +charat(index: int): char +compareto(anotherstring: String): int +comparetoignorecase(anotherstring: String): int +concat(anotherstring: String): String +endswith(suffix: String): boolean +equals(anotherstring: String): boolean +equalsignorecase(anotherstring: String): boolean +getchars(int srcbegin, int srcend, char[] dst, int dstbegin): void +indexof(ch: int): int +indexof(ch: int, fromindex: int): int +indexof(str: String): int +indexof(str: String, fromindex: int): int +lastindexof(ch: int): int +lastindexof(ch: int, fromindex: int): int +lastindexof(str: String): int +lastindexof(str: String, fromindex: int): int +regionmatches(toffset: int, other: String, offset: int, len: int): boolean +length(): int +replace(oldchar: char, newchar: char): String +startswith(prefix: String): boolean +substring(beginindex: int): String +substring(beginindex: int, endindex: int): String +tochararray(): char[] +tolowercase(): String +tostring(): String +touppercase(): String +trim(): String +copyvalueof(data: char[]): String +valueof(c: char): String +valueof(data: char[]): String +valueof(d: double): String +valueof(f: float): String Constructs an empty string Constructs a string with the specified string literal value Constructs a string with the specified character array Returns the character at the specified index from this string Compares this string with another string Compares this string with another string ignoring case Concat this string with another string Returns true if this string ends with the specified suffix Returns true if this string is equal to anther string Checks if this string equals anther string ignoring case Copies characters from this string into the destination character array Returns the index of the first occurrence of ch Returns the index of the first occurrence of ch after fromindex Returns the index of the first occurrence of str Returns the index of the first occurrence of str after fromindex Returns the index of the last occurrence of ch Returns the index of the last occurrence of ch before fromindex Returns the index of the last occurrence of str Returns the index of the last occurrence of str before fromindex Returns true if the specified subregion of this string exactly matches the specified subregion of the string argument Returns the number of characters in this string Returns a new string with oldchar replaced by newchar Returns true if this string starts with the specified prefix Returns the substring from beginindex Returns the substring from beginindex to endindex-1. Returns a char array consisting characters from this string Returns a new string with all characters converted to lowercase Returns a new string with itself Returns a new string with all characters converted to uppercase Returns a string with blank characters trimmed on both sides Returns a new string consisting of the char array data Returns a string consisting of the character c Same as copyvalueof(data: char[]): String Returns a string representing the double value Returns a string representing the float value Liang, +valueof(i: Introduction int): String to Java Programming, Sixth Returns Edition, a string representing (c) 2007 the Pearson int value Education, Inc. All +valueof(l: long): String rights reserved. Returns 0-13-222158-6 a string representing the long value 4

CONSTRUCTING STRINGS String newstring = new String(stringLiteral); String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java"; 5

STRINGS ARE IMMUTABLE A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; 6

TRACE CODE String s = "Java"; s = "HTML"; After executing String s = "Java"; s : String String object for "Java" Contents cannot be changed 7

TRACE CODE String s = "Java"; s = "HTML"; After executing s = "HTML"; s : String String object for "Java" This string object is now unreferenced : String String object for "HTML" 8

INTERNED STRINGS Since strings are immutable and are frequently used, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned object. You can also use a String object s intern method to return an interned string. For example, the following statements: 9

TRACE CODE String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java"; s pool : String Interned string object for "Welcome to Java" 10

TRACE CODE String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java"; s s1 pool : String Interned string object for "Welcome to Java" : String A string object for "Welcome to Java" 11

TRACE CODE String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java"; s s2 s1 pool : String Interned string object for "Welcome to Java" : String A string object for "Welcome to Java" 12

TRACE CODE String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java"; s s2 s3 s1 pool : String Interned string object for "Welcome to Java" : String A string object for "Welcome to Java" 13

EXAMPLES String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java"; System.out.println("s1 == s is " + (s1 == s)); System.out.println("s2 == s is " + (s2 == s)); System.out.println("s == s3 is " + (s == s3)); s s2 s3 s1 pool : String Interned string object for "Welcome to Java" : String A string object for "Welcome to Java" display s1 == s is false s2 == s is true s == s3 is true A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created. 14

FINDING STRING LENGTH Finding string length using the length() method: message = "Welcome"; message.length() (returns 7) 15

RETRIEVING INDIVIDUAL CHARACTERS IN A STRING Do not use message[0] Use message.charat(index) Index starts from 0 Indices message 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 W e l c o m e t o J a v a message.charat(0) message.length() is 15 message.charat(14) 16

STRING CONCATENATION String s3 = s1.concat(s2); String s3 = s1 + s2; s1 + s2 + s3 + s4 + s5 same as (((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5); String s = 1+2; //ok or not? 17

EXTRACTING SUBSTRINGS You can extract a single character from a string using the charat method. You can also extract a substring from a string using the substring method in the String class. String s1 = "Welcome to Java"; String s2 = s1.substring(0, 11) + "HTML"; //Welcome to HTML Indices message 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 W e l c o m e t o J a v a message.substring(0, 11) 18 message.substring(11)

STRING COMPARISONS equals String s1 = new String("Welcome ); String s2 = Welcome"; if (s1.equals(s2)){ } // s1 and s2 have the same contents if (s1 == s2) { // s1 and s2 have the same reference } 19

STRING COMPARISONS, CONT. compareto(object object) String s1 = new String( e ); String s2 = b"; if (s1.compareto(s2) > 0) { // s1 is greater than s2 } else if (s1.compareto(s2) == 0) { // s1 and s2 have the same contents } else // s1 is less than s2 20

STRING CONVERSIONS The contents of a string cannot be changed once the string is created. But you can convert a string to a new string using the following methods: tolowercase touppercase trim replace(oldchar, newchar) String s3 = " Happy ok "; System.out.println(s3.trim()); //Happy ok "mesquite in your cellar".replace('e', 'o') ; //returns "mosquito in your collar" "John".replace('q', 'x') //return John 21

FINDING A CHARACTER OR A SUBSTRING IN A STRING "Welcome to Java".indexOf('W') returns 0. "Welcome to Java".indexOf('x') returns -1. "Welcome to Java".indexOf('o', 5) returns 9. "Welcome to Java".indexOf("come") returns 3. "Welcome to Java".indexOf("Java", 5) returns 11. "Welcome to Java".indexOf("java", 5) returns -1. "Welcome to Java".lastIndexOf('a') returns 14. 22

CONVERT CHARACTER AND NUMBERS TO STRINGS The String class provides several static valueof methods for converting a character, an array of characters, and numeric values to strings. These methods have the same name valueof with different argument types char, char[], double, long, int, and float. For example, to convert a double value to a string, String str = String.valueOf(5.44). The return value is string consists of characters 5,., 4, and 4. CheckPalindrome 23

THE CHARACTER CLASS java.lang.character +Character(value: char) +charvalue(): char +compareto(anothercharacter: Character): int +equals(anothercharacter: Character): boolean +isdigit(ch: char): boolean +isletter(ch: char): boolean +isletterordigit(ch: char): boolean +islowercase(ch: char): boolean +isuppercase(ch: char): boolean +tolowercase(ch: char): char +touppercase(ch: char): char Constructs a character object with char value Returns the char value from this object Compares this character with another Returns true if this character equals to another Returns true if the specified character is a digit Returns true if the specified character is a letter Returns true if the character is a letter or a digit Returns true if the character is a lowercase letter Returns true if the character is an uppercase letter Returns the lowercase of the specified character Returns the uppercase of the specified character 24

EXAMPLES Character charobject = new Character('b'); charobject.compareto(new Character('a')) returns 1 charobject.compareto(new Character('b')) returns 0 charobject.compareto(new Character('c')) returns -1 charobject.compareto(new Character('d') returns 2 charobject.equals(new Character('b')) returns true charobject.equals(new Character('d')) returns false CountEachLetter 25

STRINGBUILDER AND STRINGBUFFER The StringBuilder/StringBuffer class is an alternative to the String class. In general, a StringBuilder/StringBuffer can be used wherever a string is used. StringBuilder/StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created. 26

STRINGBUILDER VS. STRINGBUFFER The StringBuilder class, introduced in JDK 1.5, is similar to StringBuffer except that the update methods in StringBuffer are synchronized. Use StringBuffer if it may be accessed by multiple tasks concurrently. Using StringBuilder is more efficient if it is accessed by a single task. The constructors and methods in StringBuffer and StringBuilder are almost the same. This book covers StringBuffer. You may replace StringBuffer by StringBuilder. The program can compile and run without any other changes. 27

java.lang.stringbuffer +StringBuffer() +StringBuffer(capacity: int) +StringBuffer(str: String) +append(data: char[]): StringBuffer +append(data: char[], offset: int, len: int): StringBuffer +append(v: aprimitivetype): StringBuffer +append(str: String): StringBuffer +capacity(): int +charat(index: int): char +delete(startindex: int, endindex: int): StringBuffer +deletecharat(int index): StringBuffer +insert(index: int, data: char[], offset: int, len: int): StringBuffer +insert(offset: int, data: char[]): StringBuffer +insert(offset: int, b: aprimitivetype): StringBuffer +insert(offset: int, str: String): StringBuffer +length(): int +replace(int startindex, int endindex, String str): StringBuffer +reverse(): StringBuffer +setcharat(index: int, ch: char): void +setlength(newlength: int): void +substring(startindex: int): String +substring(startindex: int, endindex: int): String Constructs an empty string buffer with capacity 16 Constructs a string buffer with the specified capacity Constructs a string buffer with the specified string Appends a char array into this string buffer Appends a subarray in data into this string buffer Appends a primitive type value as string to this buffer Appends a string to this string buffer Returns the capacity of this string buffer Returns the character at the specified index Deletes characters from startindex to endindex Deletes a character at the specified index Inserts a subarray of the data in the array to the buffer at the specified index Inserts data to this buffer at the position offset Inserts a value converted to string into this buffer Inserts a string into this buffer at the position offset Returns the number of characters in this buffer Replaces the characters in this buffer from startindex to endindex with the specified string Reveres the characters in the buffer Sets a new character at the specified index in this buffer Sets a new length in this buffer Returns a substring starting at startindex Returns a substring from startindex to endindex 28

STRINGBUFFER CONSTRUCTORS public StringBuffer() No characters, initial capacity 16 characters. public StringBuffer(int length) No characters, initial capacity specified by the length argument. public StringBuffer(String str) Represents the same sequence of characters as the string argument. Initial capacity 16 plus the length of the string argument. 29

APPENDING NEW CONTENTS INTO A STRING BUFFER StringBuffer strbuf = new StringBuffer(); strbuf.append("welcome"); strbuf.append(' '); strbuf.append("to"); strbuf.append(' '); strbuf.append("java"); PalindromeIgnoreNonAlphanumeric 30

MAIN METHOD IS JUST A REGULAR METHOD You can call a regular method by passing actual parameters. Can you pass arguments to main? Of course, yes. For example, the main method in class B is invoked by a method in A, as shown below: public class A { public static void main(string[] args) { String[] strings = {"New York", "Boston", "Atlanta"}; B.main(strings); } } class B { public static void main(string[] args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]); } } 31

COMMAND-LINE PARAMETERS class TestMain { public static void main(string[] args) {... } } C:/>java TestMain val0 val1 val2... valn In the main method, get the arguments from args[0], args[1],..., args[n], which corresponds to val0, val1,..., valn in the command line. 32

THE STRINGTOKENIZER CLASS java.util.stringtokenizer +StringTokenizer(s: String) +StringTokenizer(s: String, delimiters: String) +StringTokenizer(s: String, delimiters: String, returndelimiters: boolean) +counttokens(): int +hasmoretokens(): boolean +nexttoken(): String +nexttoken(delimiters: String): String Constructs a string tokenizer for the string. Constructs a string tokenizer for the string with the specified delimiters. Constructs a string tokenizer for the string with the delimiters and returndelims. Returns the number of remaining tokens. Returns true if there are more tokens left. Returns the next token. Returns the next token using new delimiters. 33

EXAMPLES 1 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s); System.out.println("The total number of tokens is " + tokenizer.counttokens()); while (tokenizer.hasmoretokens()) System.out.println(tokenizer.nextToken()); The code displays อย ใน java.util The total number of tokens is 3 Java is cool. 34

EXAMPLES 2 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s, "ac"); System.out.println("The total number of tokens is " + tokenizer.counttokens()); while (tokenizer.hasmoretokens()) System.out.println(tokenizer.nextToken()); The total number of tokens is 4 J v is ool. The code displays 35

EXAMPLES 3 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s, "ac", true); System.out.println("The total number of tokens is " + tokenizer.counttokens()); while (tokenizer.hasmoretokens()) System.out.println(tokenizer.nextToken()); The total number of tokens is 7 J a v a The code displays is c ool. 36

JDK 1.5 Feature THE SCANNER CLASS The delimiters are single characters in StringTokenizer. You can use the new JDK 1.5 java.util.scanner class to specify a word as a delimiter. String s = "Welcome to Java! Java is fun! Java is cool!"; Scanner scanner = new Scanner(s); scanner.usedelimiter("java"); while (scanner.hasnext()) System.out.println(scanner.next()); Welcome to! is fun! is cool! Creates an instance of Scanner for the string. Sets Java as a delimiter. hasnext() returns true if there are still more tokens left. The next() method returns a token as a string. Output 37

JDK 1.5 Feature SCANNING PRIMITIVE TYPE VALUES If a token is a primitive data type value, you can use the methods nextbyte(), nextshort(), nextint(), nextlong(), nextfloat(), nextdouble(), or nextboolean() to obtain it. For example, the following code adds all numbers in the string. Note that the delimiter is space by default. String s = "1 2 3 4"; Scanner scanner = new Scanner(s); int sum = 0; while (scanner.hasnext()) sum += scanner.nextint(); System.out.println("Sum is " + sum); 38

JDK 1.5 Feature CONSOLE INPUT USING SCANNER Another important application of the Scanner class is to read input from the console. For example, the following code reads an int value from the keyboard: System.out.print("Please enter an int value: "); Scanner scanner = new Scanner(System.in); int i = scanner.nextint(); NOTE: StringTokenizer can specify several single characters as delimiters. Scanner can use a single character or a word as the delimiter. So, if you need to scan a string with multiple single characters as delimiters, use StringTokenizer. 39 If you need to use a word as the delimiter, use Scanner.