Strings JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Advertisements

Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
Fundamental Programming Structures in Java: Strings.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
28-Jun-15 String and StringBuilder Part I: String.
The String Class. Objectives: Learn about literal strings Learn about String constructors Learn about commonly used methods Understand immutability of.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Chapter 9: Text Processing and More about Wrapper Classes Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis.
Class T{ public static int id; public static int num = 5; public int n; public boolean c; public static void setNumberOfBicycles(int val) { num=val; //
Java Methods A & AB Chapter 10 - Strings. Ch 10 Goals Understand Strings indepth Learn strategies to deal with the immutability of Strings Learn how to.
String Class in Java java.lang Class String java.lang.Object java.lang.String java.lang.Object We do not have to import the String class since it comes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
String Class. Objectives and Goals Identify 2 types of Strings: Literal & Symbolic. Learn about String constructors and commonly used methods Learn several.
Java Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
String Manipulation Chapter 15 This chapter explains the String facilities. You have already seen some of the main methods of the String class.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 8 Strings 1.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Operations on Strings. 8/8/2005 Copyright 2006, by the authors of these slides, and Ateneo de Manila University. All rights reserved L: String Manipulation.
Chapter 7: Characters, Strings, and the StringBuilder.
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
10-2 Chapter 10 discusses the following main topics:  Introduction to Wrapper Classes  Character Testing and Conversion with the Character Class  More.
String Handling StringBuffer class character class StringTokenizer class.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 10: Text Processing and More about Wrapper Classes Starting.
Strings Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and.
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.
Strings and ArrayLists April 23, 2012 ASFA AP CS.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
String Class in Java java.lang Class String java.lang.Object java.lang.String java.lang.Object We do not have to import the String class since it comes.
17-Feb-16 String and StringBuilder Part I: String.
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings Chapter.
"Chapter 9" Strings Java Methods Maria Litvin Gary Litvin
The String Class.
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
String Class.
Strings Chapter 6.
Primitive Types Vs. Reference Types, Strings, Enumerations
String and StringBuilder
MSIS 655 Advanced Business Applications Programming
String and StringBuilder
Exposure Java 2015 Pre-AP®CS Edition Chapter 12 Slides String Methods
String and StringBuilder
CS2011 Introduction to Programming I Strings
Presentation transcript:

Strings JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. TM "Chapter 9"

9-2 Objectives: l Learn about literal strings l Learn about String constructors and commonly used methods l Understand immutability of strings l Learn to convert strings into numbers and numbers into strings l Learn several useful methods of the Character class

9-3 The String class l An object of the String class represents a string of characters. l The String class belongs to the java.lang package, which is built into Java. l Like other classes, String has constructors and methods. l Unlike other classes, String has two operators, + and += (used for concatenation).

9-4 Literal Strings l Literal strings are anonymous constant objects of the String class that are defined as text in double quotes. l The string text may include “escape” characters, as described in Chapter 6 (p. 146); for example: \\ stands for \ \n stands for the newline character "Biology”, "C:\\jdk1.4\\docs”, "Hello\n"

9-5 Literal Strings (cont’d) l don’t have to be constructed: they are “just there.” l can be assigned to String variables. l can be passed to methods and constructors as arguments. l have methods you can call: String fileName = "fish.dat"; button = new JButton("Next slide"); if (”Start". equals(cmd))...

9-6 Immutability l Once created, a string cannot be changed: none of its methods changes the string. l Such types of objects are called immutable. l Immutable objects are convenient because two references can point to the same object safely. l There is no danger of changing an object through one reference without the others being aware of the change.

9-7 Immutability (cont’d) l Advantage: more efficient, no need to copy. String s1 = "Sun"; String s2 = s1; String s1 = "Sun"; String s2 = new String(s1); s1 s2 "Sun" s1 s2 "Sun" OKLess efficient and wasteful

9-8 Immutability (cont’d) l Disadvantage: less efficient — you need to create a new string and throw away the old one for every small change. String s = "sun"; char ch = Character.toUpper(s.charAt (0)); s = ch + s.substring (1); s "sun" "un"'S' +

9-9 Empty Strings l An empty string has no characters; its length is 0. l Not to be confused with an uninitialized string: String s1 = ""; String s2 = new String(); Empty strings private String errorMsg; errorMsg is null

9-10 Constructors l String’s no-args and copy constructors are not used much. l Other constructors convert arrays into strings (used in a lab in Chapter 10). String s1 = new String (); String s2 = new String (s1); String s1 = ""; String s2 = s1;

9-11 Methods — length, charAt int length (); char charAt (k); l Returns the number of characters in the string l Returns the k-th char 6 ’n' ”Flower".length(); ”Wind".charAt (2); Returns: Character positions in strings are numbered starting from 0

9-12 Methods — substring String s2 = s.substring (i, k); –returns the substring of chars in positions from i to k-1 String s2 = s.substring (i); –returns the substring from the i-th char to the end ”raw" "happy" "" (empty string) ”strawberry".substring (2,5); "unhappy".substring (2); "emptiness".substring (9); Returns: strawberry i k

9-13 Methods — Concatenation String result = s1 + s2; –concatenates s1 and s2 String result = s1.concat (s2); –the same as s1 + s2 result += s3; –concatenates s3 to result result += num; –converts num to String and concatenates it to result

9-14 Methods — Find (indexOf) String date = "July 5, :28:19 PM" ; date.indexOf ('J'); 0 date.indexOf ('2'); 8 date.indexOf ("2012"); 8 date.indexOf ('2', 9); 11 date.indexOf ("2020"); -1 date.lastIndexOf ('2'); Returns: (not found) (starts searching at position 9)

9-15 Methods — Comparisons boolean b = s1.equals(s2); –returns true if the string s1 is equal to s2 boolean b = s1.equalsIgnoreCase(s2); –returns true if the string s1 matches s2, case- blind int diff = s1.compareTo(s2); –returns the “difference” s1 - s2 int diff = s1.compareToIgnoreCase(s2); –returns the “difference” s1 - s2, case-blind

9-16 Methods — Replacements String s2 = s1.trim (); –returns a new string formed from s1 by removing white space at both ends String s2 = s1.replace(oldCh, newCh); –returns a new string formed from s1 by replacing all occurrences of oldCh with newCh String s2 = s1.toUpperCase(); String s2 = s1.toLowerCase(); –returns a new string formed from s1 by converting its characters to upper (lower) case

9-17 Replacements (cont’d) l Example: how to convert s1 to upper case l A common bug: s1 = s1.toUpperCase(); s1.toUpperCase(); s1 remains unchanged

9-18 Methods — toString l It is customary to provide a toString method for your class. l toString converts an object into a String (for printing it out, for debugging, etc.). is the same as System.out.print (obj); System.out.print (obj.toString());

9-19 Numbers to Strings and Strings to Numbers l Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. l Integer and Double provide useful static methods for conversions: String s1 = Integer.toString (i); String s2 = Double.toString (d); int n = Integer.parseInt (s1); double x = Double.parseDouble (s2); int i; double d;

9-20 Numbers to Strings l Three ways to convert a number into a string: 1. String s = "" + num; 2. String s = Integer.toString (i); String s = Double.toString (d); 3. String s = String.valueOf (num); int i; double d;

9-21 Numbers to Strings (cont’d) l The DecimalFormat class can be used for more controlled conversions of numbers into strings: import java.text.DecimalFormat;... DecimalFormat money = new DecimalFormat("0.00");... double amt = …;... String s = money.format (amt); "56.79"

9-22 Strings to Numbers l These methods throw a NumberFormatException if s does not represent a valid number. l Older versions of SDK (before 1.2) did not have Double.parseDouble; you had to use int n = Integer.parseInt(s); double x = Double.parseDouble(s); double x = Double.valueOf(s).doubleValue();

9-23 Character Methods l java.lang.Character is a class that represents characters as objects. l Character has several useful static methods that determine the type of a character. l Character also has methods that convert a letter to the upper or lower case.

9-24 Character Methods (cont’d) if (Character.isDigit (ch))....isLetter....isLetterOrDigit....isUpperCase....isLowerCase....isWhitespace... –return true if ch belongs to the corresponding category Whitespace is space, tab, newline, etc.

9-25 Character methods (cont’d) char ch2 = Character.toUpperCase (ch1);.toLowerCase (ch1); –if ch1 is a letter, returns its upper (lower) case; otherwise returns ch1 int d = Character.digit (ch, radix); –returns the int value of the digit ch in the given int radix char ch = Character.forDigit (d, radix); –returns a char that represents int d in a given int radix

9-26 StringTokenizer l java.util.StringTokenizer is used to extract “tokens” from a string. l Tokens are separated by delimiters (e.g., whitespace). l A tokenizer object is constructed with a given string as an argument. l The second optional argument is a string that lists all delimiters (default is whitespace).

9-27 StringTokenizer (cont’d) import java.util.StringTokenizer;... String str = input.readLine(); StringTokenizer q = new StringTokenizer (str); // or: // new StringTokenizer (str, ";+ \t, "); int n = q.countTokens (); while ( q.hasMoreTokens() ) { String word = q.nextToken();... Delimiters are whitespace The number of found tokens All delimiters

9-28 EquationSolver Applet

9-29 EquationSolver (cont’d) l Uses many techniques discussed earlier: –trim, substring, and other String methods clean the input, surround operation signs with spaces –StringTokenizer extracts tokens –Character.isDigit, and other Character methods identify tokens –Integer.parseInt converts tokens to numbers –String's + operator combines strings and numbers to generate output

9-30 Review: l What makes the String class unusual? l How can you include a double quote character into a literal string? l Is "length".length() allowed syntax? If so, what is the returned value? l Define immutable objects. l Does immutability of Strings make Java more efficient or less efficient?

9-31 Review (cont’d): l How do you declare an empty string? l Why are String constructors not used very often? l If the value of String city is "Boston", what is returned by city.charAt (2)? By city.substring (2, 4)? l How come String doesn’t have a setCharAt method? l Is s1 += s2 the same as s1 = s1 + s2 for strings?

9-32 Review (cont’d): l What do the indexOf methods do? Name a few overloaded versions. l What is more efficient for strings: == and other relational operators or equals and compareTo methods? l What does the trim method do? l What does s.toUpperCase() do to s? l What does the toString method return for a String object?

9-33 Review (cont’d): l Name a simple way to convert a number into a string. l Which class has a method for converting a String into an int? l Name a few Character methods that help identify the category to which a given character belongs. l What is the StringTokenizer class used for?