Characters, Strings and the String Buffer Jim Burns.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Strings Testing for equality with strings.
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 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
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.
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.
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
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 ,
1 Strings and String Operations Overview l Creating String Objects l Substring methods l The Concatenation Operator l Strings are Immutable l Other Methods.
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.
©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 
1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their.
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
CIS 234: Strings (click, scroll down)Strings Dr. Ralph D. Westfall April, 2010.
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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
Chapter 2: Using Data.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
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.
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.
10-2 Chapter 10 discusses the following main topics:  Introduction to Wrapper Classes  Character Testing and Conversion with the Character Class  More.
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.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
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,
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
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 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,
Casting, Wrapper Classes, Static Methods, JOptionPane Class.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
String and StringBuffer classes
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Strings.
The StringBuffer Class 
2.5 Another Java Application: Adding Integers
Multiple variables can be created in one declaration
String Handling in JAVA
Primitive Types Vs. Reference Types, Strings, Enumerations
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
Lecture 07 String Jaeki Song.
Introduction to Java Programming
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
Chapter 2: Java Fundamentals cont’d
Just Enough Java 17-May-19.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

Characters, Strings and the String Buffer Jim Burns

Identifying problems that can occur when you manipulate string data String is not a simple data type like int, float, or double String is not a simple data type like int, float, or double String creates an instance of a class, the class String String creates an instance of a class, the class String As such it contains a reference or an address and not the actual string As such it contains a reference or an address and not the actual string So you cannot do equality comparisons of two different instances of String, because you are simply testing if the addresses are the same So you cannot do equality comparisons of two different instances of String, because you are simply testing if the addresses are the same

An example of incorrect code import javax.swing.JOptionPane; public class TryToCompareStrings { public static void main(String[] args) public static void main(String[] args) { String aName = "Carmen"; String aName = "Carmen"; String anotherName; String anotherName; anotherName = JOptionPane.showInputDialog(null, anotherName = JOptionPane.showInputDialog(null, "Enter your name"); "Enter your name"); if(aName == anotherName) if(aName == anotherName) JOptionPane.showMessageDialog(null, aName + JOptionPane.showMessageDialog(null, aName + " equals " + anotherName); " equals " + anotherName); else else JOptionPane.showMessageDialog(null, aName + JOptionPane.showMessageDialog(null, aName + " does not equal " + anotherName); " does not equal " + anotherName); System.exit(0); System.exit(0); } }

Correct Code import javax.swing.JOptionPane; import javax.swing.JOptionPane; public class CompareStrings public class CompareStrings { public static void main(String[] args) public static void main(String[] args) { { String aName = "Carmen"; String aName = "Carmen"; String anotherName; String anotherName; anotherName = JOptionPane.showInputDialog(null, anotherName = JOptionPane.showInputDialog(null, "Enter your name"); "Enter your name"); if(aName.equals(anotherName)) if(aName.equals(anotherName)) JOptionPane.showMessageDialog(null, aName + JOptionPane.showMessageDialog(null, aName + " equals " + anotherName); " equals " + anotherName); else else JOptionPane.showMessageDialog(null, aName + JOptionPane.showMessageDialog(null, aName + " does not equal " + anotherName); " does not equal " + anotherName); System.exit(0); System.exit(0); } } }

Three classes for working with strings Character—a class whose instances can hold a single character value—provides methods that can manipulate or inspect single-character data Character—a class whose instances can hold a single character value—provides methods that can manipulate or inspect single-character data String—a class for working with fixed-string data—that is unchanging data composed of multiple characters, strings that are immutable String—a class for working with fixed-string data—that is unchanging data composed of multiple characters, strings that are immutable StringBuffer—a class for storing and manipulating changeable data composed of mulltiple characters StringBuffer—a class for storing and manipulating changeable data composed of mulltiple characters

Manipulating Characters We know the char data type can hold any single character We know the char data type can hold any single character Character class provides the following methods Character class provides the following methods isUpperCase(), toUpperCase(), isLowerCase(), toLowerCase(), isDigit(), isLetter(), isLetterOrDigit(), isWhitespace() isUpperCase(), toUpperCase(), isLowerCase(), toLowerCase(), isDigit(), isLetter(), isLetterOrDigit(), isWhitespace() Methods that begin with ‘is…’ perform tests delivering true or false values Methods that begin with ‘is…’ perform tests delivering true or false values Methods that begin with ‘to…’ perform conversions Methods that begin with ‘to…’ perform conversions

Declaring a String Object We know that characters enclosed within double quotation marks are literal strings We know that characters enclosed within double quotation marks are literal strings We’ve learned to print these strings using println() and showMessageDialog() We’ve learned to print these strings using println() and showMessageDialog() An literal string is an unnamed object, or anonymous object, of the String class An literal string is an unnamed object, or anonymous object, of the String class A String variable is simply a named object of the same class. A String variable is simply a named object of the same class. The class String is defined in java.lang.String, which is automatically imported into every program you write The class String is defined in java.lang.String, which is automatically imported into every program you write

Declaring a String variable When you declare a String variable, the String itself—that is, the series of characters contained in the String—is distinct from the variable you use to refer to it. When you declare a String variable, the String itself—that is, the series of characters contained in the String—is distinct from the variable you use to refer to it. Can initialize a String variable with or without a String constructor Can initialize a String variable with or without a String constructor

With or without a String Constructor With the constructor With the constructor String aGreeting = new String(“Hello”); Without the constructor Without the constructor String aGreeting = “Hello”; Unlike other classes, you can create a String object without using the keyword new or explicitly calling the class constructor Unlike other classes, you can create a String object without using the keyword new or explicitly calling the class constructor

Comparing String Values Consider the following two statements: String aGreeting = “hello”; aGreeting = “Bonjour”; These statements are syntactically correct. What happens is that the address contained in aGreeting is changed to point to “Bonjour” rather than “hello”, both of which are contained at different locations in memory. Eventually, the garbage collector discards the “hello” characters.

Comparing String Values The String class provides methods for comparing strings The String class provides methods for comparing strings In the example above the == sign is comparing memory addresses, not the actual strings. In the example above the == sign is comparing memory addresses, not the actual strings. The String class equals() method evaluates the contents of two String objects to determine if they are equivalent. The String class equals() method evaluates the contents of two String objects to determine if they are equivalent.

Import javax.swing.JOptionPane; Public class CompareStrings { public static void main(String[] args) { String aName = “Carmen”, anotherName; anotherName = JOptionPane. showInputDialog(null, “Enter your name”); if(aName.equals(anotherName)) JOptionPane.showMessageDialog(null, aName + “ equals “ + anotherName); else JOptionPane.showMessageDialog(null, aName + “ does not equal “ + anotherName)); System.exit(0);}

The equals() method From the code above, we can see that the equals() method returns a Boolean value of true or false From the code above, we can see that the equals() method returns a Boolean value of true or false

equalsIgnoreCase() Method Similar to the equals() method Similar to the equals() method Ignores case Ignores case String aName = “Roger”; If(aName.equalsIgnoreCase(“roGER”))… evaluates to true evaluates to true

compareTo() method Returns an integer that is the numeric difference between the first two non- matching characters

Using other String Methods toUpperCase() and toLowerCase() convert any String to its uppercase and lowercase equivalent toUpperCase() and toLowerCase() convert any String to its uppercase and lowercase equivalent Length() returns the length of a String Length() returns the length of a String

import javax.swing.*; public class BusinessLetter { public static void main(String[] args) public static void main(String[] args) { String name; String name; String firstName = ""; String firstName = ""; String familyName = ""; String familyName = ""; int x; int x; char c; char c; name = JOptionPane.showInputDialog(null, name = JOptionPane.showInputDialog(null, "Please enter customer's first and last name"); "Please enter customer's first and last name"); x = 0; x = 0; while(x < name.length()) while(x < name.length()) { if(name.charAt(x) == ' ') if(name.charAt(x) == ' ') { firstName = name.substring(0, x); firstName = name.substring(0, x); familyName = name.substring(x + 1, name.length()); familyName = name.substring(x + 1, name.length()); x = name.length(); x = name.length(); } ++x; ++x; } JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(null, "Dear " + firstName + "Dear " + firstName + ",\nI am so glad we are on a first name basis" + ",\nI am so glad we are on a first name basis" + "\nbecause I would like the opportunity to" + "\nbecause I would like the opportunity to" + "\ntalk to you about an affordable insurance" + "\ntalk to you about an affordable insurance" + "\nprotection plan for the entire " + familyName + "\nprotection plan for the entire " + familyName + "\nfamily. Call A-One Family Insurance today" + "\nfamily. Call A-One Family Insurance today" + "\nat "); "\nat "); System.exit(0); System.exit(0); } }

x = 0; x = 0; while(x < name.length()) while(x < name.length()) { { if(name.charAt(x) == ' ') if(name.charAt(x) == ' ') { { firstName = name.substring(0, x); firstName = name.substring(0, x); familyName = name.substring(x + 1, name.length()); familyName = name.substring(x + 1, name.length()); x = name.length(); x = name.length(); } } ++x; ++x; } }

Concatenation You know you can concatenate strings to strings as in System.out.println(firstName + “ “ + lastName); You know you can concatenate strings to strings as in System.out.println(firstName + “ “ + lastName);

Concatenation—numbers to strings by using + The following is permissible: The following is permissible: Int myAge = 25; String aString = “My age is “ + myAge; Another example would be Another example would be String anotherString; String anotherString; float someFloat = 12.34f; anotherString = “” + someFloat;

Concatenation by using the toString() method String theString; Int someInt = 10; theString = Integer.toString(someInt); String aString; double someDouble = 8.25; aString = Double.toString(someDouble);

Converting Strings to Numbers Use a wrapper like the Integer class which is a part of java.lang Use a wrapper like the Integer class which is a part of java.lang A wrapper is a class that is “wrapped around” a simpler element A wrapper is a class that is “wrapped around” a simpler element Int anInt = Integer.parseInt(“649”) stores the value 649 in the variable anInt Int anInt = Integer.parseInt(“649”) stores the value 649 in the variable anInt

public class TestCharacter { public static void main(String[] args) public static void main(String[] args) { char aChar = 'C'; char aChar = 'C'; System.out.println("The character is " + aChar); System.out.println("The character is " + aChar); if(Character.isUpperCase(aChar)) if(Character.isUpperCase(aChar)) System.out.println(aChar + " is uppercase"); System.out.println(aChar + " is uppercase"); else else System.out.println(aChar + " is not uppercase"); System.out.println(aChar + " is not uppercase"); if(Character.isLowerCase(aChar)) if(Character.isLowerCase(aChar)) System.out.println(aChar + " is lowercase"); System.out.println(aChar + " is lowercase"); else else System.out.println(aChar + " is not lowercase"); System.out.println(aChar + " is not lowercase"); aChar = Character.toLowerCase(aChar); aChar = Character.toLowerCase(aChar); System.out.println("After toLowerCase(), aChar is " + aChar); System.out.println("After toLowerCase(), aChar is " + aChar); aChar = Character.toUpperCase(aChar); aChar = Character.toUpperCase(aChar); System.out.println("After toUpperCase(), aChar is " + aChar); System.out.println("After toUpperCase(), aChar is " + aChar); if(Character.isLetterOrDigit(aChar)) if(Character.isLetterOrDigit(aChar)) System.out.println(aChar + " is a letter or digit"); System.out.println(aChar + " is a letter or digit"); else else System.out.println(aChar + " is neither a letter nor a digit"); System.out.println(aChar + " is neither a letter nor a digit"); if(Character.isWhitespace(aChar)) if(Character.isWhitespace(aChar)) System.out.println(aChar + " is whitespace"); System.out.println(aChar + " is whitespace"); else else System.out.println(aChar + " is not whitespace"); System.out.println(aChar + " is not whitespace"); }} //see next slide

Test Character App public class TestCharacter { public static void main(String[] args) public static void main(String[] args) { char aChar = 'C'; char aChar = 'C'; System.out.println("The character is " + aChar); System.out.println("The character is " + aChar); if(Character.isUpperCase(aChar)) if(Character.isUpperCase(aChar)) System.out.println(aChar + " is uppercase"); System.out.println(aChar + " is uppercase"); else else System.out.println(aChar + " is not uppercase"); System.out.println(aChar + " is not uppercase"); if(Character.isLowerCase(aChar)) if(Character.isLowerCase(aChar)) System.out.println(aChar + " is lowercase"); System.out.println(aChar + " is lowercase"); else else

System.out.println(aChar + " is not lowercase"); System.out.println(aChar + " is not lowercase"); aChar = Character.toLowerCase(aChar); aChar = Character.toLowerCase(aChar); System.out.println("After toLowerCase(), aChar is " + aChar); System.out.println("After toLowerCase(), aChar is " + aChar); aChar = Character.toUpperCase(aChar); aChar = Character.toUpperCase(aChar); System.out.println("After toUpperCase(), aChar is " + aChar); System.out.println("After toUpperCase(), aChar is " + aChar); if(Character.isLetterOrDigit(aChar)) if(Character.isLetterOrDigit(aChar)) System.out.println(aChar + " is a letter or digit"); System.out.println(aChar + " is a letter or digit"); else else System.out.println(aChar + " is neither a letter nor a digit"); System.out.println(aChar + " is neither a letter nor a digit"); if(Character.isWhitespace(aChar)) if(Character.isWhitespace(aChar)) System.out.println(aChar + " is whitespace"); System.out.println(aChar + " is whitespace"); else else System.out.println(aChar + " is not whitespace"); System.out.println(aChar + " is not whitespace"); }}

Learning about the StringBuffer Class Some strings are not constants, not immutable Some strings are not constants, not immutable String someChars = “Goodbye”; someChars = “Goodbye Everybody”; someChars = “Goodbye” + “ Everybody”; You cannot change the string “Goodbye” You cannot change the string “Goodbye” To overcome these limitations, you can use the StringBuffer class To overcome these limitations, you can use the StringBuffer class The StringBuffer class was invented to accommodate strings that are not immutable (constants) The StringBuffer class was invented to accommodate strings that are not immutable (constants)

The StringBuffer Class Uses a buffer that is much larger than any one string; actual size of the buffer is the capacity Uses a buffer that is much larger than any one string; actual size of the buffer is the capacity Provides methods that can change individual characters within a string Provides methods that can change individual characters within a string Must initialize StringBuffer objects as follows: Must initialize StringBuffer objects as follows: StringBuffer eventString = new StringBuffer(“Hello there”); StringBuffer eventString = new StringBuffer(“Hello there”); Cannot use StringBuffer eventString = “Hello there”; Cannot use StringBuffer eventString = “Hello there”;

Methods in the StringBuffer Class setLength() will change the length of a String in a StringBuffer object setLength() will change the length of a String in a StringBuffer object capacity() will find the capacity of an object capacity() will find the capacity of an object Has four constructors: Has four constructors: public StringBuffer() constructs a StringBuffer with no characters and a default size of 16 characters public StringBuffer() constructs a StringBuffer with no characters and a default size of 16 characters public StringBuffer(int Capacity) creates a StringBuffer with no characters and a capacity defined by the parameter public StringBuffer(int Capacity) creates a StringBuffer with no characters and a capacity defined by the parameter public StringBuffer(String s) contains the same characters as those stored in the String object s public StringBuffer(String s) contains the same characters as those stored in the String object s

Still more methods in the StringBuffer Class Append() lets you add characters to the end of a StringBuffer object Append() lets you add characters to the end of a StringBuffer object Insert() lets you add characters at a specific location within a StringBuffer object Insert() lets you add characters at a specific location within a StringBuffer object StringBuffer someBuffer = new StringBuffer(“Happy Birthday); someBuffer.insert(6,”30 th “); Produces “Happy 30 th Birthday”

Still more methods in StringBuffer setCharAt() method allows you to change a single character at a specified location setCharAt() method allows you to change a single character at a specified location someBuffer.setCharAt(6,’4’); someBuffer.setCharAt(6,’4’); Changes someBuffer to “Happy 40 th Birthday” Changes someBuffer to “Happy 40 th Birthday” Can use charAt() method will return the character at an offset number of positions from the first character Can use charAt() method will return the character at an offset number of positions from the first character StringBuffer text = new StringBuffer(“Java Programming); StringBuffer text = new StringBuffer(“Java Programming); Then text.charAt(5) returns the character ‘P’. Then text.charAt(5) returns the character ‘P’.

package Strings; import javax.swing.*; public class RepairName { /** args args */ */ public static void main(String[] args) { String name, saveOriginalName; int stringLength; int i; char c; name = JOptionPane.showInputDialog(null, "Please enter your first and last name"); saveOriginalName = name; stringLength = name.length(); for (i=0; i < stringLength; i++) { c = name.charAt(i); if(i==0) { c = Character.toUpperCase(c); name = c + name.substring(1, stringLength); }else if(name.charAt(i) == ' ') {++i; c = name.charAt(i); c = Character.toUpperCase(c); name = name.substring(0, i) + c + name.substring(i + 1, stringLength); }} JOptionPane.showMessageDialog(null, "Original name was " + saveOriginalName + "\nRepaired name is " + name); System.exit(0); } // TODO Auto-generated method stub }