Consider the following Java code snippet. What will it print when run?
import java.util.ArrayList; public class Test { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); System.out.println(list.get(1)); } }
Remember that ArrayList is part of java.util package.
The code imports java.util.ArrayList correctly, so it compiles and runs fine. The list has two elements: "apple" at index 0 and "banana" at index 1. The code prints the element at index 1, which is "banana".
What error will this Java code produce if the import statement is removed?
import java.util.HashMap; public class Test { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("one", 1); System.out.println(map.get("one")); } }
Think about what happens if you use a class without importing it or fully qualifying it.
If the import statement is removed, the compiler does not know what HashMap is, causing a compilation error: cannot find symbol HashMap.
Given the following code, why does it cause a compilation error?
import java.util.Date; import java.sql.Date; public class Test { public static void main(String[] args) { Date d = new Date(0); System.out.println(d); } }
Think about what happens when two classes with the same name are imported.
Importing both java.util.Date and java.sql.Date causes ambiguity. The compiler cannot decide which Date class to use, resulting in a compilation error.
Which of the following import statements is correct in Java?
Remember the syntax for import statements requires a semicolon at the end.
Option B is correct because it uses the wildcard * and ends with a semicolon. Option B is missing the semicolon, C has an extra semicolon, and D is missing the wildcard and semicolon.
You have two classes named List in different packages: java.awt.List and java.util.List. You want to use both in the same file without import statements. How do you declare variables of each type?
Use the full package name before the class name to avoid ambiguity.
Option D uses fully qualified names to specify which List class is used. This avoids conflicts without import statements. Other options either omit package names or mix imports incorrectly.
