Skip to the content.

Unit 2 Notes

Unit 2: Using Objects – AP Computer Science A

🔑 Key Concepts

  • Creating objects with new
  • Calling methods on objects
  • String objects and their methods
  • Wrapper classes (Integer, Double, etc.)
  • Autoboxing and unboxing

📦 Object Instantiation

Objects are created using the new keyword.

Scanner input = new Scanner(System.in);
Random rand = new Random();

📚 String Methods

Strings are objects with built-in methods.

String s = "APCSA";
System.out.println(s.length());      // 5
System.out.println(s.indexOf("C"));  // 2
System.out.println(s.substring(1, 3)); // "PC"

Strings are immutable: methods return a new String, not modify the original.


📐 Wrapper Classes

Used to store primitives as objects.

Integer num = new Integer(5);
int x = num.intValue(); // unboxing

⚙️ Autoboxing & Unboxing

Java automatically converts between primitives and wrapper objects.

Integer a = 10;      // autoboxing
int b = a;           // unboxing

✅ Comparing Objects

Use .equals() for objects (not ==):

String a = "hello";
String b = "hello";
System.out.println(a == b);         // false (sometimes true due to string pool)
System.out.println(a.equals(b));    // true

🧪 Practice Multiple Choice (5 Questions)

1. What is printed by the following?

String s = "Java";
System.out.println(s.substring(1, 3));

(A) “Ja”
(B) “av”
(C) “va”
(D) “Jav”
Answer: (B)


2. Which of the following correctly creates a Scanner object to read input from the keyboard?
(A) Scanner scan = Scanner();
(B) Scanner scan = new Scanner();
(C) Scanner scan = new Scanner(System.in);
(D) Scanner scan = System.in;
Answer: (C)


3. What does the Integer wrapper class allow you to do?
(A) Store multiple integers
(B) Convert an integer to a string
(C) Treat an int as an object
(D) Use decimals with integers
Answer: (C)


4. What will the following code print?

String x = "abc";
String y = "abc";
System.out.println(x == y);

(A) true
(B) false
(C) error
(D) depends on the compiler
Answer: (A) (true because of string interning)


5. What will be the output?

Integer i1 = 100;
Integer i2 = 100;
System.out.println(i1 == i2);

(A) true
(B) false
(C) 100
(D) error
Answer: (A) (cached for values between -128 and 127)