2.2

Creating Objects

AP Computer Science A

What is a method?

java
String greeting = "Hello, World!";
int length = greeting.length();    // calling the length() method → 13

Calling methods — the dot operator

java
objectName.methodName(arguments)
java
String name = "Alice";
System.out.println(name.length());         // 5
System.out.println(name.toUpperCase());     // "ALICE"
System.out.println(name.substring(0, 3));   // "Ali"

Two types of methods

1. Void methods — do something, return nothing

java
System.out.println("Hello");  // prints to console, returns nothing
java
// WRONG — println is void, it doesn't return anything
String result = System.out.println("Hello");  // COMPILE ERROR

2. Non-void methods — do something AND return a value

java
String name = "Alice";
int len = name.length();              // returns 5
String upper = name.toUpperCase();     // returns "ALICE"
boolean match = name.equals("Bob");   // returns false

Parameters and arguments

java
//                argument
//                   ↓
name.substring(3);

// In the String class, substring is defined as:
// public String substring(int beginIndex)  ← parameter

Methods with multiple parameters

java
String text = "Hello, World!";

// substring(int beginIndex, int endIndex)
String sub = text.substring(0, 5);   // "Hello"
//                          ↑    ↑
//                     arg 1  arg 2
java
// Math.pow(base, exponent)
Math.pow(2, 10);    // 2^10 = 1024.0
Math.pow(10, 2);    // 10^2 = 100.0  (order matters!)

Method signatures

java
// Two different methods — different signatures:
substring(int)              // one int parameter
substring(int, int)         // two int parameters

Overloaded methods

java
// Both are named substring, but have different parameters:
"Hello".substring(2);       // "llo"     — signature: substring(int)
"Hello".substring(1, 4);    // "ell"     — signature: substring(int, int)

Chaining method calls

java
String result = "  Hello  ".trim().toUpperCase();
// Step 1: "  Hello  ".trim() → "Hello"
// Step 2: "Hello".toUpperCase() → "HELLO"
// result = "HELLO"

Static methods vs. instance methods

java
// Instance method — called on an object
String name = "Alice";
name.length();           // called on the name object

// Static method — called on the class
Math.sqrt(25);           // called on the Math CLASS, not an object

A complete trace example

java
String word = "Computer";
int len = word.length();
String upper = word.toUpperCase();
String part = word.substring(0, 4);
boolean same = word.equals("computer");

AP Exam Tips

Common Mistakes

Key Vocabulary