Title: Characters and Strings
1Characters and Strings
- Chapter 7
- Dr. James Jiang
Characters and Strings
2String class
- Defined in java.lang.String
- String aGreeting new String(Hello)
- OR
- String aGreeting Hello
3Comparing Strings
- String variable name is a reference to a location
in memory - String aGreeting Hello
- aGreeting Bonjour
aGreeting holds an address that points to
Hello aGreeting holds a new address that points
to Bonjour
The garbage collector will discard Hello
Strings and other objects that cant be changed
are known as immutable
4The equals() method
- Evaluates the contents of two String objects to
see if they are the same - Method returns boolean true if equivalent
if(aName.equals(anotherName))
5The equalsIgnoreCase() method
- Evaluates the contents of two String objects to
see if they are the same - Ignores the case of the letters
aName DEBBIE anotherName
Debbie if(aName.equalsIgnoreCase(anotherName))
Returns true
6The compareTo() method
- Returns 0 if strings are equal
- negative ? calling less than argument
- positive I? calling greater than argument
- Example aName Roger
- aName.compareTo(Robert) ? 5
- For alphabetical order
- if(aWord.compareTo(anotherWord)
- aWord hamster anotherWord iguana
Returns true
7Other String Methods
- toUpperCase()
- aWord something
- aWord aWord.toUpperCase()
- toLowerCase()
- indexOf()
- String myName Stacy
- myName.indexOf(a) myName.indexOf(q)
- charAt()
- myName.charAt(0)
Results?
8Other String Methods
- endsWith()
- myName.startsWith(Sta) returns True
- replace()
String yourName Annette String goofyName
yourName.replace(n, X)
AXXette
9toString() Method
- Converts primitive type to a String
- How do we know that toString() is an overloaded
method?
int someInt 4 theString Integer.toString(some
Int)
4
10subString() Method
- subString(start position, end position)
String dayOfWeek Monday, Tuesday,
Wednesday, Thursday, Friday String
sentence int x for(x 0 x x) sentence The abbreviation for
dayOfWeekx is dayOfWeekx.substring(0,3
) System.out.println(sentence)
11Converting Strings to Integers
- To convert a String to an integer, use the
Integer class - parseInt() is a method of the Integer class
- anInt Integer.parseInt(649)
12Converting Strings to Doubles
- To convert a String to a double, use the Double
class - double dvalue Double.parseDouble(147.82)
- valueOf()and doubleValue() are methods of the
Double class - String stringValue new String(147.82)
- Double tempValue Double.valueOf(stringValue)
- double doubleValue tempvalue.doubleValue()
13Example of Input
- import java.swing.x
- public class NumIn
-
- public static void main(String args)
- String inputString
- int inputNumber
- inputString JOptionPane.showInputDialo
g(null, Enter the number) - inputNumber Integer.parseInt(inputStri
ng) - if (inputNumber 100)
- JOptionPane.showMessageDialog(null,
A surchage will apply) - System.exit(0)
-