Standard Classes
Javaprovides a number of classes and methods for use by programmers. A few of those items are described below:
Math Class
The Math class methods are static methods that are called from the class name (e.g. Math.sqrt()). Each method takes at least one parameter and performs the required operations on it.
- Math.sqrt(num) - returns the square root of the num
- Math.pow(base, exp) - returns base raised to the exp power
- Math.min(num1, num2) - returns the smallest of the two numbers
- Math.max(num1, num2) - returns the largest of the two numbers
- Math.round(num) - returns the rounded value of num (.5+ rounds up, under .5 rounds down)
- Math.ceil(num) - returns the next highest integer - rounds up (4.2 returns 5)
- Math.floor(num) - returns the next lowest integer - rounds down (6.8 returns 6)
- Math.abs(num) - returns the absolute value of num (-5 returns 5)
- Math.random() - returns a random value between 0 and 1.0
- Math.PI - a constant used to represent 3.1415...
String Class
The String class methods must be called from a string variable. In other words, String str="programming", must first be declared and the methods would be called from the str variable (str.toUpperCase()). Many string method operate on indicies, a numbered order of characters. The important thing to note is that strings start counting at 0. So, in str, the index of the character p is 0.
- length - a property (not method) that returns the number of characters in the string (str.length returns 11)
- indexOf(string) - returns the starting index of the first occurence of string in str, -1 if not found (str.indexOf("gram") returns 3)
- lastIndexOf(string) - does the same as indexOf, but counts backwards from the end
- charAt(num) - returns the character at the specified index (str.charAt(4) returns "r")
- toUpperCase() - returns the string as all upper case (str.toUpperCase() returns PROGRAMMING)
- toLowerCase() - returns the string as all lower case
- substring(start, [end]) - returns a substring of the string starting at start, up to but not including end. If end is not specified, the remainder of the string is included (str.substring(3, 7) returns "gram", str.substring(7) returns "ming")