Browse Certification Practice Tests by Exam Family

Java 17 1Z0-829: Logging and Annotations

Try 10 focused Java 17 1Z0-829 questions on Logging and Annotations, with explanations, then continue with IT Mastery.

On this page

Open the matching IT Mastery practice page for timed mocks, topic drills, progress tracking, explanations, and full practice.

Try Java 17 1Z0-829 on Web View full Java 17 1Z0-829 practice page

Topic snapshot

FieldDetail
Exam routeJava 17 1Z0-829
Topic areaLogging API and Standard Annotations
Blueprint weight7%
Page purposeFocused sample questions before returning to mixed practice

How to use this topic drill

Use this page to isolate Logging API and Standard Annotations for Java 17 1Z0-829. Work through the 10 questions first, then review the explanations and return to mixed practice in IT Mastery.

PassWhat to doWhat to record
First attemptAnswer without checking the explanation first.The fact, rule, calculation, or judgment point that controlled your answer.
ReviewRead the explanation even when you were correct.Why the best answer is stronger than the closest distractor.
RepairRepeat only missed or uncertain items after a short break.The pattern behind misses, not the answer letter.
TransferReturn to mixed practice once the topic feels stable.Whether the same skill holds up when the topic is no longer obvious.

Blueprint context: 7% of the practice outline. A focused topic score can overstate readiness if you recognize the pattern too quickly, so use it as repair work before timed mixed sets.

Sample questions

These questions are original IT Mastery practice items aligned to this topic area. They are designed for self-assessment and are not official exam questions.

Question 1

Topic: Logging API and Standard Annotations

A method receives an Object from a legacy API. With lint warnings enabled, the only warning is the unchecked cast on the local variable declaration shown below. The team wants the narrowest suppression that targets only that warning.

import java.util.*;

class Importer {
    void load(Object source) {
        List<String> names = (List<String>) source;
        System.out.println(names.size());
    }
}

Which change correctly applies @SuppressWarnings?

Options:

  • A. Annotate the local variable with @SuppressWarnings("unchecked").

  • B. Annotate the class with @SuppressWarnings("unchecked").

  • C. Annotate the method with @SuppressWarnings("rawtypes").

  • D. Annotate the cast expression with @SuppressWarnings("unchecked").

Best answer: A

Explanation: @SuppressWarnings should be placed on the smallest declaration that contains the warning and should name the relevant warning category. Here, the warning is an unchecked cast during the local variable declaration, so the local variable can be annotated with "unchecked".

@SuppressWarnings is a source-retained standard annotation used on declarations such as types, methods, fields, parameters, constructors, local variables, and modules. It is not meant to be applied broadly when a smaller scope works. In this code, the compiler warning is caused by casting Object to List<String>, which is an unchecked cast because generic type information is not fully available at runtime. Placing @SuppressWarnings("unchecked") directly on the local variable declaration suppresses that specific warning without hiding unrelated warnings elsewhere.

Using "rawtypes" would target a different warning category, and annotating the whole class or method is broader than necessary.

  • Class-level suppression hides unchecked warnings throughout the class, not just the legacy cast.
  • Wrong warning key fails because "rawtypes" does not match an unchecked cast warning.
  • Expression annotation fails because @SuppressWarnings is used on declarations, not directly on a cast expression.

Question 2

Topic: Logging API and Standard Annotations

An application must use only Java SE 17 java.util.logging. It wants a ConsoleHandler to choose the output destination and a SimpleFormatter to control the text layout. Which line correctly belongs in the blank?

var logger = Logger.getLogger("audit");
logger.setUseParentHandlers(false);

var handler = new ConsoleHandler();
__________;
logger.addHandler(handler);

logger.info("created");

Options:

  • A. logger.addHandler(new SimpleFormatter())

  • B. handler.publish(new SimpleFormatter())

  • C. logger.setFormatter(new SimpleFormatter())

  • D. handler.setFormatter(new SimpleFormatter())

Best answer: D

Explanation: In java.util.logging, a Handler sends log records to a destination such as the console or a file. A Formatter controls how those records are converted to text, so it is configured on the handler, not on the logger.

The Java Logging API separates responsibilities. A Logger creates and routes LogRecord objects. A Handler, such as ConsoleHandler, publishes those records to a destination. A Formatter, such as SimpleFormatter, is assigned to a handler with setFormatter() so the handler knows how to render each record.

The key rule is that formatting is a handler concern. The logger can have handlers added with addHandler(), but it does not have a setFormatter() method, and a formatter is not itself a handler.

  • Logger formatting fails because Logger does not own the output text format.
  • Adding a formatter fails because addHandler() requires a Handler, not a Formatter.
  • Publishing directly fails because publish() expects a LogRecord, not a formatter.

Question 3

Topic: Logging API and Standard Annotations

A method catches an IOException while reading a file. The team is choosing the java.util.logging call; it should use the overload that logs at WARNING with ex as the record’s thrown exception and file in the message. Do not predict whether any handler will publish it.

Logger logger = Logger.getLogger("app");
Path file = Path.of("data.txt");
IOException ex = new IOException("disk");

Which call best meets the requirement?

Options:

  • A. logger.warning("Read failed for " + file, ex);

  • B. logger.log(Level.WARNING, "Read failed for {0}", new Object[] { file, ex });

  • C. logger.log(Level.WARNING, "Read failed for " + file, ex);

  • D. logger.log(Level.WARNING, "Read failed for {0}", ex);

Best answer: C

Explanation: The decisive API distinction is the Logger.log(Level, String, Throwable) overload. It supplies the level, the message text, and the thrown exception without depending on console output or logging configuration.

In java.util.logging, the convenience methods such as warning do not have a (String, Throwable) overload. To attach an exception to the LogRecord, use log(Level, String, Throwable). Concatenating file into the message makes the path part of the message text, and passing ex as the third argument selects the throwable overload. Handler levels, formatters, and external configuration may affect whether or how the record is displayed, but they do not change which overload the source code calls.

The closest trap is using formatting parameters; those set message parameters, not the record’s thrown exception.

  • Convenience method trap fails because warning accepts a message or supplier, not a separate Throwable argument.
  • Placeholder with exception selects the Throwable overload, so {0} is not filled with the file path.
  • Parameter array trap supplies formatting parameters but does not set ex as the thrown exception.

Question 4

Topic: Logging API and Standard Annotations

A developer adds a standard annotation to a Java 17 helper method that is not intended to be overridden. Compilation fails with an error that the method is neither final nor private.

import java.util.*;

class ReportMerger {
    @SafeVarargs
    void merge(List<String>... parts) {
        for (var p : parts)
            System.out.println(p.size());
    }
}

Which change best fixes the cause while preserving the annotation’s intent?

Options:

  • A. Replace @SafeVarargs with @FunctionalInterface .

  • B. Annotate ReportMerger with @Deprecated.

  • C. Add @SuppressWarnings("unchecked") to the class.

  • D. Declare merge as final.

Best answer: D

Explanation: @SafeVarargs is used to assert that a varargs method with a non-reifiable element type is safe. Java only permits it on constructors and methods that cannot be overridden, so making this non-overridable helper final matches the annotation’s intent.

The core issue is the permitted use of the standard annotation @SafeVarargs. A method annotated with @SafeVarargs must be a varargs method and must not be overridable. In Java 17, that means the method can be static, final, or private, or it can be a constructor. The shown method is a varargs method, but it is an ordinary instance method, so the compiler rejects the annotation. Since the stem says the helper is not intended to be overridden, declaring the method final fixes the compile error without changing the purpose of the annotation.

  • Functional interface confusion fails because @FunctionalInterface applies to interfaces, not varargs method safety.
  • Suppressing warnings does not make an invalid @SafeVarargs placement legal.
  • Deprecation marker only signals discouraged API use; it does not affect varargs or override rules.

Question 5

Topic: Logging API and Standard Annotations

A library team is compiling on Java 17. The method legacyPrice() must remain callable for binary compatibility, but new source code that calls it should receive deprecation warnings. The team also wants tools to know the API has been deprecated since version 4.1 and is planned for removal. Which declaration correctly applies the standard annotation?

Options:

  • A. @Deprecated(since = "4.1", forRemoval = true) public int legacyPrice() { return 0; }

  • B. @SuppressWarnings("deprecation") public int legacyPrice() { return 0; }

  • C. @Deprecated(since = 4.1, forRemoval = "true") public int legacyPrice() { return 0; }

  • D. @Deprecated("4.1", true) public int legacyPrice() { return 0; }

Best answer: A

Explanation: Java 17’s @Deprecated annotation marks a declaration as deprecated and can include metadata. The since element is a String, and forRemoval is a boolean, so the annotation with since = "4.1" and forRemoval = true correctly expresses the stated intent.

The standard @Deprecated annotation is used on declarations such as methods, classes, fields, and constructors to indicate that their use is discouraged. In Java 17, it has two optional elements: since, which takes a String, and forRemoval, which takes a boolean. Marking legacyPrice() with @Deprecated keeps the method callable but allows compilers and tools to warn callers that use it. @SuppressWarnings("deprecation") has the opposite purpose: it suppresses deprecation warnings in the annotated scope; it does not deprecate the API.

The key distinction is marking an API as deprecated versus suppressing warnings about using one.

  • Positional values fail because @Deprecated does not accept two unnamed annotation values.
  • Wrong element types fail because since must be a string and forRemoval must be a boolean.
  • Suppressing warnings fails because @SuppressWarnings("deprecation") does not mark a method as deprecated.

Question 6

Topic: Logging API and Standard Annotations

A service uses Java Util Logging. The auditText() method is expensive and should be invoked only if FINE messages are enabled for the logger. Which statement should replace the comment?

class AuditService {
    private static final Logger LOG =
        Logger.getLogger(AuditService.class.getName());

    static String auditText() { return "audit"; }

    static void audit() {
        // replace this line
    }
}

Options:

  • A. LOG.fine(auditText());

  • B. LOG.log(Level.FINE, () -> auditText());

  • C. LOG.log(auditText(), Level.FINE);

  • D. LOG.log(Level.FINE, auditText());

Best answer: B

Explanation: Logger has overloads that accept a Supplier<String> for lazy message construction. Passing a lambda to log(Level, Supplier<String>) lets the logging framework call auditText() only when the FINE record will be logged.

The core rule is that normal method arguments are evaluated before the logging method is called, but a Supplier<String> passed to a Logger logging method can be evaluated lazily. In this scenario, auditText() is expensive, so calling it directly as an argument defeats the requirement even if the logger later filters out FINE records.

Using LOG.log(Level.FINE, () -> auditText()) passes a supplier, not the result of auditText(). The logger can check whether FINE is loggable before invoking the supplier. The key takeaway is to use the supplier overload when message creation should be conditional on the log level.

  • Eager argument fails because LOG.log(Level.FINE, auditText()) calls auditText() before log runs.
  • Convenience method fails because LOG.fine(auditText()) also evaluates the message eagerly.
  • Wrong parameter order fails because Logger does not provide a log(String, Level) overload.

Question 7

Topic: Logging API and Standard Annotations

Assume this Java 17 program is run as shown; imports are included and external logging configuration is not needed to answer. What does the final System.out.println call print?

import java.util.*;
import java.util.logging.*;

public class LogDemo {
  static int built;
  public static void main(String[] args) {
    var log = Logger.getLogger("demo.local");
    log.setUseParentHandlers(false);
    log.setLevel(Level.WARNING);
    var seen = new ArrayList<String>();
    var h = new Handler() {
      public void publish(LogRecord r) { seen.add(r.getMessage()); }
      public void flush() {}
      public void close() {}
    };
    h.setLevel(Level.ALL);
    log.addHandler(h);
    log.info(() -> { built++; return "info"; });
    log.warning(() -> { built++; return "warn"; });
    System.out.println(seen + ":" + built);
  }
}

Options:

  • A. It prints []:0.

  • B. It prints [warn]:2.

  • C. It prints [warn]:1.

  • D. It prints [info, warn]:2.

Best answer: C

Explanation: Logger checks whether a level is loggable before publishing a record. With the logger level set to WARNING, the info call is ignored and its supplier is not evaluated, while the warning call is accepted by the logger and the custom handler.

The core rule is that java.util.logging.Logger filters a message using the logger’s effective level before creating and publishing a log record. Supplier-based logging methods, such as info(Supplier<String>) and warning(Supplier<String>), evaluate the supplier only if that level is loggable. Here, INFO is lower than WARNING, so the info supplier does not run and built is not incremented for it. The WARNING call is loggable, its supplier runs, and the custom handler adds warn to seen. Setting the handler to Level.ALL allows accepted records through the handler, but it does not override the logger’s own level filtering.

  • Handler level confusion fails because Level.ALL on the handler cannot publish records rejected by the logger.
  • Supplier evaluation fails because disabled supplier-based log calls do not evaluate their suppliers.
  • No console dependency fails because the custom handler records the accepted message without needing parent handlers or console configuration.

Question 8

Topic: Logging API and Standard Annotations

Assume required imports exist and this code is in a method:

Logger logger = Logger.getLogger("app");
IOException ex = new IOException("disk");

Which logger call is the standard Java 17 way to create a log record at WARNING level with ex recorded as the thrown exception, without assuming anything about handlers or external logging configuration?

Options:

  • A. logger.log(Level.WARNING, "Read failed", ex);

  • B. logger.log(Level.WARNING, "Read failed", new Object[] { ex });

  • C. logger.warning("Read failed", ex);

  • D. logger.log("Read failed", Level.WARNING, ex);

Best answer: A

Explanation: The Java Logging API provides an overload log(Level, String, Throwable) for attaching an exception to a log record. This rule is independent of whether any handler later prints the record or how logging is configured externally.

In java.util.logging, the durable API rule is about which method overload creates the LogRecord. The call log(Level.WARNING, "Read failed", ex) matches Logger.log(Level level, String msg, Throwable thrown), so the exception is stored as the thrown exception for the record. Whether the record is emitted, filtered, formatted, or written anywhere depends on logger and handler configuration, which the question deliberately does not rely on.

The key takeaway is to choose an overload that explicitly accepts Throwable in the thrown-exception position.

  • Convenience method trap fails because warning() does not have a two-argument overload accepting a Throwable.
  • Parameter order trap fails because log() expects the Level before the message.
  • Formatting parameter trap fails because Object[] supplies message parameters, not the record’s thrown exception.

Question 9

Topic: Logging API and Standard Annotations

A Java 17 application uses only the standard java.util.logging API. The team wants to send log output to the console and control how each log record appears as text. Which statement correctly describes the roles of Handler and Formatter?

Options:

  • A. A Formatter routes records; a Handler only localizes messages.

  • B. A Handler creates loggers; a Formatter controls level inheritance.

  • C. A Handler publishes records; a Formatter converts records to text.

  • D. A Formatter writes files; a Handler only changes message patterns.

Best answer: C

Explanation: The standard Java Logging API separates destination from presentation. A Handler is responsible for publishing LogRecord objects, such as to the console or a file, while a Formatter defines how a record is rendered as text.

In java.util.logging, a Logger produces LogRecord objects and passes them to one or more Handler instances after filtering and level checks. A Handler represents an output target or publishing mechanism, such as ConsoleHandler or FileHandler. A Formatter is attached to a handler when text formatting is needed and supplies the string form of each LogRecord. This separation lets the same destination use different formats, or different destinations use the same format. The closest trap is treating a formatter as the routing mechanism; routing and publication belong to handlers, not formatters.

  • Routing role fails because formatters do not decide which destination receives a record.
  • Logger creation fails because handlers do not create Logger instances or define level inheritance.
  • File writing fails because file output is handled by FileHandler, while the formatter shapes the text.

Question 10

Topic: Logging API and Standard Annotations

A build fails because warnings are treated as errors. Only the cast shown has been reviewed, and the team wants other warnings to remain visible.

import java.util.*;

class Parser {
    List<String> read(Object input) {
        @SuppressWarnings("deprecation")
        var values = (List<String>) input;
        return values;
    }
}

Compiler output includes:

warning: [unchecked] unchecked cast
error: warnings found and -Werror specified

Which change is the best next fix?

Options:

  • A. Add @SuppressWarnings("all") to the Parser class.

  • B. Use @SuppressWarnings("rawtypes") on the values declaration.

  • C. Move @SuppressWarnings("unchecked") to the input parameter.

  • D. Use @SuppressWarnings("unchecked") on the values declaration.

Best answer: D

Explanation: @SuppressWarnings should name the actual warning category and be placed on the smallest effective scope. The compiler reports [unchecked], so deprecation does not apply. Since the warning comes from the local cast, the local variable declaration is the best scoped location.

@SuppressWarnings is not a general error fixer; it only asks the compiler to suppress named warning categories in the annotated scope. Here, the compiler explicitly identifies the warning as [unchecked], caused by casting Object to List<String>. The existing "deprecation" value is unrelated. Because only this cast has been reviewed, placing @SuppressWarnings("unchecked") on the local variable declaration suppresses the reviewed warning without hiding other warnings elsewhere. A broader class-level suppression would make the build quieter but would violate the goal of scoped, relevant suppression.

  • Wrong category fails because rawtypes is for raw generic type usage, not an unchecked cast warning.
  • Wrong scope fails because annotating the parameter does not cover the cast expression in the method body.
  • Too broad fails because class-level "all" can hide unrelated warnings that the team wants to keep visible.

Continue with full practice

Use the Java 17 1Z0-829 Practice Test page for the full IT Mastery route, mixed-topic practice, timed mock exams, explanations, and web/mobile app access.

Try Java 17 1Z0-829 on Web View Java 17 1Z0-829 Practice Test

Free review resource

Read the Java 17 1Z0-829 Cheat Sheet on Tech Exam Lexicon, then return to IT Mastery for timed practice.

Revised on Thursday, May 14, 2026