Java Reference
In-Depth Information
4.
You can use the
concat
method to concatenate two strings, or the plus (
+
) operator
to concatenate two or more strings.
5.
You can use the
substring
method to obtain a substring from the string.
6.
You can use the
equals
and
compareTo
methods to compare strings. The
equals
method returns
true
if two strings are equal, and
false
if they are not equal. The
compareTo
method returns
0
, a positive integer, or a negative integer, depending on
whether one string is equal to, greater than, or less than the other string.
7.
A
regular expression
(abbreviated
regex
) is a string that describes a pattern for match-
ing a set of strings. You can match, replace, or split a string by specifying a pattern.
8.
The
Character
class is a wrapper class for a single character. The
Character
class
provides useful static methods to determine whether a character is a letter
(
isLetter(char)
), a digit (
isDigit(char)
), uppercase (
isUpperCase(char)
),
or lowercase (
isLowerCase(char)
).
9.
The
StringBuilder
and
StringBuffer
classes can be used to replace the
String
class. The
String
object is immutable, but you can add, insert, or append
new contents into
StringBuilder
and
StringBuffer
objects. Use
String
if the
string contents do not require any change, and use
StringBuilder
or
StringBuffer
if they might change.
10.
You can pass strings to the
main
method from the command line. Strings passed to
the
main
program are stored in
args
, which is an array of strings. The first string is
represented by
args[0]
, and
args.length
is the number of strings passed.
T
EST
Q
UESTIONS
P
ROGRAMMING
E
XERCISES
Sections 9.2-9.3
*9.1
(
Check SSN
) Write a program that prompts the user to enter a Social Security
number in the format DDD-DD-DDDD, where D is a digit. The program displays
Valid SSN
for a correct Social Security number and
Invalid SSN
otherwise.
**9.2
(
Check substrings
) You can check whether a string is a substring of another string
by using the
indexOf
method in the
String
class. Write your own method for
this function. Write a program that prompts the user to enter two strings, and
checks whether the first string is a substring of the second.
**9.3
(
Check password
) Some websites impose certain rules for passwords. Write a
method that checks whether a string is a valid password. Suppose the password
rules are as follows:
A password must have at least eight characters.
■
A password consists of only letters and digits.
■
A password must contain at least two digits.
Write a program that prompts the user to enter a password and displays
Valid
Password
if the rules are followed or
Invalid Password
otherwise.
■