characters strings
TRANSCRIPT
-
7/27/2019 Characters Strings
1/33
Characters, Strings and the String
Buffer
Jim Burns
-
7/27/2019 Characters Strings
2/33
Identifying problems that can occur when
you manipulate string data
String is not a simple data type like int, float,or double
String creates an instance of a class, the class
String As such it contains a reference or an address
and not the actual string
So you cannot do equality comparisons of twodifferent instances of String, because you aresimply testing if the addresses are the same
-
7/27/2019 Characters Strings
3/33
An example of incorrect code
import javax.swing.JOptionPane;
public class TryToCompareStrings{
public static void main(String[] args)
{
String aName = "Carmen";
String anotherName;anotherName = JOptionPane.showInputDialog(null,
"Enter your name");
if(aName == anotherName)
JOptionPane.showMessageDialog(null, aName +
" equals " + anotherName);
else
JOptionPane.showMessageDialog(null, aName +
" does not equal " + anotherName);
System.exit(0);
}
}
-
7/27/2019 Characters Strings
4/33
Correct Code import javax.swing.JOptionPane;
public class CompareStrings
{ public static void main(String[] args)
{
String aName = "Carmen";
String 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);
}
}
-
7/27/2019 Characters Strings
5/33
Three classes for working with strings
Charactera class whose instances can hold a single
character valueprovides methods that can
manipulate or inspect single-character data
Stringa class for working with fixed-string datathat is unchanging data composed of multiple
characters, strings that are immutable
StringBuffera class for storing and manipulating
changeable data composed of mulltiple characters
-
7/27/2019 Characters Strings
6/33
Manipulating Characters
We know the char data type can hold anysingle character
Character class provides the following
methods isUpperCase(), toUpperCase(), isLowerCase(),
toLowerCase(), isDigit(), isLetter(),isLetterOrDigit(), isWhitespace()
Methods that begin with is perform testsdelivering true or false values
Methods that begin with to performconversions
-
7/27/2019 Characters Strings
7/33
Declaring a String Object
We know that characters enclosed within doublequotation marks are literal strings
Weve learned to print these strings using println()and showMessageDialog()
An literal string is an unnamed object, or anonymousobject, of the String class
A String variable is simply a named object of thesame class.
The class String is defined in java.lang.String, which isautomatically imported into every program you write
-
7/27/2019 Characters Strings
8/33
-
7/27/2019 Characters Strings
9/33
With or without a String Constructor
With the constructor
String aGreeting = new String(Hello);
Without the constructor
String aGreeting = Hello;
Unlike other classes, you can create a String objectwithout using the keyword new or explicitly calling
the class constructor
-
7/27/2019 Characters Strings
10/33
Comparing String Values
Consider the following two statements:
String aGreeting = hello;
aGreeting = Bonjour;
These statements are syntactically correct. Whathappens is that the address contained in aGreeting ischanged to point to Bonjour rather than hello,both of which are contained at different locations inmemory. Eventually, the garbage collector discardsthe hello characters.
-
7/27/2019 Characters Strings
11/33
Comparing String Values
The String class provides methods for
comparing 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.
I j i JO i P
-
7/27/2019 Characters Strings
12/33
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);
elseJOptionPane.showMessageDialog(null, aName + does
not equal + anotherName));
System.exit(0);
}
-
7/27/2019 Characters Strings
13/33
The equals() method
From the code above, we can see that the
equals() method returns a Boolean value of
true or false
-
7/27/2019 Characters Strings
14/33
equalsIgnoreCase() Method
Similar to the equals() method
Ignores case
String aName = Roger;If(aName.equalsIgnoreCase(roGER))
evaluates to true
-
7/27/2019 Characters Strings
15/33
compareTo() method
Returns an integer that is the numeric difference
between the first two non-matching
characters
-
7/27/2019 Characters Strings
16/33
-
7/27/2019 Characters Strings
17/33
Using other String Methods
toUpperCase() and toLowerCase() convert any
String to its uppercase and lowercase
equivalent
Length() returns the length of a String
import javax swing *;
-
7/27/2019 Characters Strings
18/33
import javax.swing. ;
public class BusinessLetter
{
public static void main(String[] args)
{
String name;
String firstName = "";
String familyName = "";
int x;char c;
name = JOptionPane.showInputDialog(null,
"Please enter customer's first and last name");
x = 0;
while(x < name.length())
{
if(name.charAt(x) == ' ')
{
firstName = name.substring(0, x);familyName = name.substring(x + 1, name.length());
x = name.length();
}
++x;
}
JOptionPane.showMessageDialog(null,
"Dear " + firstName +
",\nI am so glad we are on a first name basis" +
"\nbecause I would like the opportunity to" +"\ntalk to you about an affordable insurance" +
"\nprotection plan for the entire " + familyName +
"\nfamily. Call A-One Family Insurance today" +
"\nat 1-800-555-9287.");
System.exit(0);
}
}
0
-
7/27/2019 Characters Strings
19/33
x = 0;
while(x < name.length())
{
if(name.charAt(x) == ' ')
{
firstName = name.substring(0, x);
familyName = name.substring(x + 1,name.length());
x = name.length();
}
++x;
}
-
7/27/2019 Characters Strings
20/33
-
7/27/2019 Characters Strings
21/33
Concatenation
You know you can concatenate strings to
strings as in System.out.println(firstName +
+ lastName);
-
7/27/2019 Characters Strings
22/33
Concatenationnumbers to strings by
using +
The following is permissible:
Int myAge = 25;
String aString = My age is + myAge; Another example would be
String anotherString;
float someFloat = 12.34f;anotherString = + someFloat;
-
7/27/2019 Characters Strings
23/33
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);
-
7/27/2019 Characters Strings
24/33
Converting Strings to Numbers
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
Int anInt = Integer.parseInt(649) stores the
value 649 in the variable anInt
public class TestCharacter
-
7/27/2019 Characters Strings
25/33
p
{
public static void main(String[] args)
{
char aChar = 'C';
System.out.println("The character is " + aChar);
if(Character.isUpperCase(aChar))
System.out.println(aChar + " is uppercase");else
System.out.println(aChar + " is not uppercase");
if(Character.isLowerCase(aChar))
System.out.println(aChar + " is lowercase");
else
System.out.println(aChar + " is not lowercase");
aChar = Character.toLowerCase(aChar);
System.out.println("After toLowerCase(), aChar is " + aChar);
aChar = Character.toUpperCase(aChar);
System.out.println("After toUpperCase(), aChar is " + aChar);
if(Character.isLetterOrDigit(aChar))
System.out.println(aChar + " is a letter or digit");
else
System.out.println(aChar + " is neither a letter nor a digit");
if(Character.isWhitespace(aChar))System.out.println(aChar + " is whitespace");
else
System.out.println(aChar + " is not whitespace");
}
}
//see next slide
T Ch A
-
7/27/2019 Characters Strings
26/33
Test Character Apppublic class TestCharacter
{
public static void main(String[] args){
char aChar = 'C';
System.out.println("The character is " + aChar);
if(Character.isUpperCase(aChar))System.out.println(aChar + " is uppercase");
else
System.out.println(aChar + " is not uppercase");
if(Character.isLowerCase(aChar))
System.out.println(aChar + " is lowercase");
else
System out println(aChar + " is not lowercase");
-
7/27/2019 Characters Strings
27/33
System.out.println(aChar + is not lowercase );
aChar = Character.toLowerCase(aChar);
System.out.println("After toLowerCase(), aChar is " + aChar);
aChar = Character.toUpperCase(aChar);
System.out.println("After toUpperCase(), aChar is " + aChar);if(Character.isLetterOrDigit(aChar))
System.out.println(aChar + " is a letter or digit");
else
System.out.println(aChar + " is neither a letter nor a digit");
if(Character.isWhitespace(aChar))
System.out.println(aChar + " is whitespace");
else
System.out.println(aChar + " is not whitespace");
}}
-
7/27/2019 Characters Strings
28/33
Learning about the StringBuffer Class
Some strings are not constants, not immutable
String someChars = Goodbye;
someChars = Goodbye Everybody;
someChars = Goodbye + Everybody; You cannot change the string Goodbye
To overcome these limitations, you can use theStringBuffer class
The StringBuffer class was invented to accommodatestrings that are not immutable (constants)
-
7/27/2019 Characters Strings
29/33
The StringBuffer Class
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
Must initialize StringBuffer objects as follows:
StringBuffer eventString = new StringBuffer(Hello
there);
Cannot use StringBuffer eventString = Hello
there;
M h d i h S i B ff Cl
-
7/27/2019 Characters Strings
30/33
Methods in the StringBuffer Class setLength() will change the length of a String in
a StringBuffer object capacity() will find the capacity of an object
Has four constructors:
public StringBuffer() constructs a StringBuffer withno 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(String s) contains the same
characters as those stored in the String object s
-
7/27/2019 Characters Strings
31/33
Still more methods in the StringBuffer
Class
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
StringBuffer someBuffer = new StringBuffer(Happy
Birthday);
someBuffer.insert(6,30th);
Produces Happy 30thBirthday
-
7/27/2019 Characters Strings
32/33
Still more methods in StringBuffer
setCharAt() method allows you to change a single
character at a specified location
someBuffer.setCharAt(6,4);
Changes someBuffer to Happy 40th
Birthday Can use charAt() method will return the character at
an offset number of positions from the first character
StringBuffer text = new StringBuffer(Java Programming);
Then text.charAt(5) returns the character P.
package Strings;import javax swing *;
-
7/27/2019 Characters Strings
33/33
import javax.swing. ;
publicclass RepairName {
/**
* @param args
*/
publicstaticvoid 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
}