Object-Oriented Programming (Java)

Chapter 15
Contemporary Java, AI, Ethics, and Future Directions

Bachelors Program in IT
Object-Oriented Programming (Java)   •   Bachelor

Contemporary Java, AI, Ethics, and Future Directions

Introduction

Java remains one of the most influential platforms in professional software development. Its longevity is not explained simply by the Java programming language. The broader Java platform includes a virtual machine, standard libraries, development tools, frameworks, deployment technologies, security mechanisms, and a large professional community. Contemporary Java therefore involves more than learning classes, inheritance, interfaces, and exceptions. It requires understanding how object-oriented systems operate in cloud environments, how applications can be compiled into native executables, how reactive systems manage asynchronous workloads, and how Java applications consume artificial-intelligence services.

Modern development also creates responsibilities. Software can expose personal data, reproduce social bias, infringe intellectual-property rights, consume substantial energy, or make decisions that are difficult to explain. AI coding assistants increase productivity but introduce questions about authorship, security, reliability, and accountability. Professional Java developers must therefore combine technical competence with ethical reasoning and governance practices.

This chapter examines these developments as connected aspects of contemporary software engineering. It treats Java as both a programming technology and a component of larger sociotechnical systems.

Learning Objectives

By the end of this chapter, students should be able to:

  1. Explain significant developments in modern Java and the implications of its release model.
  2. Describe cloud-native Java principles, including containers, observability, resilience, and twelve-factor design.
  3. Compare JVM execution with ahead-of-time native compilation.
  4. Explain reactive programming and identify when it is appropriate.
  5. Design a responsible integration between a Java application and an AI service.
  6. Evaluate privacy, intellectual property, bias, sustainability, and accountability risks.
  7. Assess the opportunities and limitations of AI coding assistants.
  8. Apply ethical and governance principles to a contemporary Java project.

1. The Modern Java Platform

1.1 Evolution rather than replacement

Java has evolved incrementally while preserving a strong commitment to compatibility. The language has gained features such as lambda expressions, the Stream API, local-variable type inference, records, sealed classes, pattern matching, text blocks, and improved switch expressions. These features reduce boilerplate and express domain models more directly, but they do not eliminate object-oriented design. Instead, they add functional and declarative techniques to the object-oriented foundation.

The Java Platform Module System, introduced in Java 9, provides stronger boundaries between packages and modules. A module can explicitly declare which modules it requires and which packages it exports. This improves maintainability and can reduce accidental dependencies, although migration may be difficult for older applications that rely on reflective access or informal classpath behavior.

Java also follows a regular release cadence. Long-Term Support releases are selected by vendors and organizations for extended maintenance, while non-LTS releases provide earlier access to language, library, and virtual-machine improvements. An organization should choose a release based on support policy, security updates, library compatibility, operational requirements, and migration cost—not merely on the largest version number.

1.2 Records and sealed types

A record is a concise way to express a transparent, mostly immutable data carrier. For example:

public record CustomerId(String value) {
    public CustomerId {
        if (value == null || value.isBlank()) {
            throw new IllegalArgumentException("Customer ID is required");
        }
    }
}

The declaration automatically provides accessors, equality, hashing, and a string representation based on its components. A record is not automatically deeply immutable: if a component refers to a mutable object, that object may still change. Records are particularly useful for API responses, configuration values, and value objects.

Sealed classes and interfaces restrict which types may extend or implement them:

public sealed interface PaymentResult
        permits Approved, Declined, TechnicalFailure { }

This restriction communicates domain alternatives and supports exhaustive pattern matching. It is valuable in systems where an open-ended inheritance hierarchy would make error handling incomplete or unsafe.

1.3 Virtual threads and concurrency choices

Traditional platform threads are closely associated with operating-system threads. Virtual threads are lightweight threads managed by the Java runtime and are useful for large numbers of tasks that spend much of their time waiting for network or database operations. They can make synchronous-looking code scalable without requiring every developer to write callback-based asynchronous code.

Virtual threads do not make CPU-intensive work faster. A computation-heavy task still requires sufficient processor capacity, and blocking a limited external resource—such as a database connection pool—can remain a bottleneck. Developers must also consider thread-local state, synchronization, transaction boundaries, rate limits, and library compatibility.

A sound design begins with workload characterization:

  • I/O-bound workloads often benefit from virtual threads or asynchronous techniques.
  • CPU-bound workloads require careful parallelism and resource measurement.
  • Highly event-driven pipelines may benefit from reactive streams.
  • Shared mutable state should be minimized regardless of the concurrency model.

2. Cloud-Native Java

Cloud-native development is not simply the act of moving an existing application to a cloud provider. It is an approach that emphasizes independently deployable services, automated delivery, elastic infrastructure, observable behavior, resilience, and explicit configuration.

2.1 Core principles

A cloud-native Java service commonly has the following characteristics:

  1. Stateless application instances. Persistent state is stored in a database, object store, or specialized state service rather than in a local process memory that disappears when an instance is replaced.
  2. Externalized configuration. Environment-specific values such as database URLs and credentials are supplied through configuration or secret-management systems, not hard-coded in source code.
  3. Containerized packaging. The application and its runtime dependencies are packaged consistently so that development, testing, and production environments are more alike.
  4. Automated delivery. Builds, tests, security checks, and deployments are repeatable pipeline activities.
  5. Observability. Logs, metrics, and traces provide evidence about system behavior.
  6. Resilience. Timeouts, retries, circuit breakers, bulkheads, and graceful degradation limit the effect of failure.
  7. Security by design. Identity, authorization, dependency updates, secret handling, and network controls are treated as engineering requirements.

Frameworks such as Spring Boot, Quarkus, Micronaut, and Jakarta EE support these practices in different ways. The framework is not the architecture. A poorly designed monolith can be packaged in a container, and a distributed system can be badly operated. Architectural quality depends on boundaries, data ownership, testing, and operational discipline.

2.2 Observability and reliability

A log records an event, a metric summarizes a measurable condition, and a distributed trace follows a request across components. These signals answer different questions. Logs may explain an individual failure; metrics may show that error rates are increasing; traces may reveal that latency originates in a downstream service.

Reliability engineering often uses service-level indicators (SLIs), service-level objectives (SLOs), and service-level agreements (SLAs). For example, an organization might define an availability SLO as the proportion of valid requests that receive an acceptable response during a measurement period. The precise calculation depends on the organization’s definition of valid requests, measurement window, and exclusions. A numerical target without a measurement method is not a meaningful reliability commitment.

Timeouts are essential because a request waiting indefinitely consumes resources. Retries must be bounded and should normally use exponential backoff with jitter. Retrying a non-idempotent operation can duplicate a payment or create repeated records. Consequently, retry policy must be connected to operation semantics, not copied mechanically from a library example.

2.3 Containers and orchestration

A container image is a versioned artifact containing an application and the files needed to run it. Containers improve consistency, but they do not automatically provide security or isolation equivalent to a virtual machine. Images should be minimized, scanned, signed where appropriate, rebuilt regularly, and run with least privilege.

An orchestrator can schedule instances, restart failed processes, expose services, and scale workloads. These capabilities introduce new failure modes: misconfigured health checks can cause restart loops, excessive autoscaling can exhaust a database, and a service may appear healthy while returning incorrect data. Cloud-native design therefore requires testing failure conditions, not only successful requests.

3. JVM Execution and Native Compilation

3.1 The JVM model

Java source code is ordinarily compiled into bytecode. The Java Virtual Machine verifies and executes that bytecode. Frequently executed code may be compiled at runtime by a just-in-time compiler, allowing optimization based on observed behavior. The JVM also provides garbage collection, security boundaries, profiling interfaces, and a mature runtime ecosystem.

This model has several strengths: portability, dynamic optimization, rich diagnostics, and compatibility with a broad library ecosystem. Its costs may include startup time, memory overhead, runtime warm-up, and the need to ship a suitable runtime environment.

3.2 Ahead-of-time compilation

Ahead-of-time (AOT) compilation transforms an application into a native executable before deployment. Technologies such as GraalVM Native Image can produce executables with fast startup and lower memory consumption for suitable applications. These properties are attractive for serverless functions, command-line tools, and rapidly scaling services.

AOT compilation has trade-offs. Dynamic class loading, reflection, proxy generation, serialization, and resource discovery may require explicit configuration. Some runtime optimizations available to a continuously running JIT compiler are unavailable or reduced. Native builds can also take longer and may complicate debugging or cross-platform distribution.

The correct comparison is workload-specific. A service that starts once and runs for weeks may benefit from JIT optimization, while a function invoked briefly may value startup latency more strongly. Teams should benchmark representative workloads using production-like data and traffic rather than relying on general claims.

ConcernJVM with JITNative executable
StartupUsually slowerUsually faster
Warm-upOften requiredMinimal or absent
Runtime optimizationStrong adaptive optimizationMostly decided before deployment
Memory footprintOften largerOften smaller, but application-dependent
Reflection and dynamic behaviorUsually straightforwardMay need configuration
Build processGenerally simplerOften longer and more specialized
Best fitLong-running, dynamic servicesShort-lived or startup-sensitive services

3.3 A decision method

A rational selection can follow four steps:

  1. Define measurable requirements, such as startup time, memory limit, throughput, and diagnostic needs.
  2. Identify application features that depend on reflection, dynamic proxies, class loading, or runtime instrumentation.
  3. Build both deployment forms where practical.
  4. Measure startup, steady-state throughput, tail latency, memory use, build time, and operational effort.

No single compilation strategy is universally superior. The engineering decision is a trade-off among performance, compatibility, cost, and maintainability.

4. Reactive Systems and Asynchronous Design

4.1 The reactive idea

Reactive systems are designed to remain responsive, resilient, elastic, and message-driven. Reactive programming is a related implementation approach in which asynchronous data streams are processed through operators such as mapping, filtering, merging, and error recovery.

A central concept is backpressure: a consumer can signal how much data it can process, preventing a fast producer from overwhelming it. The Reactive Streams specification defines interoperability rules for asynchronous streams, including controlled demand and serialized signaling. Libraries such as Project Reactor and RxJava implement these ideas.

A simplified conceptual pipeline might be represented as:

request → validate → query asynchronously → transform → combine → respond
             |             |                  |
           error       timeout            fallback

Reactive code is not automatically faster. It can improve resource utilization when many operations wait on I/O, but it introduces complexity in debugging, context propagation, cancellation, and error handling. A system should not use reactive programming merely because it is fashionable.

4.2 Choosing between models

Imperative code with virtual threads may offer excellent scalability while retaining familiar control flow. Reactive programming may be appropriate when the entire path—from network client through service composition to response—supports non-blocking operation and backpressure. Mixing blocking calls into a reactive event loop can reduce performance and cause thread starvation.

The choice should consider:

  • latency and throughput requirements;
  • proportion of waiting versus computation;
  • library and database-driver support;
  • team expertise;
  • observability and debugging tools;
  • cancellation and failure semantics;
  • operational complexity.

A small service with moderate traffic may be safer and cheaper to maintain using ordinary request handling. A high-concurrency streaming platform may justify reactive architecture.

5. Integrating AI Services with Java

AI integration generally means that a Java application invokes a model through an API, an SDK, or a locally hosted inference server. The model may generate text, classify content, extract structured information, create embeddings, or support retrieval from a document collection.

5.1 A responsible integration architecture

A robust integration separates application responsibilities from model behavior:

  1. Input boundary: authenticate the caller, validate size and format, and classify sensitivity.
  2. Policy layer: decide whether the request may be sent to an external provider and remove unnecessary personal data.
  3. Prompt or request construction: provide clear instructions, constraints, context, and output format.
  4. Model gateway: centralize provider selection, timeouts, retries, cost controls, logging policy, and safety checks.
  5. Validation layer: parse and validate the response against a schema; do not treat generated text as trusted code or database commands.
  6. Human or business control: require review for high-impact decisions and provide escalation paths.
  7. Audit layer: record appropriate metadata without retaining sensitive prompts unnecessarily.

A Java record can represent structured model output:

public record Classification(String label, double confidence) {
    public Classification {
        if (label == null || label.isBlank()) {
            throw new IllegalArgumentException("Label is required");
        }
        if (confidence < 0.0 || confidence > 1.0) {
            throw new IllegalArgumentException("Confidence must be between 0 and 1");
        }
    }
}

The confidence value in this example is merely a field supplied by a service. It should not automatically be interpreted as a calibrated probability. Calibration and performance must be evaluated for the intended population and task.

5.2 Reliability controls

AI services can be unavailable, slow, expensive, inconsistent, or incorrect. Java clients should use explicit connection and read timeouts, bounded retries, circuit breakers where appropriate, and quotas. Responses should be treated as untrusted external input. JSON schema validation, maximum output sizes, content filtering, and authorization checks reduce risk.

Prompt injection is an important threat in retrieval-augmented systems. A document may contain instructions designed to manipulate the model, even though the document is supposed to be source material. Retrieved content should therefore be treated as data, not as authority. System policies, tool permissions, and output validation must remain outside the model’s control.

5.3 Evaluation

An AI feature requires evaluation beyond a demonstration. Teams should define representative test cases, unacceptable outputs, escalation conditions, and monitoring measures. Evaluation may include accuracy, false-positive and false-negative rates, latency, cost, robustness to adversarial inputs, and performance across relevant demographic or linguistic groups.

For a binary classifier, precision is the proportion of predicted positive cases that are actually positive, while recall is the proportion of actual positive cases that are identified. These measures answer different questions and should not be treated as interchangeable. Their usefulness depends on a clearly defined dataset, labels, decision threshold, and deployment context.

6. AI Coding Assistants

AI coding assistants can generate code, explain APIs, propose tests, refactor methods, translate between languages, and summarize unfamiliar code. They may reduce routine effort and help learners explore alternatives. They can also generate insecure, inefficient, non-compiling, or subtly incorrect code.

6.1 A verification-oriented workflow

A professional workflow treats generated code as a proposal:

  1. State the requirement and constraints precisely.
  2. Ask for a small, reviewable change rather than an entire system.
  3. Inspect dependencies, licenses, assumptions, and error handling.
  4. Compile and run static analysis.
  5. Write or execute tests, including boundary and failure cases.
  6. Check security issues such as injection, authorization, secret exposure, and unsafe deserialization.
  7. Review performance and resource behavior.
  8. Document material AI assistance where organizational policy requires it.

A passing test suite does not prove correctness if the tests are incomplete. Human review remains necessary because requirements include domain, legal, ethical, and organizational considerations that may not be visible in code.

6.2 Educational implications

Students should use coding assistants to strengthen understanding rather than bypass it. A useful assignment may require students to explain generated code, identify its assumptions, produce tests that expose a defect, and compare alternative designs. In professional settings, organizations should define acceptable-use policies covering confidential source code, customer data, attribution, retention, and review obligations.

7. Ethics, Privacy, and Governance

7.1 Privacy and data protection

Privacy is not merely a security feature. Security protects information from unauthorized access or alteration; privacy concerns the justified collection, use, sharing, retention, and deletion of information about people.

Important principles include:

  • collect only data necessary for a defined purpose;
  • communicate purposes clearly;
  • restrict access according to role and need;
  • encrypt data in transit and, where appropriate, at rest;
  • avoid sending personal or confidential data to an AI provider without authorization;
  • define retention and deletion procedures;
  • support access, correction, and other rights required by applicable law;
  • maintain records of processing and meaningful risk assessments where required.

The exact legal obligations vary by jurisdiction and sector. Developers should not present a technical design as legally compliant without qualified legal and privacy review.

7.2 Intellectual property and licensing

Software projects combine original code, open-source dependencies, generated artifacts, data, documentation, and sometimes model outputs. Each may have different rights and obligations. A dependency’s license can impose notice, attribution, source-disclosure, or distribution conditions. Generated code may resemble existing material, and the legal status of AI-generated content differs across jurisdictions and circumstances.

A responsible process maintains a software bill of materials, records dependency licenses, scans for known vulnerabilities, and preserves provenance for important artifacts. Developers should not paste proprietary code or confidential customer information into an AI tool unless the organization has expressly approved the practice and understands provider terms.

7.3 Bias and fairness

Bias can enter through historical data, sampling, labels, feature selection, model design, thresholds, and operational use. Removing a sensitive attribute does not necessarily remove discrimination because other variables may act as proxies.

Fairness is context-dependent. A system used to prioritize support tickets may have different harms from a system used in employment, credit, education, or healthcare. Teams should identify affected groups, consult domain experts and stakeholders, test performance across relevant subgroups, and establish remediation and appeal processes.

A fairness metric is not a universal certificate of fairness. Some desirable statistical properties cannot generally all be satisfied simultaneously when groups have different base rates. Therefore, technical measures must be connected to a normative decision about acceptable risk and treatment.

7.4 Accountability and explainability

Accountability means that identifiable people and institutions remain responsible for system outcomes. “The model decided” is not an adequate governance explanation. A system should have an owner, documented purpose, approval criteria, monitoring responsibilities, incident procedures, and a mechanism for correction or appeal.

Explainability has several meanings. A global explanation describes general system behavior; a local explanation concerns one output; a process explanation documents how data, rules, model versions, and human decisions contributed to an outcome. In high-impact contexts, a plausible explanation is not sufficient if the decision itself is invalid, discriminatory, or impossible to contest.

7.5 Sustainability

Software affects sustainability through hardware utilization, data transfer, storage, cooling, and the energy required to train or operate models. Efficient algorithms, right-sized infrastructure, caching, batching, lifecycle management, and avoidance of unnecessary inference can reduce environmental impact.

A useful engineering approach measures rather than assumes. Teams can track request volume, execution time, memory allocation, storage growth, and infrastructure utilization. Measurements should be interpreted carefully because energy depends on hardware, location, workload, and provider accounting methods. Sustainability is therefore a system property and a governance concern, not only a code-optimization exercise.

8. A Responsible Digital-Transformation Framework

A contemporary Java project can use the following lifecycle:

Define: articulate the problem, affected stakeholders, intended benefits, unacceptable uses, and success measures.

Discover: identify data sources, dependencies, model providers, legal constraints, accessibility needs, and environmental effects.

Design: choose architecture, deployment model, concurrency approach, privacy controls, human oversight, and failure behavior.

Implement: apply secure coding, dependency management, schema validation, tests, observability, and documentation.

Evaluate: test functional correctness, security, fairness, robustness, performance, cost, and usability with representative cases.

Deploy gradually: use feature flags, canary releases, rollback plans, and clear ownership.

Monitor and improve: review incidents, drift, complaints, cost, energy use, and changes in law or provider behavior.

This framework emphasizes that responsible transformation is continuous. Ethical analysis performed only at project approval will not detect risks introduced by later data, model, dependency, or business changes.

9. Illustrative Case: A Java Claims-Triage Service

Background

An insurance organization operates a Java service that receives claim descriptions and routes them to specialist teams. Management proposes an AI service to classify claims and prioritize urgent cases. The application is being modernized from a monolithic deployment to cloud-native services.

Problem

The organization wants faster response times, but claim descriptions contain personal and medical information. Incorrect prioritization could delay assistance. The existing system also has inconsistent audit records and no clear process for challenging automated decisions.

Analysis

The engineering team identifies several risks:

  • sensitive data may be transmitted to an external model provider;
  • historical routing decisions may reflect unequal access or inconsistent treatment;
  • generated classifications may be confidently wrong;
  • retries could duplicate claim events;
  • a cloud migration could increase data replication;
  • staff may over-trust an automated priority label.

Approach and solution

The team first defines the AI feature as decision support rather than autonomous adjudication. A Java gateway removes unnecessary identifiers, applies access controls, and sends only approved fields to a contracted provider. The provider agreement specifies retention and training terms. The gateway uses timeouts, bounded retries, request identifiers, and a circuit breaker.

The response is accepted only if it conforms to a strict schema. A human claims specialist reviews urgent and ambiguous cases. The system records the model version, input-data category, output, reviewer action, and timestamp, while excluding raw sensitive text from ordinary application logs.

The team evaluates performance on a held-out, time-separated dataset and examines error rates across relevant groups. It also conducts adversarial tests, including misleading text and prompt-injection content. A feature flag permits gradual rollout, and the previous rules-based process remains available for rollback.

For the cloud deployment, the service is packaged as a container, configuration is externalized, secrets are managed separately, and traces connect the API gateway, classification service, and case-management system. Database writes use idempotency keys so that a repeated request does not create duplicate assignments.

Outcome

The service reduces routine manual sorting while preserving human responsibility for consequential decisions. Monitoring reveals that performance degrades for short multilingual descriptions, so the organization limits automated use for those cases and funds improved data collection and translation support. The project is judged successful not because automation is maximized, but because service quality improves without concealing uncertainty or weakening rights.

Learning points

  1. AI capability should be constrained by the decision’s social impact.
  2. Privacy controls must be designed at the data boundary.
  3. Model output requires validation and operational safeguards.
  4. Cloud-native techniques support reliability but do not resolve ethical questions.
  5. Human oversight must be meaningful, adequately trained, and empowered to disagree.
  6. Monitoring must include social and quality outcomes, not only uptime and latency.

Challenges and Limitations

Contemporary Java technologies introduce genuine complexity. Multiple release trains and frameworks can make migration decisions difficult. Native compilation may expose hidden reflection assumptions. Reactive systems can be difficult to debug, especially when context is lost across asynchronous boundaries. Distributed systems create network failure, partial failure, consistency, and observability challenges.

AI integration adds uncertainty that ordinary software testing cannot fully eliminate. Model behavior may change between provider versions, and benchmark performance may not predict real-world outcomes. Privacy-preserving transformations can reduce utility, while excessive logging can create new exposure. Fairness evaluation may be limited by incomplete or sensitive demographic data. Sustainability measurement is often approximate.

These limitations do not justify avoiding modern technologies. They require proportional controls, explicit assumptions, evidence-based evaluation, and willingness to restrict or discontinue a feature when harms exceed benefits.

Professional Best Practices

  • Prefer supported Java releases and document upgrade policy.
  • Keep domain logic independent from deployment and AI-provider details.
  • Use strong typing, immutable values where practical, and explicit validation.
  • Define timeouts, retry semantics, idempotency, and failure behavior.
  • Measure JVM and native alternatives with representative workloads.
  • Select reactive programming or virtual threads based on evidence.
  • Treat AI output as untrusted input.
  • Never expose secrets or unapproved personal data to coding assistants or AI services.
  • Maintain dependency inventories, license records, and vulnerability-management processes.
  • Test security, accessibility, fairness, robustness, and performance.
  • Assign accountable owners and provide human review for high-impact decisions.
  • Monitor cost, resource use, environmental effects, incidents, and user complaints.
  • Design rollback, deletion, appeal, and shutdown procedures before deployment.

Chapter Summary

Contemporary Java extends traditional object-oriented programming into a platform for cloud-native, distributed, concurrent, and AI-enabled systems. Modern language features such as records, sealed types, pattern matching, and virtual threads improve expressiveness and concurrency, but they must be applied according to workload and design constraints. Cloud-native Java depends on statelessness, externalized configuration, containers, automation, observability, resilience, and security.

JVM execution and native compilation offer different trade-offs in startup, memory, dynamic behavior, optimization, and operational complexity. Reactive systems provide asynchronous streams and backpressure, while virtual threads can preserve imperative programming for many I/O-bound workloads. Neither approach is universally best.

AI-service integration requires validation, timeouts, privacy controls, security boundaries, monitoring, and human responsibility. AI coding assistants can increase productivity, but generated code must be reviewed, tested, secured, and assessed for licensing and confidentiality risks. Responsible digital transformation requires attention to privacy, intellectual property, bias, sustainability, explainability, accountability, and the rights of affected people.

The central professional lesson is that technical modernization and ethical governance are inseparable. A successful Java system is not merely fast or scalable; it is reliable, maintainable, secure, explainable enough for its context, and accountable to the people it affects.

Key Terms

Java release model: The schedule and support policy governing Java platform versions.

Record: A concise Java type intended primarily to model data values.

Sealed type: A class or interface that restricts permitted subclasses or implementations.

Virtual thread: A lightweight Java thread managed by the runtime rather than directly corresponding to an operating-system thread.

Cloud-native: An approach emphasizing automation, elasticity, observability, resilience, and independently deployable services.

Container: A packaged process environment containing an application and its required runtime files.

Observability: The ability to infer internal system behavior from outputs such as logs, metrics, and traces.

Circuit breaker: A resilience mechanism that temporarily stops calls to a failing dependency.

Ahead-of-time compilation: Compilation into native machine code before deployment.

Just-in-time compilation: Runtime compilation and optimization based on observed execution.

Reactive programming: Asynchronous processing of streams of data and events.

Backpressure: A mechanism by which consumers regulate the amount of data supplied by producers.

AI service: A software-accessible system that performs tasks such as generation, classification, extraction, or prediction.

Prompt injection: Malicious or unintended instructions that manipulate an AI system through supplied content.

Calibration: The correspondence between predicted confidence and observed frequencies of correctness.

Software bill of materials: An inventory of software components and dependencies in an artifact.

Fairness: The context-dependent evaluation of whether system outcomes or processes treat affected groups acceptably.

Accountability: Assignment of responsibility for system design, operation, impacts, and remediation.

Idempotency: A property in which repeating an operation has the same intended effect as performing it once.

Responsible digital transformation: Modernization that combines technical benefits with governance of social, legal, environmental, and ethical impacts.

Review Questions

Short Answer Questions

  1. What are two differences between a platform thread and a virtual thread?
  2. Why can a containerized application still have serious security weaknesses?
  3. Define backpressure and explain its purpose.
  4. Why should AI-service responses be validated before use by a Java application?
  5. What is the difference between privacy and security?

Long Answer Questions

  1. Compare JVM execution with native compilation, including benefits, limitations, and suitable workloads.
  2. Explain the major principles of cloud-native Java development and their relationship to reliability.
  3. Discuss how records, sealed types, and pattern matching can improve domain modeling.
  4. Explain the governance issues associated with AI coding assistants in a professional organization.
  5. Describe how privacy, intellectual property, bias, sustainability, and accountability should be addressed throughout an AI-enabled software lifecycle.

Analytical / Application Questions

  1. A Java service calls a payment provider and sometimes receives a timeout after the provider has accepted the payment. Design a retry and idempotency strategy, and justify each decision.
  2. An organization wants to deploy a native Java executable for a service that uses extensive reflection and dynamic proxies. Analyze the risks and propose an evidence-based decision process.
  3. Design a responsible architecture for a Java application that summarizes confidential customer documents using an AI service. Identify data controls, validation mechanisms, human oversight, monitoring requirements, and rollback conditions.

Multiple Choice Questions with Answers

Question 1

Which Java feature is primarily intended to model a concise data carrier with generated accessors, equality, hashing, and string representation?

A. Record

B. Module descriptor

C. Checked exception

D. Annotation processor

Correct Answer: A. Record

Question 2

Which statement best describes a virtual thread?

A. A thread that always runs faster than a platform thread

B. A lightweight thread managed by the Java runtime

C. A thread that can execute only CPU-intensive tasks

D. A replacement for database connection pooling

Correct Answer: B. A lightweight thread managed by the Java runtime

Question 3

What is the main purpose of backpressure in a reactive system?

A. To encrypt messages between services

B. To increase database storage capacity

C. To prevent a producer from overwhelming a consumer

D. To eliminate all network latency

Correct Answer: C. To prevent a producer from overwhelming a consumer

Question 4

Which situation is generally most attractive for ahead-of-time native compilation?

A. A short-lived function with strict startup requirements

B. A long-running service requiring extensive runtime dynamism

C. A program that must use unlimited reflection without configuration

D. A workload whose main requirement is maximum JIT warm-up optimization

Correct Answer: A. A short-lived function with strict startup requirements

Question 5

Why should retries for an external service be bounded and carefully designed?

A. Retries always reduce correctness

B. Retries can amplify load and duplicate non-idempotent operations

C. Retries prevent all service failures

D. Retries eliminate the need for timeouts

Correct Answer: B. Retries can amplify load and duplicate non-idempotent operations

Question 6

Which practice best protects confidential data when integrating an external AI service?

A. Send all available data so the model has maximum context

B. Place secrets in prompts for authentication

C. Send only necessary, authorized data through a controlled gateway

D. Store raw prompts permanently in ordinary application logs

Correct Answer: C. Send only necessary, authorized data through a controlled gateway

Question 7

What is the most appropriate attitude toward code generated by an AI coding assistant?

A. It is correct if it looks idiomatic

B. It is a proposal that requires review, testing, and security analysis

C. It should never be compiled because generated code is illegal

D. It replaces the need for requirements analysis

Correct Answer: B. It is a proposal that requires review, testing, and security analysis

Question 8

Which statement correctly distinguishes privacy from security?

A. Privacy concerns justified data use; security concerns protection from unauthorized access or alteration

B. Privacy and security are identical terms

C. Privacy applies only to financial data

D. Security concerns only user interface design

Correct Answer: A. Privacy concerns justified data use; security concerns protection from unauthorized access or alteration

Question 9

Why is a model confidence value not automatically a calibrated probability?

A. Confidence values can never be numerical

B. Calibration requires comparing predictions with observed outcomes for the intended task and population

C. Probabilities cannot be used in software

D. A model can be calibrated only by removing all test data

Correct Answer: B. Calibration requires comparing predictions with observed outcomes for the intended task and population

Question 10

Which governance practice most directly supports accountability for a high-impact AI feature?

A. Allowing the model provider to make all final decisions

B. Removing audit records to protect privacy

C. Assigning an owner, documenting decisions, and providing review or appeal mechanisms

D. Measuring only response latency

Correct Answer: C. Assigning an owner, documenting decisions, and providing review or appeal mechanisms

Object-Oriented Programming (Java)
Chapter 15 of 15