Mr. Gottsacker
Computer Programming
Methods contain groups of statements that perform a specific task. They make your life easier by providing an interface into common functionality. This chapter is an introduction to methods because you will use a handful of built-in methods. Eventually (in chapter 6), you will write your own methods.
Static methods can be invoked without using an object. They are not tied to an object instance. The syntax is ClassName.methodName(arguments)
.
Instance methods must be invoked from a specific object instance.
These methods are all static methods. They belong to the Math
class, so they should be prefixed with Math
when using them in programs.
Math.PI
is an object of the Math
class, not a method. It holds the double
value that is closest to the actual value of pi.
toRadians(angleInDegrees)
: Returns the angle, converted to radians.
Math.toRadians(30) // returns 0.5236 (same as pi/6)
toDegrees(angleInRadians)
: Returns the angle, converted to degrees.
Math.toDegrees(Math.PI / 2) // returns 90.0
sin(angleInRadians)
: Returns the trigonometric sine of an angle in radians.
Math.sin(Math.PI / 2) // returns 1.0
Math.sin(Math.toRadians(270)) // returns -1.0
Math.sin(Math.PI / 6) // returns 0.5
cos(angleInRadians)
: Returns the trigonometric cosine of an angle in radians.
Math.cos(0) // returns 1.0
Math.cos(Math.toRadians(30)) // returns 0.866
Math.cos(Math.PI / 2) // returns 0
tan(angleInRadians)
: Returns the trigonometric tangent of an angle in radians.
Math.tan(Math.PI / 4) // returns 1.0
asin(angleInRadians)
, acos(angleInRadians)
, atan(angleInRadians)
: Return the inverted trigonometric sine, cosine, tangent (respectively) of an angle.
pow(a, b)
: Returns a
raised to the power of b
.
sqrt(x)
: Returns the square root of x
.
log(x)
: Returns the natural logarithm of x
.
log10(x)
: Returns the base 10 logarithm of x
.
exp(x)
: Returns e raised to the power of x
(e^x).
ceil(x)
: Rounds x
up to its nearest integer. The return type is a double
.
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
floor(x)
: Rounds x
down to its nearest integer. The return type is a double
.
Math.floor(2.1) // returns 2.0
Math.floor(2.0) // returns 2.0
Math.floor(-2.1) // returns -3.0
Math.floor(-2.0) // returns -2.0
rint(x)
: Round x
to its nearest integer value, returning it as a double
. If x is equidistant from two integers, the even one is returned (see **interesting case below).
Math.rint(2.1) // returns 2.0
Math.rint(-2.1) // returns -2.0
Math.rint(2.5) // returns 2.0 **interesting case
Math.rint(-2.5) // returns -2.0
round(x)
: Returns (int) Math.floor(x + 0.5)
if x
is a float
, and (long) Math.floor(x + 0.5)
if x
is a double
.
Math.round(2.5) // returns 3
Math.round(2.0) // returns 2
Math.round(-2.4) // returns -2
max(a, b)
: Returns the greater number out of a
and b
.
Math.max(2, 3) // returns 3
Math.max(2.5, 3) // returns 3.0
min(a, b)
: Returns the lesser number out of a
and b
.
Math.min(2.5, 3) // returns 2.5
abs(x)
: Returns the absolute value of x
.
random()
: Returns a random double
greater than or equal to 0 and less than 1.0.
(int) (Math.random() * 10) // returns a random integer between 0 and 9
(int) (Math.random() * 100) + 1 // returns a random integer between 1 and 100
You have printed text using System.out.print()
with a message in double quotes. These text entries are made up of characters. In Java, each character in a string of text is of the char
data type. When using the char
type, single quotes are used. For example:
char letter = 'a';
There are special characters in Java for representing things like whitespace and quotation marks. Unlike traditional letter and number characters, they are represented with two physical keystrokes. They are always prefixed with a backslash. These are the ones you may commonly use:
Escape sequence | Character name | Example code | Example output |
---|---|---|---|
\t |
tab |
|
|
\n |
newline |
|
|
\" |
quotation mark |
|
|
\\ |
backslash |
|
|
A char
can be cast to an int
, and vice versa. This is because computers store and process characters according to an encoding scheme. Recall that at their lowest level, computers process all information as 0s and 1s. Encoding schemes are responsible for mapping textual characters to binary numbers. We can use the more comprehensible decimal representation of these binary numbers to more quickly understand how this works.
Java supports the Unicode encoding scheme, which includes the ASCII code for representing common American characters. When you cast a char
to an int
, you get its ASCII decimal value. Some commonly used characters and their ASCII decimal mappings are included below. A full table can be found at this link.
Characters | Decimal code value |
---|---|
'0' to '9' |
48 to 57 |
'A' to 'Z' |
65 to 90 |
'a' to 'z' |
97 to 122 |
char
decimal representation
char letter = 'A';
System.out.println(letter); // prints: A
int decimalLetter = (int) letter;
System.out.println(decimalLetter); // prints: 65
Because the ASCII encoding maps characters alphabetically, you can compare characters like you compare numbers. Note that capital letters come before lowercase letters. Consider the following boolean comparisons:
boolean chComp = 'a' < 'b'; // true. ASCII for 'a' (97) is less than the ASCII for 'b' (98).
boolean chComp = 'b' < 'B'; // false. ASCII for 'b' (98) is greater than the ASCII for 'B' (66).
boolean chComp = '1' < '7'; // true. ASCII for '1' (49) is less than the ASCII for '7' (55).
You may need to check what kind of character you have in a program. You can leverage the decimal representations discussed above to perform this check. The following code snippet is a way to accomplish this, assuming the variable ch
stores a 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.");
The Character
class also provides a handful of static
methods to do this as well. You can invoke these with Character.methodName(ch)
, where ch
is a variable of the char
type.
isDigit(ch)
: Returns true if ch
is a numerical character.
System.out.print(Character.isDigit('a')); // prints: false
System.out.print(Character.isDigit('1')); // prints: true
isLetter(ch)
: Returns true if ch
is a letter character.
System.out.print(Character.isLetter('a')); // prints: true
System.out.print(Character.isLetter('1')); // prints: false
isLetterOrDigit(ch)
: Returns true if ch
is a numerical or letter character.
System.out.print(Character.isLetterOrDigit('a')); // prints: true
System.out.print(Character.isLetterOrDigit('1')); // prints: true
System.out.print(Character.isLetterOrDigit('\n')); // prints: false
isLowerCase(ch)
: Returns true if ch
is a lowercase letter character.
System.out.print(Character.isLowerCase('a')); // prints: true
System.out.print(Character.isLowerCase('A')); // prints: false
System.out.print(Character.isLowerCase('1')); // prints: false
isUpperCase(ch)
: Returns true if ch
is an uppercase letter character.
System.out.print(Character.isUpperCase('a')); // prints: false
System.out.print(Character.isUpperCase('A')); // prints: true
System.out.print(Character.isUpperCase('1')); // prints: false
toLowerCase(ch)
: Returns the lowercase version of ch
.
System.out.print(Character.toLowerCase('a')); // prints: a
System.out.print(Character.toLowerCase('A')); // prints: a
toUpperCase(ch)
: Returns the uppercase version of ch
.
System.out.print(Character.toUpperCase('a')); // prints: A
System.out.print(Character.toUpperCase('A')); // prints: A
The char
data type can only hold a single character. When processing or printing text, programmers typically want to use a series of characters. For this, Java has the String
data type. The String
type is a reference type, which differs from the primitive types we have seen thus far. Every String
variable references an object, which has properties and methods. The syntax for invoking an object instance's methods is referenceVariable.methodName(arguments)
.
Strings may be collected from the user in ways similar to those of numbers. Use a Scanner object's next()
method to collect a single word, or its nextLine()
method to collect a whole line of text.
Scanner in = new Scanner(System.in);
System.out.print("What is your first name?");
String firstName = in.next();
in.nextLine(); // needed to eat up the hanging newline character in System.in
System.out.print("What is your full name?");
String fullName = in.nextLine();
String
methods
length()
: Returns the number of characters in a string.
"I love coding!".length(); // returns 14
String text = "I love coding";
System.out.println(text.length()); // prints: 14
charAt(index)
: Returns the character at the specified integer index of the string. Note the indexing begins with 0, so the last character of a string s
is s.length() - 1
.
String message = "Howdy, partner.";
System.out.println("First character: " + message.charAt(0)); // prints: H
System.out.println("Last character: " + message.charAt(14)); // prints: .
System.out.println("Last character: " + message.charAt(message.length() - 1); // prints: .
concat(s2)
: Returns a new string that concatenates the reference string with s2. This method can be simplified with the addition operator ( +
).
String s1 = "You're a great coder";
String s2 = ", sir";
String s3 = s1.concat(s2);
System.out.println(s3); // prints: You're a great coder, sir.
System.out.println(s1 + s2); // prints: You're a great coder, sir.
toUpperCase()
: Returns a new string, capitalizing all letters.
String s1 = "help";
String s2 = s1.toUpperCase();
System.out.print(s2); // prints: HELP
toLowerCase()
: Returns a new string, lowercasing all letters.
String s1 = "eLiTe HaCkErZ";
System.out.print(s1.toLowerCase()); // prints: elite hackerz
trim()
: Returns a new string, removing all whitespace characters on beginning and end of string.
String s1 = " In a galaxy far, far away...\n\t";
String s2 = s1.trim();
System.out.print(s2); // prints: In a galaxy far, far away...
equals(s2)
: Returns true
if all of string's characters match those of s2.
String s1 = "Jedi master";
String s2 = "Jedi master";
String s3 = "jedi master";
System.out.println(s1.equals(s2)); // prints: true
System.out.println(s1.equals(s3)); // prints: false
equalsIgnoreCase(s2)
: Returns true
if all of string's characters match those of s2, ignoring case differences.
String s1 = "Jedi master";
String s2 = "Jedi master";
String s3 = "jedi master";
System.out.println(s1.equalsIgnoreCase(s2)); // prints: true
System.out.println(s1.equalsIgnoreCase(s3)); // prints: true
compareTo(s2)
: Returns a positive integer if s2 comes before the string alphabetically, 0 if the string is the same as s2, or a negative integer if the string comes before s2 alphabetically.
String s1 = "Sith Lord";
String s2 = "Wookiee";
String s3 = "Wookiee";
s1.compareTo(s2); // returns positive integer
s2.compareTo(s1); // returns negative integer
s2.compareTo(s3); // returns 0
compareToIgnoreCase(s2)
: Returns same result as compareTo(s2), but treats different cases as the same letter.
String s1 = "Sith Lord";
String s2 = "sith lord";
String s3 = "Wookiee";
s1.compareToIgnoreCase(s2); // returns 0
s2.compareToIgnoreCase(s3); // returns positive integer
startsWith(prefix)
: Returns true
if the string begins with the given prefix.
String pre = "Mr";
String teacherName = "Mr. Reis";
String teacherName2 = "Mrs. Piper";
String studentName = "Graham Vogt";
teacherName.startsWith(pre); // returns true
teacherName2.startsWith(pre); // returns true
studentName.startsWith(pre); // returns false
endsWith(suffix)
: Returns true
if the string ends with the given suffix.
String suff = "man";
String name = "freshman";
String name2 = "businessperson";
boolean isGendered = name.endsWith(suff); // set isGendered to true
isGendered = name2.endsWith(suff); // set isGendered to false
contains(s)
: Returns true if s is a substring of the string.
String commonWord = "the";
String phrase = "Welcome to the jungle.";
System.out.println(phrase.contains(commonWord)); // prints: true
substring(beginIndex)
: Returns the string's substring beginning with the character at beginIndex
.
String message = "Welcome to Java";
message = message.substring(11) + "Hoth";
System.out.println(message); // prints: Welcome to Hoth
substring(beginIndex, endIndex)
: Returns the string's substring beginning with the character at beginIndex
and ending with the character at endIndex - 1
.
String text = "Luke, I am your father.";
String t1 = text.substring(0, 11);
String t2 = text.substring(11);
String newText = t1 + "not " + t2;
System.out.println(newText); // prints: Luke, I am not your father.
indexOf(ch)
: Returns the index of the first occurrence of char
ch in the string, or -1 if not matched.
indexOf(ch, fromIndex)
: Returns the index of the first occurrence of char
ch in the string after position fromIndex
, or -1 if not matched.
String msg = "Looking for something?";
System.out.println(msg.indexOf('o')); // prints: 1
System.out.println(msg.indexOf('o', 2)); // prints: 9
System.out.println(msg.indexOf('O')); // prints: -1
indexOf(str)
: Returns the index of the first occurrence of String
str in the string, or -1 if not matched.
indexOf(str, fromIndex)
: Returns the index of the first occurrence of String
str in the string after position fromIndex
, or -1 if not matched.
String msg = "Text processing is cool.";
System.out.println(msg.indexOf("cool")); // prints: 19
System.out.println(msg.indexOf("lame")); // prints: -1
lastIndexOf(ch)
: Returns the index of the last occurrence of char
ch in the string, or -1 if not matched.
lastIndexOf(ch, fromIndex)
: Returns the index of the last occurrence of char
ch in the string after positionfromIndex
, or -1 if not matched.
lastIndexOf(str)
Returns the index of the last occurrence of String
str in the string, or -1 if not matched.
indexOf(str, fromIndex)
: Returns the index of the last occurrence of String
str in the string after position fromIndex
, or -1 if not matched.
Integer.parseInt(intString)
: Return the int
value of a numeric string.
String numStr = "789";
int num = Integer.parseInt(numStr); // num holds 789
Double.parseDouble(doubleString)
: Return the int
value of a numeric string.
String numStr = "56.789";
double num = Double.parseDouble(numStr); // num holds 56.789
You can convert a number to a string using the concatenation operator:
int num = 789;
String numStr = num + ""; // num holds "789"