
Mathematical Functions, Characters, and Strings in Java Programming
Explore mathematical functions, character representation, and string manipulation in Java programming. Learn about using Math class methods, working with characters and strings, and solving problems involving GPS locations. Dive into trigonometric functions and encoding characters with ASCII and Unicode.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Chapter 4 Mathematical Functions, Characters, and Strings Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1
Motivations Suppose you need to estimate the area enclosed by four cities, given the GPS locations (latitude and longitude) of these cities, as shown in the following diagram. How would you write a program to solve this problem? You will be able to write such a program after completing this chapter. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 2
Objectives To solve mathematics problems by using the methods in the Math class ( 4.2). To represent characters using the char type ( 4.3). To encode characters using ASCII and Unicode ( 4.3.1). To represent special characters using the escape sequences ( 4.4.2). To cast a numeric value to a character and cast a character to an integer ( 4.3.3). To compare and test characters using the static methods in the Character class ( 4.3.4). To introduce objects and instance methods ( 4.4). To represent strings using the String objects ( 4.4). To return the string length using the length() method ( 4.4.1). To return a character in the string using the charAt(i) method ( 4.4.2). To use the + operator to concatenate strings ( 4.4.3). To read strings from the console ( 4.4.4). To read a character from the console ( 4.4.5). To compare strings using the equals method and the compareTo methods ( 4.4.6). To obtain substrings ( 4.4.7). To find a character or a substring in a string using the indexOf method ( 4.4.8). To program using characters and strings (GuessBirthday) ( 4.5.1). To convert a hexadecimal character to a decimal value (HexDigit2Dec) ( 4.5.2). To revise the lottery program using strings (LotteryUsingStrings) ( 4.5.3). To format output using the System.out.printf method ( 4.6). Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 3
Mathematical Functions Java provides many useful methods in the Math class for performing common mathematical functions. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 4
The Math Class Class constants: PI E Class methods: Trigonometric Methods Exponent Methods Service Methods: Includes rounding min, max, abs, and random Methods Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 5
Trigonometric Methods Examples Notes: The parameter for sin, cos, and tan is radians. The return value for asin, acos, and atan is a degree in radians in the range between -pi/2 and pi/2. One degree is equal to pi/180 in radians, 90 degrees is equal to pi/2 in radians, and 30 degrees is equal to pi/6 in radians. sin(double a) an angle in cos(double a) tan(double a) acos(double a) asin(double a) atan(double a) toDegree(double a) toRadians(double a) Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 6
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 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 7
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) Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 8
Exponent Methods Examples: Math.exp(1) returns 2.71 Math.log(2.71) 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(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24 exp(double a) Returns e raised to the power of a. log(double a) Returns the natural logarithm of a. log10(double a) Returns the 10-based logarithm of a. pow(double a, double b) Returns a raised to the power of b. sqrt(double a) Returns the square root of a. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 9
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). Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 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 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 11
min, max, and abs max(a, b)and min(a, b) Returns the maximum or minimum of two parameters. Examples: Math.max(2, 3) returns 3 Math.max(2.5, 3) returns 3.0 Math.min(2.5, 3.6) returns 2.5 Math.abs(-2) returns 2 Math.abs(-2.1) returns 2.1 abs(a) Returns the absolute value of the parameter. random() Returns a random double value in the range [0.0, 1.0). Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 12
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: Returns a random integer between 0 and 9. (int)(Math.random() * 10) Returns a random integer between 50 and 99. 50 + (int)(Math.random() * 50) In general, Returns a random number between a and a + b, excluding a + b. a + Math.random() * b Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 13
Case Study: Computing Angles of a Triangle x2, y2 A = acos((a * a - b * b - c * c) / (-2 * b * c)) B = acos((b * b - a * a - c * c) / (-2 * a * c)) C = acos((c * c - b * b - a * a) / (-2 * a * b)) a B c C x3, y3 A b x1, y1 Write a program that prompts the user to enter the x- and y-coordinates of the three corner points in a triangle and then displays the triangle s angles. Note: distance between two points (x1, y1) and (x2, y2) can be computed using the formula ((?2 ?1)2+ (?2 ?1)2) Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 14
1 import java.util.Scanner; 2 public class ComputeAngles { 3 public static void main(String[] args) { 4 Scanner input = new Scanner(System.in); 5 // Prompt the user to enter three points 6 System.out.print("Enter three points: "); 7 double x1 = input.nextDouble(); 8 double y1 = input.nextDouble(); 9 double x2 = input.nextDouble(); 10 double y2 = input.nextDouble(); 11 double x3 = input.nextDouble(); 12 double y3 = input.nextDouble(); 16 // Compute three sides 17 double a = Math.sqrt((x2 - x3) * (x2 - x3) 18 + (y2 - y3) * (y2 - y3)); 19 double b = Math.sqrt((x1 - x3) * (x1 - x3) 20 + (y1 - y3) * (y1 - y3)); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 15
20 double c = Math.sqrt((x1 - x2) * (x1 - x2) 21 + (y1 - y2) * (y1 - y2)); 22 // Compute three angles 23 double A = Math.toDegrees(Math.acos((a * a - b * b - c * c) 24 / (-2 * b * c))); 25 double B = Math.toDegrees(Math.acos((b * b - a * a - c * c) 26 / (-2 * a * c))); 27 double C = Math.toDegrees(Math.acos((c * c - b * b - a * a) 28 / (-2 * a * b))); 29 // Display results 30 System.out.println("The three angles are " + 31 Math.round(A * 100) / 100.0 + " " + 32 Math.round(C * 100) / 100.0); 33 Math.round(B * 100) / 100.0 + " " + 34 } 35 } Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 16
Output Enter three points: 1 1 6.5 1 6.5 2.5 The three angles are 15.26 90.0 74.74 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 17
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: "); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 18
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) char numChar = '4'; (ASCII) Four hexadecimal digits. char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode) Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 19
Character Data Type 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 = 'a'; System.out.println(++ch); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 20
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 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 21
ASCII Code for Commonly Used Characters Characters Code Value in Decimal Unicode Value '0' to '9' 48 to 57 \u0030 to \u0039 'A' to 'Z' 65 to 90 \u0041 to \u005A 'a' to 'z' 97 to 122 \u0061 to \u007A Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 22
Escape Sequences for Special Characters Can You Write the following? System.out.println("He said "Java is fun""); Compilation error Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 23
Escape Sequences for Special Characters Examples : System.out.println("He said \"Java is fun\""); The output is: He said "Java is fun System.out.println("\\ is a backslash character"); The output is: \ is a backslash character Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 24
Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 25
ASCII Character Set, cont. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 26
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; When an integer is cast into a char, only its lower 16 bits of data are used; the other part is ignored char ch = (char)0XAB0041; // The lower 16 bits hex code 0041 is // assigned to ch System.out.println(ch); // ch is character A Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 27
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 When a char is cast into a numeric type, the character s Unicode is cast into the specified numeric type. int i = (int)'A'; // The Unicode of character A is assigned to i System.out.println(i); // i is 65 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 28
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. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 29
Casting between char and Numeric Types Example: 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(j + " is the Unicode for character " + (char)j); // 99 is the Unicode for character c System.out.println("Chapter " + '2'); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 30
Output: i is 101 j is 99 99 is the Unicode for character c Chapter 2 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 31
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"); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 32
Methods in the Character Class Method Description isDigit(ch) Returns true if the specified character is a digit. isLetter(ch) Returns true if the specified character is a letter. isLetterOfDigit(ch) Returns true if the specified character is a letter or digit. isLowerCase(ch) Returns true if the specified character is a lowercase letter. isUpperCase(ch) Returns true if the specified character is an uppercase letter. toLowerCase(ch) Returns the lowercase of the specified character. toUpperCase(ch) Returns the uppercase of the specified character. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 33
Methods in the Character Class Example: 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')); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 34
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 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 35
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 message = "Welcome to Java"; 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. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 36
Simple Methods for String Objects Method Description Returns the number of characters in this string. Returns the character at the specified index from this string. Returns a new string that concatenates this string with string s1. Returns a new string with all letters in uppercase. Returns a new string with all letters in lowercase. Returns a new string with whitespace characters trimmed on both sides. length() charAt(index) concat(s1) toUpperCase() toLowerCase() trim() Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 37
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). Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 38
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 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 39
Getting Characters from a String String message = "Welcome to Java"; System.out.println("The first character in message is " + message.charAt(0)); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 40
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 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 41
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. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 42
String Concatenation String s3 = s1.concat(s2); or String s3 = s1 + s2; // 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 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 43
String Concatenation If i = 1 and j = 2, System.out.println("i + j is " + i + j); The output is "i + j is 12" System.out.println("i + j is " + (i + j)); The output is "i + j is 3" Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 44
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. Scanner input = new Scanner(System.in); System.out.print("Enter three words separated by spaces: "); String s1 = input.next(); 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); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 45
Output Enter three words separated by spaces: Welcome to Java s1 is Welcome s2 is to s3 is Java Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 46
Reading a String from the Console Scanner input = new Scanner(System.in); System.out.println("Enter a line: "); String s = input.nextLine(); System.out.println("The line entered is " + s); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 47
Output Enter a line: Welcome to Java The line entered is Welcome to Java Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 48
Reading a Character from the Console 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); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 49
Output Enter a character: Welcome to Java The character entered is W Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 50