Mastering Java: The Ultimate Quiz for 'Thinking in Java'

Disable ads (and more) with a membership for a one time $2.99 payment

Mastering Java: The Ultimate Quiz for 'Thinking in Java'. Dive deep into Java with multiple-choice questions. Challenge yourself with quiz questions designed to test and improve your understanding of the 'Thinking in Java' book. Get ready for your exam!

Practice this question and more.


What is the syntax to declare an ArrayList intended to hold String objects in Java using generics?

  1. ArrayList<String> list = new ArrayList<>();

  2. ArrayList list = new ArrayList<String>();

  3. ArrayList[String] list = new ArrayList();

  4. List<String> list = new ArrayList<String>();

The correct answer is: ArrayList<String> list = new ArrayList<>();

The syntax to declare an ArrayList intended to hold String objects in Java using generics is to use the keyword "ArrayList" followed by the generic type "<String>", and then assign it to a new ArrayList object using the constructor "()". Option A is the correct syntax and is the most efficient and recommended way to declare an ArrayList with generics. Option B may compile, but it does not use the proper syntax for generics and can result in warnings. Option C is not valid syntax for generics in Java. Option D is also valid syntax, but it uses a more general type "List" instead of the specific type "ArrayList", which may not be desired.