String Class. Objectives and Goals Identify 2 types of Strings: Literal & Symbolic. Learn about String constructors and commonly used methods Learn several.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
©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 ,
Comparing Data Comparing More than Numbers. Comparing Data When comparing data using boolean expressions, it's important to understand the nuances of.
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
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.
ECE122 L8: More Conditional Statements February 7, 2007 ECE 122 Engineering Problem Solving with Java Lecture 8 More Conditional Statements.
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.
Logical Operators and Conditional statements
©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 
CIS 234: Strings (click, scroll down)Strings Dr. Ralph D. Westfall April, 2010.
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.
1 Data Comparisons and Switch Data Comparisons Switch Reading for this class: L&L 5.3,
From C++ to Java A whirlwind tour of Java for C++ programmers.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
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.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
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.
Chapter 7: Characters, Strings, and the StringBuilder.
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
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 JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
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 String Builder. System.String string is the alias for System.String A string is an object of class string in the System namespace representing.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
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.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
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:
17-Feb-16 String and StringBuilder Part I: String.
"Chapter 9" Strings Java Methods Maria Litvin Gary Litvin
The String Class.
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
EKT 472: Object Oriented Programming
String and String Buffers
String String Builder.
String Class.
Strings Chapter 6.
Primitive Types Vs. Reference Types, Strings, Enumerations
Modern Programming Tools And Techniques-I Lecture 11: String Handling
String and StringBuilder
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
String and StringBuilder
String and StringBuilder
Java – String Handling.
String and StringBuilder
String methods 26-Apr-19.
Strings in Java.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

String Class

Objectives and Goals Identify 2 types of Strings: Literal & Symbolic. Learn about String constructors and commonly used methods Learn several useful methods of the Character class Understand immutability of strings Learn to format numbers into strings and extract numbers from strings Learn about the StringBuffer class

String Class java.lang package Two types of String –Literal String – characters in double quotes –Symbolic String – variable that represents a String

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

Literal Strings “words” in double quotes Literals act as an object Literal Strings have access to all the methods of String class as a String object does.

Literal Strings Literal strings are anonymous constant objects of the String class that are defined as text in double quotes. Literal strings don’t have to be constructed: they are “just there.”

Literal Strings (cont’d) can be assigned to String variables. can be passed to methods and constructors as parameters. Literal Strings are treated as symbolic strings by accessing String properties. have methods you can call: String fileName = "fish.dat"; button = new JButton("Next slide"); if ("Start". equals(cmd))...

Literal Strings (cont’d) The string text may include “escape” characters For example: –\\ stands for \ –\n stands for the newline character String s1 = "Biology”; String s2 = "C:\\jdk1.4\\docs " ; String s3 = "Hello\n";

Creating a String Object String name; –Null String Reference –Has no length –Calling a null String object will cause a NullPointerException Error String name = “”; –Empty String –Has a size of 0 String name = new String(); –Creates an empty String String name = new String(“Bob”); –Creates an object that has the name Bob –Its length is 3.

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

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

Immutability Once created, a string cannot be changed: none of its methods changes the string. Such objects are called immutable. Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change. You can create a new String objects that have the new version of the original string’s value.

Immutability (cont’d) Advantage: more efficient, no need to copy. String s1 = "Sun"; String s2 = s1; String s1 = "Sun"; String s2 = new String(s1); s1 s2 s1 s2 OK Less efficient: wastes memory "Sun"

Immutability (cont’d) 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.toUpperCase(s.charAt (0)); s = ch + s.substring (1); s "sun" "Sun"

String Assignment Strings are immutable. Assigning a new string to a String object simply changes the object reference to point to the new string in memory: String text; text = "heLlO"; text = text.toLowerCase(); text heLlO hello

Reference When you create a symbolic variable that represents a String, it doesn’t contain the string object, it contains the reference (address) of the memory location of the string object.

Examples of referencing String Objects String s1 = “Bob”; –s1  “Bob” s2 = s1; –s1 & s2  “bob” points to the same memory location. s2 = new String(s1); –s1  “Bob” –s2  “Bob” two different memory locations.

Size and character location of a String Size is the number of characters a String has including and blank spaces in the String. Character positions in strings are counted starting from 0. Location  The first letter in the String is in location 0 and the second letter is in the position 1 and so on. Always make sure that when you refer to the positions of characters in strings, they fall in the range from 0 to string’s length – 1.

Methods length() charAt(int); substring(int); substring(int, int); concat(str); compareTo(str); compareToIgnoreCase(str); equals(str); equalsIgnoreCase(str); indexOf(char); indexOf(char, int); indexOf(str); indexOf(str, int);

Methods Continued lastIndexOf(char); lastindexOf(char, int); lastIndexOf(str); lastIndexOf(str, int); trim(); replace(oldChar, newChar); toUpperCase(); toLowerCase();

AP String Methods compareTo(str); equals(str); indexOf(str); length(); substring(int, int); substring(int);

Method Overloading When you have more than one method with the same name. The parameter list are different and the computer determine which method to pick by the parameter list. Example: –substring(int); –substring(int, int);

Comparing Characters In Unicode, the digit characters (0-9) are contiguous and in order Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order CharactersUnicode Values 0 – 948 through 57 A – Z65 through 90 a – z97 through 122

Comparing Strings The String class includes several methods for comparing two strings: equals() equalsIgnoreCase() compareTo() compareToIgnoreCase() indexOf() lastIndexOf() startsWith() endsWith()

Comparing Strings Remember that in Java a character string is an object The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name");

Comparing Strings We cannot use the relational operators to compare strings The String class contains a method called compareTo to determine if one string comes before another A call to name1.compareTo(name2) –returns zero if name1 and name2 are equal (contain the same characters) –returns a negative value if name1 is less than name2 –returns a positive value if name1 is greater than name2

Comparing Strings if (name1.compareTo(name2) < 0) System.out.println (name1 + "comes first"); else if (name1.compareTo(name2) == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first"); Because comparing characters and strings is based on a character set, it is called a lexicographic ordering

Lexicographic Ordering Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically) Therefore "book" comes before "bookcase"

Comparing Objects The == operator can be applied to objects – it returns true if the two references are aliases of each other The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator It has been redefined in the String class to compare the characters in the two strings When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate

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

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 strawberry i

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

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'); 15 Returns: (not found) (starts searching at position 9)

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

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

Replacements (cont’d) Example: how to convert s1 to upper case A common bug: S1 is not assigned to a memory location that holds the change. s1 = s1.toUpperCase(); s1.toUpperCase(); s1 remains unchanged

Numbers to Strings 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); Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. They also provide useful static methods.

Numbers to Strings (cont’d) The DecimalFormat class can be used for formatting numbers into strings. import java.text.DecimalFormat;... DecimalFormat money = new DecimalFormat("0.00");... double amt = ;... String s = money.format (amt); "56.74"

Numbers to Strings (cont’d) Java 5.0 added printf and format methods: int m = 5, d = 19, y = 2007; double amt = 123.5; System.out.printf ( "Date: %02d/%02d/%d Amount = %7.2f\n", m, d, y, amt); String s = String. format( "Date: %02d/%02d/%d Amount = %7.2f\n", m, d, y, amt); Displays, sets s to: "Date: 05/19/2007 Amount "

Numbers from Strings These methods throw a NumberFormatException if s does not represent a valid number (integer, real number, respectively). String s1 = "-123", s2 = "123.45"; int n = Integer.parseInt(s1); double x = Double.parseDouble(s2);

Numbers from Strings (cont’d) A safer way: int n; do { try { n = Integer.parseInt(s); } catch (NumberFormatException ex) { System.out.println("Invalid input, reenter"); } } while (...);

Character Methods java.lang.Character is a “wrapper” class that represents characters as objects. Character has several useful static methods that determine the type of a character (letter, digit, etc.). Character also has methods that convert a letter to the upper or lower case.

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.

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

The StringBuffer Class Represents a string of characters as a mutable object Constructors: StringBuffer() // empty StringBuffer of the default capacity StringBuffer(n) // empty StringBuffer of a given capacity StringBuffer(str) // converts str into a StringBuffer Adds setCharAt, insert, append, and delete methods The toString method converts this StringBuffer into a String

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

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

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

Review (cont’d): Name a simple way to convert a number into a string. Which class has a method for converting a String into an int? Name a few Character methods that help identify the category to which a given character belongs. What is the difference between the String and StringBuffer classes?