Professional Documents
Culture Documents
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 2
Motivations
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 3
Common Mathematical Functions
Mathematical Functions
– Java provides many useful methods in the Math class for
performing common mathematical functions.
What is Java Math Method:
– A group of statements that performs a specific task
– Such as:
pow(a, b): to compute ab
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 4
The Math Class
Class constants:
– PI You can use these constants as Math.PI
–E and Math.E in any program.
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 5
Trigonometric Methods
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 8
Exponent Methods
Examples:
Math.exp(1); // returns 2.71828
Math.log(Math.E); // returns 1.0
Math.log10(10); // returns 1.0
Math.pow(2, 3); // returns 8.0
Math.pow(3, 2); // returns 9.0
Math.pow(4.5, 2.5); // returns 22.91765
Math.sqrt(4); // returns 2.0
Math.sqrt(10.5); // returns 4.24
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 9
Rounding Methods
Math class contains five 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).
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 10
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
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 11
min, max, and abs
min and max methods
– min(a, b): returns minimum of a and b
– max(a, b): returns the maximum of a and b
abs method:
– abs(a): returns the absolute value of a
Examples:
Math.max(2, 3); //returns 3
Math.max(2.5, 3); //returns 3
Math.min(2.5, 4.6); //returns 2.5
Math.abs(-2); //returns 2
Math.abs(-2.1); //returns 2.1
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 12
The random Method
Generates a random double value
– This value is greater than or equal to 0.0 and less
than 1.0
0 <= Math.random() < 1.0
– Examples:
(int)(Math.random() * 10);
– returns a random integer between 0 and 9
50 + (int)(Math.random() * 50);
– returns a random integer between 50 and 99
a + Math.random() * b;
– returns a random number between a and a+b, excluding a+b
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 13
Evaluate the following method calls:
a. Math.sqrt(4) 2
b. Math.pow(2,3) 8
c. Math.rint(-2.5) -2.0
d. Math.ceil(7.1) 8
e. Math.ceil(-2.8) -2.0
f. Math.floor(-2.2) -3.0
g. Math.floor(9.9) 9.0
h. Math.round(2.5) 3
i. Math.round(Math.abs(-3.5)) 4
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 14
Character Data Type
Java allows you to process characters using the
character data type, char
– char represents a single character
– a character literal is enclosed in single quotation marks
Examples:
– char letter = ‘A’;
Assigns the character A to the char variable letter
– char numChar = ‘4’;
Assigns the digit character 4 to the char variable numChar
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 15
Unicode and ASCII code
Computers use binary numbers internally
– a character is stored in a computer as a sequence of 0s
and 1s
– Mapping a character to its binary representation is
called encoding
– There are different ways to encode a character
– Java uses Unicode
Unicode is an encoding scheme
Originally designed for 16-bit character encoding
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 16
Unicode and ASCII code
Unicode is usually expressed in Hexadecimal
– Hexadecimal number system: 16 digits from 0 to F
• 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
– We need 4 bits to represent a Hex digit
• Example: 15 in decimal is 1111 in binary and F in
Hex
– 16 bits in Unicode
– Each hexadecimal requires 4 bits
– So that means each Unicode is expressed in 4 Hex
digits!
– From \u0000 to \uFFFF
Example:
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 17
Unicode and ASCII code
ASCII
– Most computers use ASCII
American Standard Code for International Exchange
– 8-bit encoding scheme
Used to represent all uppercase and lowercase letters, all
digits, all punctuation marks, and control characters
128 characters total
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 18
Unicode and ASCII code
ASCII
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 20
Casting between char and
Numeric Types
Explicit casting:
– The following would be incorrect:
byte b = '\uFFF4';
Why?
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 22
Casting between char and
Numeric Types
Numeric operators
– Examples:
int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51
System.out.println("i is " + i); // i is 101
int j = 2 + 'a'; // (int)'a' is 97
System.out.println("j is " + j); // j is 99
System.out.println("Chapter " + '2');
System.out.println(j + " is the Unicode for character " + (char)j);
Output:
i is 101
j is 99
Chapter 2
99 is the Unicode for character c
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 23
Comparing and Testing Characters
Two characters can be compared using relational
operators
– just like comparing two numbers
Thisis done by comparing the Unicode values
Examples:
'a' < 'b' is true because the Unicode for 'a' (97) is less than the Unicode for 'b' (98).
'a' < 'A' is false because the Unicode for 'a' (97) is greater than the Unicode for 'A' (65).
'1' < '8' is true because the Unicode for '1' (49) is less than the Unicode for '8' (56).
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 24
Comparing and Testing Characters
Often you must test whether a character is a
number, a letter, or even if it is uppercase or
lowercase.
– The following code tests whether a character ch is an
uppercase letter, a lowercase letter, or a digit:
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");
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 25
Methods in the Character Class
Testing characters is common
– Therefore, Java gives the following methods inside the
Character class
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 26
Methods in the Character Class
Using the Character class:
– Examples:
System.out.println("isDigit('a') is " + Character.isDigit('a'));
System.out.println("isLetter('a') is " + Character.isLetter('a'));
System.out.println("isLowerCase('a') is " + Character.isLowerCase('a'));
System.out.println("isUpperCase('a') is " + Character.isUpperCase('a'));
System.out.println("toLowerCase('T') is " + Character.toLowerCase('T'));
System.out.println("toUpperCase('q') is " + Character.toUpperCase('q'));
Output:
isDigit('a') is false
isLetter('a') is true
isLowerCase('a') is true
isUpperCase('a') is false
toLowerCase('T') is t
toUpperCase('q') is Q
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 27
Evaluate the following :
System.out.println('a' < 'b'); true
System.out.println('a' <= 'A'); false
System.out.println('a' > 'b'); false
System.out.println('a' >= 'A'); true
System.out.println('a' == 'a'); true
System.out.println('a' != 'b'); true
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 28
What is the output of the following program:
public class Test {
public static void main(String[] args) {
char x = 'a';
char y = 'c';
System.out.println(++x);
System.out.println(y++);
System.out.println(x - y);
}
}
Output:
b
c
-2
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 29
Write code that generates a random lowercase
letter.
– Remember: lowercase letters are 97 to 122 in decimal
So 26 possible values (letters)
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 30
The String Type
A char represents one character
So how do we represent a sequence (a string) of
characters?
Use the data type called String
Example:
– The following code declares variable message to be
a string with the value "Welcome to Java"
String message = "Welcome to Java";
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 31
The String Type
String details:
– String is a predefined class in the Java library
Just like the classes System and Scanner
– The String type is not a primitive type
– It is known as a reference type
– And the variable declared by a reference type is
known as a reference variable that references an object
String message = "Welcome to Java";
Here, message is a reference variable that references a
string object with the contents "Welcome to Java"
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 32
The String Type
String details:
– Declaring a String variable:
String firstName;
– Assign a value to the String variable:
firstName = "Muhammad Alzahrani";
– Most important:
How to use the methods in the String class
The following page shows some of the common methods
that can be used to operate on Strings
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 33
Simple Methods for String Objects
String details:
– Strings are objects in Java
For this reason, these methods are called "instance methods"
– A non-instance method is called a static method
All methods in the Math class are static methods
– They are not tied to a specific object instance
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 34
Simple Methods for String Objects
String details:
– Again, string methods are instance methods
This means that they are tied to a specific object/string
– Therefore, you must invoke them from a specific
object/string
– Syntax: referenceVariable.methodName(arguments)
Recall: syntax to invoke a static method:
– ClassName.methodName(arguments)
– Example: Math.pow(2, 3); // result is 8
Soinstead of mentioning the Class of the method
We mention the specific variable
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 35
Simple Methods for String Objects
Getting String Length
– Use the length() method to return the number of
characters in a string
– Example:
String message = "Welcome to Java";
System.out.println("The length of " +
message + " is " + message.length());
Output:
The length of Welcome to Java is 15
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 36
Simple Methods for String Objects
Getting Characters from a String
– The s.charAt(index) method can be used to retrieve
a specific character in a string s
Theindex is between 0 and s.length()-1
Example:
message.charAt(0); // Returns the character W
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 37
Simple Methods for String Objects
Concatenating Strings
– You can use the concat method to concatenate two
strings
– Example:
Strings s3 = s1.concat(s2);
concatenates s1 and s2 into s3
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 39
Simple Methods for String Objects
Concatenating Strings
– The augmented += operator can also be used for
concatenation with strings
– Example:
String message = "Welcome to Java";
message += ", and Java is fun.";
System.out.println(message);
Output:
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 40
Simple Methods for String Objects
Concatenating Strings
– Final example:
i=1 and j=2, what is the output of the following:
If
Output:
"i + j is 12"
Why?
– In Java, we read from left to right
– So we have the String "i + j is " concatenated with the int i
– The result: a new String ("i + j is 1")
– This new String is the concatenated with the int j
– You can force addition by enclosing the i + j in parentheses
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 41
Simple Methods for String Objects
Converting Strings
– Methods:
toLowerCase() method returns a new string with all
lowercase letters
toUpperCase() method returns a new string with all
uppercase letters
trim() method returns a new string after removing all
whitespace characters from both ends of the string
– Final example:
"Welcome".toLowerCase(); // returns a new string welcome
"Welcome".toUpperCase(); // returns a new string WELCOME
"\t a b c ".trim(); // returns a new string a b c
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 42
Reading a String from the Console
How to read a string from the console
– Use the next() method on a Scanner object
System.out.print("Enter three words separated by spaces: ");
String s1 = input.next(); // assume we made Scanner object
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 43
Reading a String from the Console
How to read a complete line from the console
– Use the nextLine() method on a Scanner object
Scanner input = new Scanner(System.in);
System.out.println("Enter a line: ");
String s = input.nextLine();
System.out.println("The line entered is " + s);
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 44
Reading a Character from the Console
How to read a single character from the console
– Use the nextLine() method to read a string and then
invoke the charAt(0) method on the string
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0);
System.out.println("The character entered is " + ch);
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 45
Comparing Strings
The String class has many methods you can use
to compare two strings.
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 46
Comparing Strings
String equality
– How can you check if two strings are equal?
– Note: you cannot use the == operator
– Example:
if (s1 == s2)
System.out.println("s1 and s2 are the same object");
else
System.out.println("s1 and s2 are different object");
This will only tell us if two string reference variables point
to (refer to) the same object
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 47
Comparing Strings
String equality
– So how can you check if two strings are equal?
– Meaning, how to check if they have same contents?
– Use the equals() method
– Example:
if (s1.equals(s2))
System.out.println("s1 and s2 have same contents");
else
System.out.println("s1 and s2 are not equal");
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 48
Comparing Strings
String equality
– Example:
String s1 = "Welcome to Java";
String s2 = "Welcome to Java";
String s3 = "Welcome to C++";
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 49
Comparing Strings
compareTo() method
– We can use the compareTo() method to compare two
strings
This allows us to alphabetically order the strings
– Syntax:
s1.compareTo(s2);
Returns the value 0 if s1 is equal to s2
– Example:
"abc".compareTo("abg"); // returns -4
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 50
Program 1: OrderTwoCities
Write a program that prompts the user to enter
two cities and then displays them in alphabetical
order.
Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 51
Program 1: OrderTwoCities
Step 1: Problem-solving Phase
– Algorithm:
1. Prompt the user to enter an two Strings
2. Compare the two strings using compareTo() method
3. Print the cities in correct alphabetical order
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 52
Program 1: OrderTwoCities
Step 2: Implementation
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 53
Program 1: OrderTwoCities
Run the Program:
– Note:
Some city names have multiple words
– Such as New York
Therefore, we used nextLine() to scan the city name
– Instead of next()
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 55
Obtaining Substrings
Java gives you two substring methods:
– substring(beginIndex)
Returns this string's substring that begins with the character
at the specified beginIndex and extends to the end of the
string
– substring(beginIndex, endIndex)
Returns this string's substring that begins with the character
at the specified beginIndex and extends to the character at
index endIndex–1
– NOTE: the character at endIndex is NOT part of the substring
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 56
Finding a Character or a Substring
in a String
The String class provides several versions of
indexOf and lastIndexOf methods to find a
character or a substring in a string
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 57
Finding a Character or a Substring
in a String
The String class provides several versions of
indexOf and lastIndexOf methods to find a
character or a substring in a string
– Examples:
"Welcome to Java".indexOf('W') returns 0.
"Welcome to Java".indexOf('o') returns 4.
"Welcome to Java".indexOf('o', 5) returns 9.
"Welcome to Java".indexOf("come") returns 3.
"Welcome to Java".indexOf("Java", 5) returns 11.
"Welcome to Java".indexOf("java", 5) returns -1.
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 58
Finding a Character or a Substring
in a String
The String class provides several versions of
indexOf and lastIndexOf methods to find a
character or a substring in a string
– Examples:
"Welcome to Java".lastIndexOf('W') returns 0.
"Welcome to Java".lastIndexOf('o') returns 9.
"Welcome to Java".lastIndexOf('o', 5) returns 4.
"Welcome to Java".lastIndexOf("come") returns 3.
"Welcome to Java".lastIndexOf("Java", 5) returns -1.
"Welcome to Java".lastIndexOf("Java") returns 11.
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 59
Finding a Character or a Substring
in a String
Practical Example
– Suppose a string s contains the first name and last
name of a student, separated by a space
– How can you extract the first name and last name?
– Can we use a method to find the space?
YES!
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 60
Finding a Character or a Substring
in a String
Practical Example
– Solution:
String s = "Kim Jones";
int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 61
Conversion between Strings and
Numbers
Youcan convert a numeric string into an int
How?
– Use the Integer.parseInt() method
– Example:
int value = Integer.parseInt("152");
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 62
Conversion between Strings and
Numbers
Can you convert a number to a String?
– Yes.
– You can do it a complicated way
We won't bother showing you!
– OR, you do it the EASY way:
int number = 7;
String s = number + "";
kinda like a "hack"
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 66
Program 2: HexDigit2Dec
Write a program that prompts the user to enter
one hex digit and then displays this as a decimal
value.
Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 67
Program 2: HexDigit2Dec
Step 1: Problem-solving Phase
– Algorithm:
1. Prompt the user to enter a hex digit
2. Check to see if the input is exactly one digit
3. If so, confirm the input is between 0-9 or A-F
– Then print the decimal equivalent
4. Otherwise, print invalid input
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 68
Program 2: HexDigit2Dec
Step 2: Implementation
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 69
Program 2: HexDigit2Dec
Step 2: Implementation
is A-F?
is 0-9?
© Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 70
Program 2: HexDigit2Dec
Run the Program: