•Strings
•Strings
String
1
1. Java Class Library
• A class library is a collection of classes that we use when
developing programs
• The Java standard class library is part of any Java development
environment
• The library classes are not part of the Java language per se, but we
rely on them heavily
• Various library classes we've already used in our programs, such as
System, Scanner, and Random
• Other class libraries can be obtained through third party vendors,
or you can create them yourself
• Classes must be imported into the program
2
Packages
• The classes of the Java standard class library are organized into
packages
• Some of the packages in the standard class library are:
Package Purpose
[Link] General support (Character, Math, System, Number, …)
[Link] Utilities (Date, Random, Calendar, …)
[Link] Creating applets for the web
[Link] Graphics and graphical user interfaces
[Link] Additional graphics capabilities
[Link] Network communication
[Link] XML document processing
3
import Declaration
• When you want to use a class from a package, you could use its fully
qualified name
[Link]
• Or you can import the class, and then use just the class name
import [Link];
• To import all classes in a particular package, you can use the *
wildcard character
import [Link].*; // wildcard
4
import Declaration
• All classes of the [Link] package are imported automatically
into all programs
• It's as if all programs contain the following line:
import [Link].*;
• That's why we didn't have to import the System or String classes
explicitly in earlier programs
• The Scanner class, on the other hand, is part of the [Link]
package, and therefore must be imported
5
2. Class Math
• The Math class is part of the [Link] package
• The Math class contains methods (called class methods) that perform
various mathematical functions:
• PI constant
• E (base of natural logarithms) constant
• Trigonometric Methods
• Exponent Methods
• Rounding Methods
• min, max, abs, and random Methods
• Methods in the Math class are called static methods
• Static methods can be invoked through the class name – no object of
the Math class is needed
Double value = [Link](90) + [Link](delta);
6
Example
import [Link];
public class Quadratic
{
public static void main (String[] args)
{
int a, b, c; // ax^2 + bx + c
double discriminant, root1, root2;
Scanner scan = new Scanner ([Link]);
[Link] ("Enter the coefficient of x squared: ");
a = [Link]();
[Link] ("Enter the coefficient of x: ");
b = [Link]();
[Link] ("Enter the constant: ");
c = [Link]();
// Use quadratic formula to compute the roots.
discriminant = [Link](b, 2) - (4 * a * c);
root1 = ((-1 * b) + [Link](discriminant) ) / (2 * a);
root2 = ((-1 * b) - [Link](discriminant) ) / (2 * a);
[Link] ("Root #1: " + root1);
[Link] ("Root #2: " + root2);
}
}
7
Example
Output:
Enter the coefficient of x squared: 3
Enter the coefficient of x: 8
Enter the constant: 4
Root #1: -0.6666666666666666
Root #2: -2.0
Enter the coefficient of x squared: 2
Enter the coefficient of x: 4
Enter the constant: 8
Root #1: NaN
Root #2: NaN
NaN indicates undefined root due to square root of negative
value (sqrt of b^2-4ac)
8
Trigonometric Methods
Examples:
• sin(double a)
• cos(double a)
[Link](0) returns 0.0
[Link]([Link]/6) returns 0.5
• tan(double a)
[Link]([Link]/2) returns 1.0
• acos(double a)
[Link](0) returns 1.0
• asin(double a)
[Link]([Link]/2) returns 0
• atan(double a)
[Link]([Link]/6) returns 0.866
9
Exponent Methods
• exp(double a) Examples:
Returns e raised to the power of a.
• log(double a) [Link](1) returns 2.71
Returns the natural logarithm of a. [Link](2.71) returns 1.0
[Link](2,3) returns 8.0
• log10(double a)
Returns the 10-based logarithm of a. [Link](3,2) returns 9.0
[Link](3.5,2.5) returns
• pow(double a, double b)
22.91765
Returns a raised to the power of b.
[Link](4) returns 2.0
• sqrt(double a) [Link](10.5) returns 3.24
Returns the square root of a.
10
Rounding Methods
• double ceil(double x)
x is rounded up to its nearest integer. This integer is returned as a double
value.
• double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a double
value.
• double rint(double x)
x is rounded to its nearest integer. If x is equally close to two integers, the even
one is returned as a double.
• int round(float x)
returns (int)[Link](x+0.5)
• long round(double x)
returns (long)[Link](x+0.5)
11
Rounding Methods Examples
[Link](2.1) returns 3.0
[Link](2.0) returns 2.0
[Link](-2.0) returns –2.0
[Link](-2.1) returns -2.0
[Link](2.1) returns 2.0
[Link](2.0) returns 2.0
[Link](-2.0) returns –2.0
[Link](-2.1) returns -3.0
[Link](2.1) returns 2.0
[Link](2.0) returns 2.0
[Link](-2.0) returns –2.0
[Link](-2.1) returns -2.0
[Link](2.5) returns 2.0 //returns even value as double
[Link](-2.5) returns -2.0
[Link](2.6f) returns 3 //round returns integers
[Link](2.0) returns 2
[Link](-2.0f) returns -2
[Link](-2.6) returns -3
12
Min(), max(), and abs()
Examples:
• max(a,b)and min(a,b)
Returns the maximum or minimum
of two parameters. [Link](2,3) returns 3
• abs(a) [Link](2.5,3) returns 3.0
Returns the absolute value of the [Link](2.5,3.6) returns 2.5
parameter. [Link](-2) returns 2
[Link](-2.1) returns 2.1
13
Method random()
Generates a random double value greater than or equal to 0.0 and less
than 1.0 (0.0 <= [Link]() < 1.0)
Examples:
In general,
14
Generating Random Characters
Each character has a unique Unicode between 0 and FFFF in hexadecimal
(65535 in decimal).
To generate a random character is to generate a random integer between
0 and 65535 using the following expression:
(int)([Link]() * (65535 + 1))
Note:
Since 0.0 <= [Link]() <1.0, you have to add 1 to 65535
15
Generating Random Characters
Lowercase letter: The Unicode for lowercase letters are consecutive integers starting
from the Unicode for 'a', 'b', 'c', ..., and 'z'.
The Unicode for 'a' is (int)'a'
A random integer between (int)'a' and (int)'z‘ is
(int)((int)'a'+ [Link]()*((int)'z'-(int)'a'+1)
So, a random lowercase letter is:
(char)('a' + [Link]() * ('z' - 'a' + 1))
To generalize, a random character between any two characters ch1 and ch2 with ch1 <
ch2 can be generated as follows:
(char)(ch1 + [Link]() * (ch2 – ch1 + 1))
See Appendix B, page 1266, for character set order.
16
3. Character Data Type
A char variable stores a single character.
Character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' '\n' '\t'
Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';
Note the distinction between a primitive char variable, which holds only one
character, and a String object, which can hold multiple characters.
17
Character Type - Revisited
char letter = 'A'; Four hexadecimal digits.
char numChar = '4';
char letter = '\u0041'; //Unicode for A
char numChar = '\u0034'; //Unicode for character 4
NOTE: The increment and decrement operators can also be used on char
variables to get the next or preceding Unicode character. For example, the
following statements display character b.
char ch = 'c';
ch = ch + 1;
[Link](ch); //prints character d
ch = ch - 2;
[Link](ch); //prints character b
18
ASCII Code in Decimal
19
Casting char Type
int i = 'a'; //Same as int i = (int)'a'; which is 97
char ch = 97; //Same as char ch = (char)97; which is 'a'
20
Comparing char Type
if (ch >= 'A' && ch <= 'Z')
[Link](ch + " is an uppercase letter");
else if (ch >= 'a' && ch <= 'z')
[Link](ch + " is a lowercase letter");
else if (ch >= '0' && ch <= '9')
[Link](ch + " is a numeric character");
21
Class Character Methods
22
Class Character Methods
Character ch1 = new Character('b'); //object NOT char type
Character ch2 = new Character(‘9'); //object NOT char type
[Link](ch1) returns true
[Link](ch1) returns true
[Link](ch1) returns false
[Link](ch2) returns true
[Link](ch1) returns B
23
Class Character Test
// Class Character Test
import [Link];
public class CharacterTest
{
public static void main (String[] args)
{
Character ch1 = new Character('b'); //object NOT char type
Character ch2 = new Character('9'); //object NOT char type
[Link]([Link](ch1)); //returns true
[Link]([Link](ch1)); //returns true
[Link]([Link](ch1)); //returns false
[Link]([Link](ch2)); //returns true
[Link]([Link](ch1)); //returns B
char ch3 = 'R'; // char type variable
char ch4 = '7'; // char type variable
char ch5 = '*'; // char type variable
[Link]([Link](ch3)); //returns false
[Link]([Link](ch5)); //returns false
[Link]([Link](ch4)); //returns true
[Link]([Link](ch5)); //returns false
[Link]([Link](ch3)); //returns r
}
}
24
Escape Sequences
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000A
Carriage return \r \u000D
------------------------------------------------------------------------
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022
25
4. Class String
• To create a String object, we need to declare a variables of type String:
String title = "Java Software Solutions";
• Each string literal (enclosed in double quotes) represents a String
object
• Once a String object has been created, neither its value nor its length
can be changed. Thus, String objects are immutable
• The String type is not a primitive type. It is a class type and known as a
object or reference type.
26
String Methods
• However, several methods of the String class return new String
objects that are modified versions of the original string
• A String object is a sequence of characters (known as Single-Dimensional
Array).
String courseName = "CS 2301";
0 1 2 3 4 5 6
C S 2 3 0 1
27
String Index Values
• It is occasionally helpful to refer to a particular character within a string
• This can be done by specifying the character's numeric index (position)
• The indexes begin at zero in each string
• In the string "Hello", the character 'H' is at index 0 and the 'o' is at
index 4
28
Getting Characters from a String
String message = "Welcome to Java";
char ch = [Link](0);
[Link]("The first character in message is “ + ch);
String message = "Welcome to Java";
int messageLength = [Link]();
[Link]("The length of message is " + messageLength);
29
String Concatenation
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
30
Example
public class StringMutation
{
// Prints a string and various mutations of it.
public static void main (String[] args)
{
String phrase = "Change is inevitable";
String mutation1, mutation2, mutation3, mutation4;
[Link] ("Original string: \"" + phrase + "\"");
[Link] ("Length of string: " + [Link]());
mutation1 = [Link](", except from vending machines.");
mutation2 = [Link]();
mutation3 = [Link] ('E', 'X');
mutation4 = [Link] (3, 30); //excluding position 30
[Link] ("Mutation #1: " + mutation1);
[Link] ("Mutation #2: " + mutation2);
[Link] ("Mutation #3: " + mutation3);
[Link] ("Mutation #4: " + mutation4);
[Link] ("Mutated length: " + [Link]());
}
}
31
Example
Output:
Original string: "Change is inevitable"
Length of string: 20
Mutation #1: Change is inevitable, except from vending machines.
Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES.
Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS.
Mutation #4: NGX IS INXVITABLX, XXCXPT F
Mutated length: 27
32
Other String Methods
String S1 = "Welcome";
String S2 = new String(char[]);
S2 = " Hello! ";
char ch = [Link](index);
int length = [Link]();
int index = [Link](ch);
int index = [Link](ch);
boolean b = [Link](S2);
boolean b = [Link](S2);
boolean b = [Link](S2);
Boolean b = [Link](S2);
String S = [Link]();
String S = [Link]();
String S = [Link](i); //from position i to last position
String S = [Link](i,j); //excluding j position
String S = [Link](ch1,ch2);
String S = [Link](); //returns "Hello!", no spaces
33
Reading Strings
Scanner input = new Scanner([Link]);
[Link]("Enter three words separated by spaces: ");
String s1 = [Link]();
String s2 = [Link]();
String s3 = [Link]();
[Link](“First word is " + s1);
[Link](“Second word is " + s2);
[Link](“Third word is " + s3);
Note: If we use
String s1 = [Link]();
s1 contains all typed characters until we press the "Enter" key.
34
Reading Characters
//Characters are read as strings
Scanner input = new Scanner([Link]);
[Link]("Enter a character: ");
String s = [Link](); //must press the Enter key
char ch = [Link](0);
[Link]("The entered character is " + ch);
35
Comparing Strings
36
Obtaining Substrings
37
indexOf() method
38
Conversion of Strings/Numbers
You can convert strings of digits to numbers:
String intString = “123”;
int intValue = [Link](intString);
String doubleString = “123.456”;
double doubleValue = [Link](doubleString);
You can convert numbers to strings:
int number = 123456;
String s = "" + number; //gives "123456"
39
5. printf() Statement
Use the printf statement.
[Link](format, items);
Where format is a string that may consist of substrings and
format specifiers.
A format specifier specifies how an item should be displayed.
An item may be a numeric value, character, boolean value, or a
string.
Each specifier begins with a percent (%) sign.
40
Frequently-Used Specifiers
Specifier Output Example .
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.4600000
%e a standard scientific notation 4.556000e+01
%s a string "Java is cool"
Homework: Type and run program FormatDemo, listing 4.6, page 148. It shows
how to display tabulated outputs using printf() statement.
41