Unit 1 Cycle 1 Day 10: Creating Objects with Constructors
Share
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.
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.