Calling methods
java
objectName.methodName(arguments)
java
String word = "computer";
int len = word.length(); // calling length() on a String object
String sub = word.substring(0, 4); // calling substring() with two arguments
Method signatures and return types
java
// Method signature: int length()
// Name: length
// Parameters: none
// Returns: int
// Method signature: String substring(int from, int to)
// Name: substring
// Parameters: two ints
// Returns: String
Void methods vs. return methods
java
// void method — just does something (prints)
System.out.println("Hello"); // cannot assign to a variable
// Return method — gives back a value you can store
int len = "Hello".length(); // stores 5 in len
Parameters and arguments
java
// substring has parameters: (int beginIndex, int endIndex)
// We pass arguments: (0, 5)
String result = "computer".substring(0, 5); // "compu"
Passing by value
java
public static void changeValue(int x) {
x = 99; // changes the local copy, not the original
}
int num = 5;
changeValue(num);
System.out.println(num); // still 5!
Method chaining (calling methods on return values)
java
String text = " Hello World ";
String result = text.trim().toLowerCase();
// Step 1: text.trim() returns "Hello World"
// Step 2: "Hello World".toLowerCase() returns "hello world"
System.out.println(result); // "hello world"
String methods you must know
java
String s = "AP Computer Science";
s.length() // 19
s.substring(0, 2) // "AP"
s.substring(3) // "Computer Science"
s.indexOf("Computer") // 3
s.charAt(0) // 'A'
s.equals("AP Computer Science") // true
s.compareTo("B") // negative ('A' < 'B')
Overloaded methods
java
String s = "mississippi";
// Two versions of indexOf:
s.indexOf("ss"); // 2 — indexOf(String)
s.indexOf("ss", 3); // 5 — indexOf(String, int) — starts searching at index 3
// Two versions of substring:
s.substring(4); // "issippi" — substring(int)
s.substring(4, 7); // "iss" — substring(int, int)
Complete example
java
public class MethodDemo {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps";
// Return methods — capture the result
int wordCount = sentence.length();
int foxPos = sentence.indexOf("fox");
String animal = sentence.substring(foxPos, foxPos + 3);
System.out.println("Length: " + wordCount); // 25
System.out.println("Fox at: " + foxPos); // 16
System.out.println("Animal: " + animal); // "fox"
// Method chaining
String loud = sentence.substring(16, 19).toUpperCase();
System.out.println(loud); // "FOX"
// Boolean method for comparison
System.out.println(animal.equals("fox")); // true
System.out.println(animal.equals("Fox")); // false (case-sensitive)
}
}
AP Exam Tips
- •
- •
- •
- •
- •
- •