Unit 1 Cycle 1 Day 10: Creating Objects with Constructors

Unit 1 Foundation (Cycle 1) Day 10 of 28 Foundation

Creating Objects with Constructors

Section 1.6 — Objects and Classes

Key Concept

Generating random integers within a specific range is a frequently tested AP CSA skill. The formula (int)(Math.random() * range) + min produces a random integer from min to min + range - 1 inclusive. For example, to simulate a die roll (1-6), use (int)(Math.random() * 6) + 1. The (int) cast truncates the decimal, and since Math.random() never returns exactly 1.0, the maximum value before casting is just under range. Always verify the range by plugging in the boundary values of Math.random(): 0.0 and 0.999...

Consider the following statements about objects in Java.

I. String s = new String("hello"); creates a new String object. II. String t = "hello"; does NOT create a String object. III. String s and String t in the statements above refer to the same object in memory.

Which of the statements are correct?

Answer: (A) I only

Evaluate each statement:

Statement I: CORRECT. new String("hello") explicitly creates a new String object on the heap.

Statement II: INCORRECT. String t = "hello" does create a String object (or references one from the String pool). String literals are still objects in Java.

Statement III: INCORRECT. Using new always creates a distinct object, separate from the String pool. s and t reference different objects (even though their content is the same).

Why Not the Others?

(B) Statement II is wrong. String t = "hello" does create a String object (stored in the String pool). All Strings in Java are objects, whether created with new or as literals.

(C) Statement III is wrong. new String("hello") creates a separate object, so s and t do not reference the same object. s == t would be false.

(D) Both statements II and III are incorrect. II wrongly claims a literal is not an object. III wrongly claims new and a literal share the same reference.

Common Mistake

Many students think String literals are not objects. They are. "hello" is a String object stored in the String pool. The difference with new String("hello") is that new forces creation of a separate object outside the pool.

AP Exam Tip

For I/II/III questions, evaluate each statement independently. Do not let a correct statement convince you the others are also correct. Mark each TRUE or FALSE, then find the matching answer.

Review this topic: Section 1.6 — Objects and Classes • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.