Mathematical Functions, Characters, and Strings in Java
Introduction to Java Programming and Data Structures
Chapter 4: Mathematical Functions, Characters, and Strings
Mathematical Functions
Java provides many useful methods in the Math class for performing common mathematical functions.
Definition: A method is a group of statements that performs a specific task.
The Math Class
Class Constants:
PI
E
Class Methods:
Exponent Methods: These methods deal with exponential and logarithmic calculations.
Rounding Methods: These methods are used for rounding numbers.
min, max, abs, and random Methods: These methods return minimum or maximum of values, absolute values, and random values, respectively.
Exponent Methods
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 of
a
with base 10.pow(double a, double b): Returns
a
raised to the power ofb
.sqrt(double a): Returns the square root of
a
.
Examples of Exponent Methods
Math.exp(1)
returns approximately 2.71Math.log(2.71)
returns 1.0Math.pow(2, 3)
returns 8.0Math.pow(3, 2)
returns 9.0Math.pow(3.5, 2.5)
returns approximately 22.91765Math.sqrt(4)
returns 2.0Math.sqrt(10.5)
returns approximately 3.24
Rounding Methods
double ceil(double x): Rounds
x
up to its nearest integer and returns it as a double value.double floor(double x): Rounds
x
down to its nearest integer and returns it as a double value.double rint(double x): Rounds
x
to its nearest integer; ifx
is equally close to two integers, the even one is returned as double.int round(float x): Returns
(int)Math.floor(x + 0.5)
.long round(double x): Returns
(long)Math.floor(x + 0.5)
.
Examples of Rounding Methods
Math.ceil(2.1)
returns 3.0Math.ceil(2.0)
returns 2.0Math.ceil(-2.0)
returns -2.0Math.ceil(-2.1)
returns -2.0Math.floor(2.1)
returns 2.0Math.floor(2.0)
returns 2.0Math.floor(-2.0)
returns -2.0Math.floor(-2.1)
returns -3.0Math.rint(2.1)
returns 2.0Math.rint(2.5)
returns 2.0Math.round(2.6f)
returns 3
min, max, and abs
max(a, b): Returns the maximum of two parameters.
min(a, b): Returns the minimum of two parameters.
abs(a): Returns the absolute value of the parameter.
random(): Returns a random double value in the range [0.0, 1.0).
Examples of min, max, and abs
Math.max(2, 3)
returns 3Math.max(2.5, 3)
returns 3.0Math.min(2.5, 3.6)
returns 2.5Math.abs(-2)
returns 2Math.abs(-2.1)
returns 2.1
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).Example:
a + Math.random() * b
returns a random number betweena
anda + b
, excludinga + b
.a + (int) (Math.random() * b)
returns a random integer betweena
anda + b
, excludinga + b
.
Examples of Random Method:
(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.
Characters
Character Data Type: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character.
Example:
char ch = 'a';
System.out.println(++ch);
// displays character 'b'.
ASCII Code for Commonly Used Characters
Decimal values and their corresponding Unicode values for characters:
'0' to '9': Decimal 48 to 57, Unicode 0 to 9
'A' to 'Z': Decimal 65 to 90, Unicode 1 to A
'a' to 'z': Decimal 97 to 122, Unicode 1 to A
Special Characters
Special Character Display:
"
: Double quotation mark\
: Backslash: Tab
or : Carriage return
Casting between char and Numeric Types
Example:
int i = 'a';
// This is equivalent toint i = (int)'a';
char c = 97;
// This is equivalent tochar c = (char)97;
Comparing and Testing Characters
Example:
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
Methods and Descriptions:
isDigit(ch)
: Returns true if the specified character is a digit.isLetter(ch)
: Returns true if the specified character is a letter.isLetterOrDigit(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.
Strings
The String Type: The
char
type only represents one character. To represent a string of characters, use the data type calledString
.Example:
String message = "Welcome to Java";
A String is a predefined class in Java’s library just like the System class and Scanner class.
The String type is not a primitive type; it is known as a reference type.
Reference data types will be thoroughly discussed in Chapter 9, “Objects and Classes”.
Key Points to Know:
How to declare a String variable.
How to assign a string to the variable.
How to concatenate strings.
To perform simple operations for strings.
Simple Methods for String Objects (1 of 2)
Method Descriptions:
length(): Returns the number of characters in this string.
charAt(index): Returns the character at the specified index from this string.
concat(s1): Returns a new string that concatenates this string with string
s1
.toUpperCase(): Returns a new string with all letters in uppercase.
toLowerCase(): Returns a new string with all letters in lowercase.
trim(): Returns a new string with whitespace characters trimmed on both sides.
Simple Methods for String Objects (2 of 2)
Strings are objects in Java. The methods described can only be invoked from a specific string instance (called instance methods).
Static Method: A non-instance method that can be invoked without using an object.
Math Methods: All the methods defined in the Math class are static methods. They are not tied to a specific object instance.
Syntax for Instance Method:
referenceVariable.methodName(arguments)
Syntax for Static Method:
ClassName.methodName(arguments)
(e.g.,Math.pow(a,b)
).
Getting String Length
Example:
String message = "Welcome to Java";
System.out.println("The length of " + message + " is " + message.length());
Getting Characters from a String
Example:
String message = "Welcome to Java";
System.out.println("The first character in message is " + message.charAt(0));
Converting Strings
Example:
"Welcome".toLowerCase()
returns a new string, "welcome"."Welcome".toUpperCase()
returns a new string, "WELCOME"." Welcome ".trim()
returns a new string, "Welcome".
String Concatenation
Example:
String s3 = s1.concat(s2);
String s3 = s1 + s2;
// Three strings are concatenatedString message = "Welcome " + "to " + "Java";
To concatenate string Chapter with number
2
:String s = "Chapter" + 2;
//s
becomes "Chapter2".To concatenate string Supplement with character
B
:String s1 = "Supplement" + 'B';
//s1
becomes "SupplementB".
Reading a String From the Console
Example:
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);
Reading a Character From the Console
Example:
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);
Comparing Strings
Methods Description:
equals(s1)
: Returns true if this string is equal to strings1
.equalsIgnoreCase(s1)
: Returns true if this string is equal to strings1
(case insensitive).compareTo(s1)
: Returns an integer that indicates whether this string is greater than, equal to, or less thans1
.compareToIgnoreCase(s1)
: Same ascompareTo
but case insensitive.startsWith(prefix)
: Returns true if this string starts with the specified prefix.endsWith(suffix)
: Returns true if this string ends with the specified suffix.
Obtaining Substrings
Methods and Descriptions:
substring(beginIndex)
: Returns this string’s substring that begins with the character at the specifiedbeginIndex
and extends to the end of the string.substring(beginIndex, endIndex)
: Returns this string’s substring that begins at the specifiedbeginIndex
and extends to the character at indexendIndex - 1
. Note that the character atendIndex
is not part of the substring.
Finding a Character or a Substring in a String (1 of 2)
Methods and Descriptions:
indexOf(ch)
: Returns the index of the first occurrence ofch
in the string; returns -1 if not matched.indexOf(ch, fromIndex)
: Returns the index of the first occurrence ofch
afterfromIndex
in the string; returns -1 if not matched.indexOf(s)
: Returns the index of the first occurrence of strings
in this string; returns -1 if not matched.indexOf(s, fromIndex)
: Returns the index of the first occurrence of strings
in this string afterfromIndex
; returns -1 if not matched.lastIndexOf(ch)
: Returns the index of the last occurrence ofch
in the string; returns -1 if not matched.lastIndexOf(ch, fromIndex)
: Returns the index of the last occurrence ofch
beforefromIndex
in this string; returns -1 if not matched.lastIndexOf(s)
: Returns the index of the last occurrence of strings
; returns -1 if not matched.lastIndexOf(s, fromIndex)
: Returns the index of the last occurrence of strings
beforefromIndex
; returns -1 if not matched.
Finding a Character or a Substring in a String (2 of 2)
Example:
int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
Conversion between Strings and Numbers
Examples:
int intValue = Integer.parseInt(intString);
double doubleValue = Double.parseDouble(doubleString);
String s = number + "";
Formatting Output
Use the
printf
statement.Syntax:
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 and begins with a percent sign.
Frequently-Used Specifiers
Specifiers and Outputs:
%b
: a boolean value (true or false)%c
: a character (e.g., 'a')%d
: a decimal integer (e.g., 200)%f
: a floating-point number (e.g., 45.460000)%e
: a number in standard scientific notation (e.g., 4.556000e+01)%s
: a string (e.g., "Java is cool")
Example:
int count = 5;
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
displayscount is 5 and amount is 45.560000 items
.
Format Decimal Places
Example:
public class Specifier { public static void main(String[] args) { System.out.printf("The number is %10.2f", 23.3658); } }
This example specifies the number format:
The first value defines the total width of the output.
The second value specifies the number of decimal places.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved.