What is an object?
java
// String is a class. greeting is an object (instance of String)
String greeting = "Hello, AP CS!";
// greeting has state (the characters) and behavior (methods like length(), substring())
System.out.println(greeting.length()); // 13
System.out.println(greeting.toUpperCase()); // HELLO, AP CS!
Classes vs. Objects
java
String name1 = "Alice";
String name2 = "Bob";
String name3 = "Charlie";
// Three different String objects, all from the same String class
Reference types vs. Primitive types
java
// Primitive — holds the value directly
int score = 95;
// Reference — holds a reference to an object in memory
String name = "Alice";
Memory model
Primitive: score -> [ 95 ]
Reference: name -> [ address ] ----> String object: "Alice"
null references
java
String s = null; // s doesn't reference any object
System.out.println(s.length()); // NullPointerException!
Reference aliasing
java
String a = "hello";
String b = a; // b now points to the same object as a
System.out.println(a == b); // true — same reference
a --> [ address ] --\\
\\----> "hello"
b --> [ address ] --/
The dot operator
java
String word = "computer";
// Calling methods with the dot operator
int len = word.length(); // 8
char first = word.charAt(0); // 'c'
String upper = word.toUpperCase(); // "COMPUTER"
boolean hasC = word.contains("com"); // true
Complete example
java
public class ObjectDemo {
public static void main(String[] args) {
// Creating String objects
String course = "AP Computer Science A";
String empty = "";
String nothing = null;
// Using methods (behavior)
System.out.println(course.length()); // 22
System.out.println(course.substring(0, 2)); // "AP"
System.out.println(empty.length()); // 0
// Checking for null before using
if (nothing != null) {
System.out.println(nothing.length());
} else {
System.out.println("nothing is null!");
}
}
}
AP Exam Tips
- •
- •
- •
- •
- •