0% found this document useful (0 votes)
41 views34 pages

Chapter 4 Mathematical Functions

The document discusses common mathematical functions and methods in the Java Math class, including pow(), random(), sqrt(), min(), max(), and abs(). It also covers string methods like length(), charAt(), concat(), toUpperCase(), and trim() as well as comparing and testing strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views34 pages

Chapter 4 Mathematical Functions

The document discusses common mathematical functions and methods in the Java Math class, including pow(), random(), sqrt(), min(), max(), and abs(). It also covers string methods like length(), charAt(), concat(), toUpperCase(), and trim() as well as comparing and testing strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Common Mathematical Functions

• Java provides many useful methods in the Math class for performing
common mathematical functions.

• A method is a group of statements that performs a specific task.

• Math.pow(a, b) : power method to compute

• Math.random(): random method for generating a random number.

• Math.Sqrt(x): returns the square root of x.


Common Mathematical Functions
• The min, max, and abs Methods

• The min and max methods return the minimum and maximum numbers of two
numbers (int, long, float, or double). For example, max(4.4, 5.0) returns 5.0, and
min(3, 2) returns 2.

• The abs method returns the absolute value of the number (int, long, float, or
double). For example

• Math.max(2, 3) returns 3

• Math.min(2.5, 4.6) returns 2.5


The random Method
• You have used the random() method in the preceding chapter. This method
generates a random double value greater than or equal to 0.0 and less than
1.0 (0 <= Math.random() < 1.0). You can use it to write a simple expression
to generate random numbers in any range. For example,

• (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.
Comparing and Testing Characters
• Two characters can be compared using the relational operators just like
comparing two numbers. This is done by comparing the Unicodes of the two
characters. For example

• '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'
• For example, the following code tests whether a character ch is an
uppercase letter, a lowercase letter, or a digital character.

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


• For convenience, Java provides the following methods in the Character class
for testing characters as shown in Table
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.

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.


For example,
System.out.println("isDigit('a') is " + Character.isDigit('a’));  false

System.out.println("isLetter('a') is " + Character.isLetter('a’)); true

System.out.println("isLowerCase('a') is "+ Character.isLowerCase('a’)); true

System.out.println("isUpperCase('a') is "+ Character.isUpperCase('a’));false

System.out.println("toLowerCase('T') is "+ Character.toLowerCase('T’)); t

System.out.println("toUpperCase('q') is "+ Character.toUpperCase('q’));  Q


The String Type
• A string is a sequence of characters.
• The char type represents only one character. To represent a string of
characters, use the data type called String. For example, the following
code declares message to be a string with the value "Welcome to
Java".
String message = "Welcome to Java";
Simple Methods for String Objects
Method Description

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
Getting String Length
• You can use the length() method to return the number of characters in a
string. For example, the following code

String message = "Welcome to Java";

System.out.println("The length of " + message + " is "+ message.length());

displays

The length of Welcome to Java is 15


Getting Characters from a String
• 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. For example,
message.charAt(0) returns the character W, as shown in Figure 4.1. Note
that the index for the first character in the string is 0
Concatenating Strings
• You can use the concat method to concatenate two strings. The statement
shown below, for example, concatenates strings s1 and s2 into s3:
String s3 = s1.concat(s2);
You can use the plus (+) operator to concatenate two strings, so the
previous statement is equivalent to
String s3 = s1 + s2;
The following code combines the strings message, " and ", and "HTML" into
one string:
String myString = message + " and " + "HTML";
• Recall that the + operator can also concatenate a number with a string. In this
case, the number is converted into a string and then concatenated. Note that
at least one of the operands must be a string in order for concatenation to
take place. Here are some examples:

// Three strings are concatenated

String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number 2

String s = "Chapter" + 2; // s becomes Chapter2

// String Room is concatenated with character B


• If neither of the operands is a string, the plus sign (+) is the addition
operator that adds two numbers.

• The augmented += operator can also be used for string concatenation. For
example, the following code appends the string "and Java is fun" with the
string "Welcome to Java" in message.

message += " and Java is fun";

• So the new message is "Welcome to Java and Java is fun"


Converting Strings
• The toLowerCase() method returns a new string with all lowercase letters and the
toUpperCase() method returns a new string with all uppercase letters. For example,

• "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 or \n are known as whitespace
characters. For example,

"\t Good Night \n".trim() returns a new string Good Night.


Reading a String from the Console
• To read a string from the console, invoke the next() method on a Scanner
object. For example, the following code reads three strings from the
keyboard:
• 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);
• The next() method reads a string that ends with a whitespace
character. You can use the nextLine() method to read an entire line
of text. The nextLine() method reads a string that ends with the
Enter key pressed. For example, the following statements read a
line of text.

• Scanner input = new Scanner(System.in);

• System.out.println("Enter a line: ");

• String s = input.nextLine();
Reading a Character from the Console
• To read a character from the console, use the nextLine()
method to read a string and then invoke the charAt(0)
method on the string to return a character. For example,
the following code reads a character from the keyboard:
• 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
• The String class contains the methods as shown in Table 4.8 for comparing
two strings
Method Description

equals(s1) Returns true if this string is equal to string s1

equalsIgnoreCase(s1) Returns true if this string is equal to string s1; it is case insensitive

compareTo(s1) Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether
this string is greater than, equal to, or less than s1

compareToIgnoreCase(s1) Same as compareTo except that the comparison is 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

contains(s1) Returns true if s1 is a substring in this string


• How do you compare the contents of two strings? You might attempt to use the ==
operator, as follows:

if (string1 == string2)

System.out.println("string1 and string2 are the same object");

else

System.out.println("string1 and string2 are different objects");

• However, the == operator checks only whether string1 and string2 refer to the same
object; it does not tell you whether they have the same contents. Therefore, you cannot
use the == operator to find out whether two string variables have the same contents.
Instead, you should use the equals method. The following code, for instance, can be used
if (string1.equals(string2))

System.out.println("string1 and string2 have the same contents");

else

System.out.println("string1 and string2 are not equal");

For example, the following statements display true and then false.

String s1 = "Welcome to Java";

String s2 = "Welcome to Java";

String s3 = "Welcome to C++";

System.out.println(s1.equals(s2)); // true
• The compareTo method can also be used to compare two strings. For
example, consider

the following code:

s1.compareTo(s2)

• The method returns the value 0 if s1 is equal to s2, a value less than 0 if
s1 is lexicographically (i.e., in terms of Unicode ordering) less than s2,
and a value greater than 0 if s1 is lexicographically greater than s2.
• The actual value returned from the compareTo method depends
on the offset of the first two distinct characters in s1 and s2 from
left to right. For example, suppose s1 is abc and s2 is abg, and
s1.compareTo(s2) returns -4. The first two characters (a vs. a) from
s1 and s2 are compared. Because they are equal, the second two
characters (b vs. b) are compared. Because they are also equal,
the third two characters (c vs. g) are compared. Since the
character c is 4 less than g, the comparison returns -4.
• public class StringCompareToDemo {
• public static void main(String[] args){
• String name1 = "Bob";
• String name2 = "Bob";
• String name3 = "David";
• if(name2.compareTo(name3)==0)
• System.out.println("The names are equal");
• else if(name2.compareTo(name3) >0)
• System.out.println(name2+" is greater than "+ name3);
• else
• System.out.println(name2+" is less than "+ name3);
• } }
• Note

• The equals method returns true if two strings are


equal and false if they are not. The compareTo
method returns 0, a positive integer, or a negative
integer, depending on whether one string is equal

to, greater than, or less than the other string


• "Welcome to Java".startsWith("We") returns true.

• "Welcome to Java".startsWith("we") returns false.

• "Welcome to Java".endsWith("va") returns true.

• "Welcome to Java".endsWith("v") returns false.

• "Welcome to Java".contains("to") returns true.

• "Welcome to Java".contains("To") returns false


Obtaining Substrings
• You can obtain a single character from a string using the charAt method. You can
also obtain a substring from a string using the substring method in the String class,

• For example,

• String message = "Welcome to Java";

• String message = message.substring(0, 11) + "HTML";

• The string message now becomes Welcome to HTML.


• The String class contains the methods for 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

substring(beginIndex, Returns this string’s substring that begins at the


endIndex) specified beginIndex and extends to the character at
index endIndex – 1
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
• The String class contains the methods for finding substrings.
Method Description
index(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, fromIndex) Returns the index of the last occurrence of ch before fromIndex in this 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, fromIndex) Returns the index of the last occurrence of string s before fromIndex. Returns -1 if
not matched.
• For example,
• "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.
• "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
• Suppose a string s contains the first name and last name separated by a space. You can
use the following code to extract the first name and last name from the string
int k = s.indexOf(' ');
• String firstName = s.substring(0, k);
• String lastName = s.substring(k + 1);

• For example, if s is Kim Jones, the following diagram illustrates how the first name and
last name are extracted.
Conversion between Strings and Numbers
• You can convert a numeric string into a number. To convert a string into an
int value, use the Integer. parseInt method, as follows:

int intValue = Integer.parseInt(intString);

• where intString is a numeric string such as "123". To


convert a string into a double value, use the
Double.parseDouble method, as follows:
• double doubleValue = Double.parseDouble(doubleString);

• where doubleString is a numeric string such as "123.45".

• If the string is not a numeric string, the conversion would cause a


runtime error. The Integer and Double classes are both included in the
java.lang package, and thus they are automatically imported.

• You can convert a number into a string, simply use the string
concatenating operator as follows:

String s = number + "";

You might also like