Introduction to Java Programming and Data Structures

Introduction to Java Programming and Data Structures

Chapter 4: Mathematical Functions, Characters, and Strings

  • Copyright © 2024 Pearson Education, Inc. All Rights Reserved

Motivations

  • Problem Statement: Estimating the area enclosed by four cities given their GPS locations (latitude and longitude).

    • Diagram referenced which illustrates the problem.

    • Objective: To enable students to write such a program by the end of this chapter.

Objectives (1 of 2)

4.1 To solve mathematics problems using methods in the Math class (§4.2).
4.2 To represent characters using the char type (§4.3).
4.3 To encode characters using ASCII and Unicode (§4.3.1).
4.4 To represent special characters using escape sequences (§4.4.2).
4.5 To cast a numeric value to a character and a character to an integer (§4.3.3).
4.6 To compare and test characters using static methods in the Character class (§4.3.4).
4.7 To introduce objects and instance methods (§4.4).
4.8 To represent strings using String objects (§4.4).
4.9 To return the string length using the length() method (§4.4.1).
4.10 To return a character in the string using the charAt(i) method (§4.4.2).
4.11 To use the + operator to concatenate strings (§4.4.3).

Objectives (2 of 2)

4.12 To return an uppercase string or a lowercase string and to trim a string (§4.4.4).
4.13 To read strings from the console (§4.4.4).
4.14 To read a character from the console (§4.4.5).
4.15 To compare strings using the equals method and the compareTo methods (§4.4.6).
4.16 To obtain substrings (§4.4.7).
4.17 To find a character or a substring in a string using the indexOf method (§4.4.8).
4.18 To program with characters and strings (GuessBirthday) (§4.5.1).
4.19 To convert a hexadecimal character to a decimal value (HexDigit2Dec) (§4.5.2).
4.20 To revise the lottery program using strings (LotteryUsingStrings) (§4.5.3).
4.21 To format output using the System.out.printf method (§4.6).
4.22 To form multi-line strings using text blocks (§4.7).

Mathematical Functions

  • Overview: Java provides numerous useful methods in the Math class for executing common mathematical functions.

The Math Class

Class Constants

  • PI: Represents the mathematical constant π.

  • E: Represents the base of the natural logarithm e.

Class Methods

  • Trigonometric Methods: Calculates trigonometric values.

  • Exponent Methods: Manipulates exponential functions.

  • Rounding Methods: Rounds numbers in various ways.

  • min, max, abs, and random Methods: Performs basic mathematical operations.

Trigonometric Methods

Functions:

  • sin(double a): Sine of angle a.

  • cos(double a): Cosine of angle a.

  • tan(double a): Tangent of angle a.

  • acos(double a): Arc cosine of a.

  • asin(double a): Arc sine of a.

  • atan(double a): Arc tangent of a.

  • toRadians(double degrees): Converts degrees to radians.

Examples:

  • Math.sin(0) returns 0.0.

  • Math.sin(Math.PI / 6) returns 0.5.

  • Math.sin(Math.PI / 2) returns 1.0.

  • Math.cos(0) returns 1.0.

  • Math.cos(Math.PI / 6) returns 0.866.

  • Math.cos(Math.PI / 2) returns 0.0.

Exponent Methods

Functions:

  • 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 logarithm base 10 of a.

  • pow(double a, double b): Returns a raised to the power of b.

  • sqrt(double a): Returns the square root of a.

Examples:

  • Math.exp(1) returns 2.71.

  • Math.log(2.71) 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.

Rounding Methods

Functions:

  • ceil(double x): Rounds x up to the nearest integer (returns as a double).

  • floor(double x): Rounds x down to the nearest integer (returns as a double).

  • rint(double x): Rounds x to the nearest integer, returning the even integer if x is equally close to two integers.

  • round(float x): Returns int value of x rounded.

  • round(double x): Returns long value of x rounded.

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.round(2.6f) returns 3.

  • Math.round(2.0) returns 2.

  • Math.round(-2.0f) returns -2.

  • Math.round(-2.6) returns -3.

min, max, and abs

Functions:

  • max(a, b): Returns the maximum of two parameters a and b.

  • min(a, b): Returns the minimum of two parameters a and b.

  • abs(a): Returns the absolute value of parameter a.

  • random(): Returns a random double value in the range [0.0, 1.0).

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.

The random Method

  • Generates a random double value

    • Range: $0.0 ext{ to less than } 1.0$

Case Study: Computing Angles of a Triangle

  • Task: Write a program that prompts the user to enter the coordinates of three triangle corners and displays the angles of the triangle.

  • Program Reference: ComputeAngles.

Character Data Type

  • Note: Increment and decrement operators may also be used with char variables to manipulate Unicode characters.

  • Example:

    • char ch = 'a';

    • System.out.println(++ch);

    • This displays character b as a result of incrementing ch.

Unicode Format

  • Java characters utilize Unicode, a 16-bit encoding scheme established to support diverse languages.

  • Representation:

    • Unicode format is preceded by \u, expressed in four hexadecimal digits: \u0000 to \uFFFF.

  • Character Scope: Unicode can represent $65536$ characters.

ASCII Code for Commonly Used Characters

Character Range

Decimal Value

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

Escape Sequences for Special Characters

Escape Sequence

Name

Unicode Code

Decimal Value

\b

Backspace

\u0008

8

\t

Tab

\u0009

9

\n

Linefeed

\u000A

10

\f

Formfeed

\u000C

12

\r

Carriage Return

\u000D

13

\

Backslash

\u005C

92

Appendix B: ASCII Character Set (1 of 2)

ASCII Character Set Definition

  • A subset of Unicode from \u0000 to \u007f.

Decimal Index

Character

Decimal Index

Character

0

nul

68

D

1

soh

69

E

2

stx

70

F

127

del

Appendix B: ASCII Character Set (2 of 2)

Continued Character Set Information

Hexadecimal Index

Character

Hexadecimal Index

Character

00

nul

41

A

01

soh

42

B

02

stx

43

C

7F

del

Casting between char and Numeric Types

  • int i = 'a'; // Equivalent to int i = (int)'a';

  • char c = 97; // Equivalent to char c = (char)97;

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");

Methods in the Character Class

Method

Description

isDigit(ch)

Returns true if the character is a digit.

isLetter(ch)

Returns true if the character is a letter.

isLetterOrDigit(ch)

Returns true if it's a letter or digit.

isLowerCase(ch)

Returns true if the character is lowercase.

isUpperCase(ch)

Returns true if the character is uppercase.

toLowerCase(ch)

Converts character to lowercase.

toUpperCase(ch)

Converts character to uppercase.

The String Type

  • The char type represents a single character, while the String type represents a sequence of characters.

  • String message = "Welcome to Java";

  • The String class is a predefined class in the Java library, unlike primitive types.

  • String is a reference type, allowing it to hold a string object.

Simple Methods for String Objects (1 of 2)

xMethod

Description

length()

Returns the number of characters in the string.

charAt(index)

Returns character at specific index.

concat(s1)

Concatenates string with string s1.

toUpperCase()

Returns a new string with uppercase characters.

toLowerCase()

Returns a new string with lowercase characters.

trim()

Returns a new string without leading or trailing whitespace.

Simple Methods for String Objects (2 of 2)

  • Strings are objects in Java; methods can only be invoked from specific instances of a String.

  • Methods are known as instance methods; whereas methods in the Math class are static methods.

  • Syntax to invoke an instance method:

referenceVariable.methodName(arguments);

Getting String Length

String message = "Welcome to Java";
System.out.println("The length of " + message + " is " + message.length());

Getting Characters from a String

String message = "Welcome to Java";
System.out.println("The first character in message is " + message.charAt(0));

Converting Strings