t04 Programming Principle
t04 Programming Principle
Mathematical Functions,
Characters, and Strings
CS402 Programming Principles
1
CS402 Programming Principles
Character Data Type
A character data type represents a single character
A string literal must be enclosed in quotation marks (" ").
A character literal is a single character enclosed in single
quotation marks (' '). Therefore, "A" is a string, but 'A' is a
character.
char letter = 'A'; (ASCII)
Four hexadecimal digits.
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
2
CS402 Programming Principles
Character Data Type
3
CS402 Programming Principles
Unicode Format
Java characters use Unicode, a 16-bit encoding scheme
established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes,
preceded by \u, expressed in four hexadecimal numbers
that run from '\u0000' to '\uFFFF'. So, Unicode can
represent 65535 + 1 characters.
Unicode \u03b1 \u03b2 \u03b3 for three Greek
letters
4
CS402 Programming Principles
ASCII Code for Commonly Used
Characters
Characters Code Value in Decimal Unicode Value
5
CS402 Programming Principles
Escape Sequences for Special Characters
Can You Write the following?
System.out.println("He said "Java is fun"");
Compilation error
6
CS402 Programming Principles
Escape Sequences for Special Characters
Examples :
System.out.println("He said \"Java is fun\"");
7
CS402 Programming Principles
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
8
CS402 Programming Principles
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
9
CS402 Programming Principles
Casting between char and
Numeric Types
A char can be cast into any numeric type, and vice
versa.
int i = 'a'; // Same as int i = (int)'a';
char c = 97; // Same as char c = (char)97;
10
CS402 Programming Principles
Casting between char and
Numeric Types
When a floating-point value is cast into a char, the
floating-point value is first cast into an int, which is then
cast into a char.
char ch = (char)65.25; // Decimal 65 is assigned to ch
System.out.println(ch); // ch is character A
11
CS402 Programming Principles
Casting between char and
Numeric Types
All numeric operators can be applied to char operands.
A char operand is automatically cast into a number if
the other operand is a number or a character.
If the other operand is a string, the character is
concatenated with the string.
12
CS402 Programming Principles
Casting between char and
Example:
Numeric Types
Output:
13
CS402 Programming Principles
Comparing and Testing
Characters
if (ch >= 'A' && ch <= 'Z')
System.out.println(ch + " is an uppercase letter");
else if (ch >= 'a' && ch <= 'z')
System.out.println(ch + " is a lowercase letter");
else if (ch >= '0' && ch <= '9')
System.out.println(ch + " is a numeric character");
14
CS402 Programming Principles
Methods in the Character Class
Method Description
15
CS402 Programming Principles
Methods in the Character Class
Example:
Output:
16
CS402 Programming Principles
The String Type
The char type only represents one character. To represent a string
of characters, use the data type called String. For example,
String is actually a predefined class in the Java library just like the
System class and Scanner class. The String type is not a primitive
type. It is known as a reference type. Any Java class can be used
as a reference type for a variable.
17
CS402 Programming Principles
Simple Methods for String Objects
Method Description
18
CS402 Programming Principles
Simple Methods for String Objects
Strings are objects in Java. The methods in the preceding
table can only be invoked from a specific string instance.
For this reason, these methods are called instance methods.
A non-instance method is called a static method. A static
method can be invoked without using an object. All the
methods defined in the Math class are static methods. They
are not tied to a specific object instance. The syntax to
invoke an instance method is
referenceVariable.methodName(arguments).
19
CS402 Programming Principles
Getting String Length
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "
+ message.length());
Output :
The length of Welcome to Java is 15
20
CS402 Programming Principles
Getting Characters from a String
21
CS402 Programming Principles
Caution
The s.charAt(index) method can be used to retrieve a specific
character in a string s,where the index is between 0 and s.length()–
1.
Attempting to access characters in a string s out of bounds is a
common programming error. To avoid it, make sure that you do not
use an index beyond s.length() – 1.
For example, s.charAt(s.length()) would cause a
StringIndexOutOfBoundsException compilation error
22
CS402 Programming Principles
Converting Strings
"Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string, WELCOME.
▪ The trim() method returns a new string by eliminating
whitespace characters from both ends of the string.
▪ The characters ' ',\t,\f,\r, or \n are known as whitespace
characters.
For example,
"\t Good Night \n".trim() returns a new string Good Night
" Welcome ".trim() returns a new string, Welcome.
23
CS402 Programming Principles
String Concatenation
String s3 = s1.concat(s2); or String s3 = s1 + s2;
24
CS402 Programming Principles
String Concatenation
If i = 1 and j = 2,
25
CS402 Programming Principles
Reading a String from the Console
The next() method reads a string that ends with a whitespace
character.
The nextLine() method reads an entire line of text. The
nextLine() method reads a string that ends with the Enter key
pressed.
Example:
26
CS402 Programming Principles
Output:
27
CS402 Programming Principles
Reading a String from the Console
Example:
Output:
28
CS402 Programming Principles
Reading a Character from the
Example:
Console
Output:
29
CS402 Programming Principles
Comparing Strings
Method Description
30
CS402 Programming Principles
Exercise – String Sorting
Write a program that prompts the user to enter two cities and
displays them in alphabetical order.
31
CS402 Programming Principles
Exercise – String Sorting
OrderTwoCities.java
32
CS402 Programming Principles
Obtaining Substrings
Method Description
substring(beginIndex) Returns this string’s substring that begins with the character at the specified
beginIndex and extends to the end of the string, as shown in Figure 4.2.
substring(beginIndex, Returns this string’s substring that begins at the specified beginIndex and
endIndex) extends to the character at index endIndex – 1, as shown in Figure 9.6.
Note that the character at endIndex is not part of the substring.
34
CS402 Programming Principles
Finding a Character or a Substring
in a String
Method Description
indexOf(ch) Returns the index of the first occurrence of ch in the string. Returns -1 if not
matched.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string.
Returns -1 if not matched.
indexOf(s) Returns the index of the first occurrence of string s in this string. Returns -1 if
not matched.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string after
fromIndex. Returns -1 if not matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns -1 if not
matched.
lastIndexOf(ch, Returns the index of the last occurrence of ch before fromIndex in this
fromIndex) string. Returns -1 if not matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1 if not matched.
lastIndexOf(s, Returns the index of the last occurrence of string s before fromIndex.
fromIndex) Returns -1 if not matched.
35
CS402 Programming Principles
Finding a Character or a Substring
in a String
int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
36
CS402 Programming Principles
Conversion between Strings and
Numbers
int intValue = Integer.parseInt(intString);
double doubleValue = Double.parseDouble(doubleString);
37
CS402 Programming Principles
Problem: Lottery Program Using Strings
Rewrites the lottery program in Topic 3 using strings. Using strings simplifies this
program.
Write a program that randomly generates a lottery of a two-digit number, prompts
the user to enter a two-digit number, and determines whether the user wins
according to the following rule:
• If the user input matches the lottery in exact order, the award is $10,000.
• If the user input matches the lottery, the award is $3,000.
• If one digit in the user input matches a digit in the lottery, the award is $1,000.
38
CS402 Programming Principles
Problem: Lottery Program Using Strings
LotteryUsingStrings .java
39
CS402 Programming Principles
Problem: Lottery Program Using Strings
LotteryUsingStrings .java
41
CS402 Programming Principles
Formatting Output
Use the printf statement.
System.out.printf(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.
42
CS402 Programming Principles
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.460000
%e a number in standard scientific notation 4.556000e+01
%s a string "Java is cool"
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
43
CS402 Programming Principles
Formatting Example #1
Example:
Output:
44
CS402 Programming Principles
Formatting Example #2
Output:
45
CS402 Programming Principles
Formatting Example #2
FormatDemo .java
46
CS402 Programming Principles
Mathematical Functions
48
CS402 Programming Principles
The Math Class
Class constants:
– PI
–E
Class methods:
– Trigonometric Methods
– Exponent Methods
– Service Methods:
Includes rounding min, max, abs, and random
Methods
49
CS402 Programming Principles
Trigonometric Methods Examples
Notes:
sin(double a) The parameter for sin, cos,
and tan is an angle in
cos(double a)
radians.
tan(double a) The return value for asin,
acos, and atan is a degree in
acos(double a) radians in the range between
-pi/2 and pi/2.
asin(double a) One degree is equal to pi/180
in radians, 90 degrees is
atan(double a) equal to pi/2 in radians, and
30 degrees is equal to pi/6
toDegree(double a) in radians.
toRadians(double a)
50
CS402 Programming Principles
Trigonometric Methods Examples
Examples:
Math.toDegrees(Math.PI / 2)
returns 90.0
Math.toRadians(30)
returns 0.5236 (same as π/6)
Math.sin(0)
returns 0.0
Math.sin(Math.toRadians(270))
returns -1.0
Math.sin(Math.PI / 6)
returns 0.5
Math.sin(Math.PI / 2)
returns 1.0
51
CS402 Programming Principles
Trigonometric Methods
Examples:
Math.asin(0.5)
returns 0.523598333 (same as π/6)
Math.acos(0.5)
returns 1.0472 (same as π/3)
Math.atan(1.0)
returns 0.785398 (same as π/4)
52
CS402 Programming Principles
Exponent Methods
exp(double a) Examples:
Returns e raised to the power of a. Math.exp(1) returns 2.71
Math.log(2.71) returns 1.0
log(double a) Math.log10(10) returns 1.0
Returns the natural logarithm of a. Math.pow(2, 3) returns 8.0
log10(double a) Math.pow(3, 2) returns 9.0
Returns the 10-based logarithm of Math.pow(3.5, 2.5) returns
a. 22.91765
Math.sqrt(4) returns 2.0
pow(double a, double b) Math.sqrt(10.5) returns 3.24
Returns a raised to the power of b.
sqrt(double a)
Returns the square root of a.
53
CS402 Programming Principles
Rounding Methods
double ceil(double x)
x 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)
Return (int)Math.floor(x+0.5).
long round(double x)
Return (long)Math.floor(x+0.5).
54
CS402 Programming Principles
Rounding Methods Examples
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3
55
CS402 Programming Principles
min, max, and abs
max(a, b)and min(a, b) Examples:
Returns the maximum or Math.max(2, 3) returns 3
minimum of two parameters. Math.max(2.5, 3) returns
abs(a) 3.0
Returns the absolute value of the Math.min(2.5, 3.6) returns
parameter. 2.5
random() Math.abs(-2) returns 2
Returns a random double value Math.abs(-2.1) returns 2.1
in the range [0.0, 1.0).
56
CS402 Programming Principles
The random Method
Generates a random double value greater than or equal to 0.0 and less
than 1.0 (0 <= Math.random() < 1.0).
Examples:
In general,
57
CS402 Programming Principles
Problem: Computing Angles of a Triangle
x2, y2
A = acos((a * a - b * b - c * c) / (-2 * b * c))
a B = acos((b * b - a * a - c * c) / (-2 * a * c))
B
c C = acos((c * c - b * b - a * a) / (-2 * a * b))
C
A x3, y3
b
x1, y1
58
59
CS402 Programming Principles
Problem: Computing Angles of a Triangle
ComputeAngles.java
61
CS402 Programming Principles
Caution
The Math class is used in the program, but not imported,
because it is in the java. lang package. All the classes in
the java.lang package are implicitly imported in a Java
program.
The program prompts the user to enter three points (line
6). This prompting message is not clear. You should give
the user explicit instructions on how to enter these
points as follows:
System.out.print("Enter the coordinates of three points separated "
+ "by spaces like x1 y1 x2 y2 x3 y3: ");
62
CS402 Programming Principles