The Math class contains a variety of static methods and constants that can be used by programmers for calculations and comparisons. All of the methods are called from the class name (Math). Each method takes at least one parameter, performs the required operations and then returns the result. The result can be either stored in a variable, output, or used in a calculation. Below are a few of the more commonly used Math class methods.
Square Root
returns the square root of a number
Math.sqrt(81);
9
Powers
returns the base (first number) raised to the power (second number)
Math.pow(2,3);
8
Minimum Value
returns the smaller of two numbers and two numbers only
Math.min(4,6);
4
Maximum
returns the larger of two values and only two values
Math.max(4,6);
6
Rounding
returns rounded value of the parameter (.5+ rounds up, under .5 rounds down)
Math.round(4.3); Math.round(4.6);
4 5
Rounding Down
returns the next lowest integer (always rounds down)
Math.floor(4.3); Math.foor(4.6);
4 4
Rounding Up
returns the next highest integer (always rounds up)
Math.ceil(4.3); Math.ceil(4.6);
5 5
Absolute Value
returns the absolute value of a number - its positive distance from zero
Math.abs(-5); Math.round(6);
5 6
Random Numbers
generates a random number between 0(inclusive) and 1.0 (exclusive)
Math.random();
.765849448
Pi
a constant variable that returns the value of Pi 3.1415...
Math.PI
3.1415...
Below are some examples of the Math methods and constants in action:
In line (1), the value for radius could be obtained from input or another calculation. In line (2), the diameter is calculated and stored by doubling the radius. Then, the circumference is calculuated with the diameter and the PI constant. Finally, in line (4), the circumference value is output.
This example calculates and outputs the value of the area of a circle in one line, as opposed to the step by step approach previously displayed in the circumference example. In line(2), the radius is rasied to the second power, then multiplied by PI and then output.
This example uses the pythagorean theorem (a2 + b2 = c2) to find the missing hypotenuse of a right triangle. Notice how the pow functions are placed inside the sqrt function. This can also be done in separate steps if desired.
Random Numbers
The Math.random() function generates a value from 0 (inclusive) to 1.0 (exclusive). This can be represented in mathematics using interval notation. A square bracket, [ or ], means inclusive and a parenthesis, ( or ), means exclusive. So, the range of Math.random() can be represented as [0, 1).
So, to get different ranges, we need to do mathematical operations on the result of Math.random(). For example, if we do Math.random()*10, the range becomes [0, 10). If we add 1, we get [1, 11). Finally, if we cast the result as an int, we get only integer values
Integer.parseInt(Math.random()*10+1);
In a more generic sense, the number we multiply the Math.random() by is the range (or the amount) of numbers and the number we add is the starting value (minimum). So, a general formula to create a random number between a min and max (inclusive) would be:
Integer.parseInt(Math.random()*(max-min+1)+min);
The String Class
The String class methods operate on and alter String values. Unlike the Math class, they are not called from the class. Instead, they are called from a String variable. This means that a String variable must first be declared and initialized prior to calling a String method.
Many of the String methods operate using indicies which is the number order of the characters. String character counting starts at zero.
Additionally, String method are non-mutators. In other words, the String method returns an altered copy of the String, but does not alter the original String. The String is said to be immutable.
Below, you will find examples of several of the more prominent String methods. For all examples, assume that String str="programming".
Length
a property (not method) that returns the number of characters in the string.
str.length;
11
Find a string in a string
returns the starting index of the first occurrence of a string in str. If the parameter string is not found, the method returns -1.There also exists a lastIndexOf method which does the same in reverse AND a version of indexOf that takes a second parameter where it starts the search
str.indexOf("gram");
str.indexOf("java");
3 -1
Index Character
returns the character at the specified index
str.charAt(4);
r
Case Changes
returns a copy of the string with all of the character alter to either upper or lower case
str.toUpperCase();
str.toLowerCase();
PROGRAMMING programming
String Parts
returns a substring of the string starting at the first value. If only one value is given, the substring is from that point (inclusive) to the end of the string. If a second value is given, the substring goes up to, but not including, the character at the second value.
str.substring(7);
str.substring(3,7);
ming gram
Below are some examples of the String methods in action:
The output from this code is Sally:::SALLY. Remember, that the String methods are NOT mutators. They return an altered COPY of the original.
System.out.println("Do you want to continue? (YES or NO)");
String answer=input.nextLine();
String achar=answer.charAt(0).toLowerCase();
At the end of this segment, the achar variable will hold either 'y' or 'n', assuming the user input was YES or NO. In line(3), the answer input is reduced to its first character (index = 0) and then converted to lower case.
String word="programming";
int firstM=word.indexOf("m");
int firstG=word.indexOf("g");
int smaller=Math.min(firstM, firstG);
int larger=Math.max(firstM, firstG);
String between=word.substring(smaller+1, larger);
System.out.println(between);
This example combines two String methods with two Math methods. In lines (2) and (3), the indexOf method finds the first occurrence of an m(index=6) and of a g(index=3). The Math methods then find which of the values is smaller and which is larger in lines (4) and (5). Finally, in line (6), the substring method is called from smaller+1 (so as not to include the letter) up to but not including the larger - resulting in an output of "ra".