Java Certification Questions 111 -120  «Prev  Next»


hashCode() implementations for Java

  1. Question: What is generic syntax?

    Answer: Generic syntax is when you put the type in angle brackets.


  2. Question: What do you call the type in angle brackets <String>?


    Answer: The type in angle brackets is referred to as either 1) parameterized type 2) type parameter


  3. Question: How can you declare a generic type parameter for a method argument?

    Answer:

    void takeListOfString(List<String> strings){
      Strings.add(β€œString 1”);
    }
    
        

  4. Question:What is a Java ClassCastException?


    A `ClassCastException` in Java is a runtime exception that occurs when you try to cast an object to a class of which it is not an instance. This typically happens when you're using explicit type casting with object references and the actual object doesn't match the expected type.
    Example:
    Object obj = "Hello, world!";
    Integer num = (Integer) obj;  // This throws ClassCastException
    
    In the above example:
    • obj is a String, but you're trying to cast it to an Integer.
    • Since String is not a subclass of Integer, the cast is invalid and a ClassCastException is thrown.


    Key Points:
    • It is a subclass of java.lang.RuntimeException.
    • It is unchecked (not caught at compile time).
    • It typically results from bad assumptions about the actual type of an object.

    How to Avoid It:
    - Use the `instanceof` operator before casting:
      if (obj instanceof Integer) {
          Integer num = (Integer) obj;
      }
      

    • Prefer generics when dealing with collections to enforce type safety at compile time.
    • Design your code to minimize the need for type casting.

    Answer:


  5. Question:In Java SE 22, is a caller expected to recover from checked exceptions?


    Answer:
    In Java SE 22, as in earlier versions, a caller is expected to recover from checked exceptions, which is the core philosophy behind checked exceptions in Java.
    What does this mean?
    A checked exception (i.e., any subclass of `java.lang.Exception` *except* `RuntimeException`) represents conditions that a reasonable application should anticipate and recover from.
    Example:

    public void readFile(String path) throws IOException {
        Files.readAllLines(Path.of(path));  // may throw IOException
    }
    
    Any caller of `readFile()` must either:
    1. Handle it with a try-catch:
            try {
              readFile("data.txt");
            } catch (IOException e) {
              // recovery logic: maybe retry, notify user, log error, etc.
            }
          
    2. Or declare it and propagate:
            public void processFile() throws IOException {
              readFile("data.txt");
            }
          

    Why checked exceptions exist:
    They force the developer to acknowledge and plan for recoverable problems, like:
    • File not found
    • Network unavailability
    • SQL errors
    • Invalid input data

    Summary: The intent of checked exceptions is to make sure the caller is responsible for recovering, retrying, or gracefully failing.
    Java SE 22 follows this same exception handling model.


  6. Question: Generic Question (See pdf)

    Answer:


  7. Question: How do you update non generic code to make it generic?



    Answer:
    <> Diamond Syntax. Add a type an angle brackets(<>) immediately following the collection type. List<Integer> myList = new ArrayList<Integer>(); 1. After type in variable declaration 2. After type in constructor call


  8. Question: How were pre-Java 5 Generics dealt with?

    Answer:
    Before Java 5 introduced generics, Java used raw types to work with collections and other parameterized classes. Here's how things were typically handled:

    1. πŸ”Έ 1. Use of Raw Types

      Without generics, Java collections (like List, Map, etc.) did not specify a type.
      This meant:

      • You could insert any Object into a collection.
      • You had to explicitly cast elements when retrieving them.

      Example (Pre-Java 5):

      import java.util.*;
      
      List list = new ArrayList(); // raw type
      list.add("Hello");
      list.add(42); // no compile-time error
      
      String s = (String) list.get(0); // explicit cast
      Integer i = (Integer) list.get(1);
          

      βœ… Pros:
      • Flexible
      • No syntax overhead
      ❌ Cons:
      • No type safety
      • Higher chance of ClassCastException at runtime

    2. πŸ”Έ 2. Manual Type Checks with instanceof

      Developers often used instanceof to ensure correctness:

      Object obj = list.get(0);
      if (obj instanceof String) {
          String s = (String) obj;
      }
          
    3. πŸ”Έ 3. Compiler Behavior and Migration Support
      • Java 5 introduced generics for compile-time type safety.
      • Old code using raw types was still backward-compatible, but:
        • Generated compiler warnings (unchecked conversions).
        • Developers were encouraged to use generics (List<String>) for clarity and safety.

    4. πŸ”Έ 4. Bridging Old and New Code

      To migrate from old code:

      // Before (raw type)
      List names = new ArrayList();
      
      // After (with generics)
      List<String> names = new ArrayList<>();
          

    You might still see raw types in legacy APIs or generic libraries for backward compatibility.
    Summary Table
    Feature Pre-Java 5 (Raw Types) Java 5+ (Generics)
    Type safety ❌ No βœ… Yes
    Type cast on retrieval βœ… Required ❌ Not needed
    Compile-time errors ❌ Rare βœ… Enforced
    Syntax clarity ❌ Poor βœ… Improved


  9. Question: What kind of data types could a programmer put into a pre Java 5 collection?

    Answer: The pre Java 5 non generic collections allowed a developer to put any data type into a collection except for primitives.


  10. Question: What is the difference between 1) compilation fails 2) compiles without error 3) compiles without warnings 4) compiles with warnings?

    Answer: In most questions on the exam, you care only about compiles vs. compilation fails, compiler warnings don’t matter for most of the exam. But when you are using generics, and mixing both typed and untyped code, warnings matter. [P641 SCJP_Sun_Certified_Programmer_for_Java6 _PDFDrive]



SEMrush Software