Skip to main content

Section 9.5 Forgetting to use the new keyword to create an object

Unlike Python, where you can create a new object without explicitly using a keyword, Java requires the new keyword to instantiate a new object.
Listing 9.5.1.
The error message in Listing 9.5.1 occurs when you forget to use the new keyword to instantiate an object. Specifically, on line 8 of Histo.java, data = Scanner(new File("test.dat")); leads to a ’cannot find symbol’ error. While the message states ’symbol: method Scanner(File)’, this can be misleading. Java incorrectly interprets Scanner() as an attempt to call a static method named Scanner within the Histo class (or an inherited one). However, Scanner is a constructor of the Scanner class, not a standalone method, and therefore requires the new keyword (e.g., data = new Scanner(new File("test.dat"));) to create a new Scanner object.

Checkpoint 9.5.2.

Based on Listing 9.5.1, select all of the statements that are true about creating objects in Java.
  • Java requires the new keyword to create a new object.
  • Correct! Unlike Python, Java needs the new keyword to instantiate an object.
  • Writing data = new Scanner(new File("test.dat")); would fix the error.
  • Correct! Adding new before Scanner properly creates the object and resolves the error.
  • Scanner is a constructor of the Scanner class, not a standalone method.
  • Correct! Because Scanner is a constructor, it must be called with new.
  • Java can create objects without a keyword, just like Python.
  • Incorrect. Unlike Python, Java requires the new keyword to instantiate objects.
  • The "cannot find symbol" error here means the Scanner class was not imported.
  • Incorrect. The Scanner class is imported; the error is caused by the missing new keyword.
You have attempted of activities on this page.