Loslegen
Javaneer

Interview-Vorbereitung

Häufige Java-Interviewfragen mit klaren Musterantworten - nach Thema gruppiert.

🧩Core Java

What's the difference between == and .equals()?+

== compares object identity (are they the same object in memory); .equals() compares value/equality. Use .equals() to compare object contents, especially Strings.

Why are Strings immutable in Java?+

Immutability makes Strings safe to share and cache (the String pool), thread-safe, and safe as HashMap keys, and prevents a class of bugs. Methods like toUpperCase() return new Strings.

What is the difference between an interface and an abstract class?+

An interface is a pure contract; a class can implement many. An abstract class can hold state, constructors, and shared code but a class extends only one. Prefer interfaces for capabilities, abstract classes to share code among related types.

🏗️OOP

What are the four pillars of OOP?+

Encapsulation (hide data behind methods), Inheritance (reuse/extend a parent), Polymorphism (one call, many behaviors via overriding), and Abstraction (show what, hide how).

If you override equals(), what else must you override?+

hashCode(). The contract requires equal objects to have equal hash codes; otherwise HashSet/HashMap misbehave. Records generate both correctly.

Composition vs. inheritance - which to prefer?+

Favor composition (has-a) over inheritance (is-a). Composition is more flexible, avoids brittle deep hierarchies, and sidesteps single-inheritance limits. Use inheritance only for genuine, stable is-a relationships.

🚀Collections & Generics

When would you use a List vs. Set vs. Map?+

List for ordered items with duplicates and index access (ArrayList); Set for unique items (HashSet); Map for key-value pairs with fast lookup (HashMap).

What is type erasure?+

Generics are a compile-time feature; type information is largely removed at runtime, so List<String> and List<Integer> are both just List at runtime. It kept generics backward-compatible.

Explain PECS.+

Producer Extends, Consumer Super. Use ? extends when reading values out of a structure, ? super when writing values in - maximizing flexibility while staying type-safe.

⚡Concurrency

What is a race condition?+

When correctness depends on unpredictable thread timing - e.g. two threads running count++ (read-modify-write) can lose updates. Fix with synchronized, atomics, or by avoiding shared mutable state.

What does volatile do?+

It guarantees visibility: reads/writes go to main memory so all threads see the latest value. It does NOT make compound operations atomic - use AtomicInteger or synchronized for that.

What are virtual threads?+

Ultra-lightweight threads (Java 21+) that let you run millions of concurrent tasks with simple blocking-style code, ideal for high-concurrency servers.

🎯Design & Best Practices

Explain the SOLID principles briefly.+

Single Responsibility (one reason to change), Open/Closed (extend, don't modify), Liskov Substitution (subtypes usable as parents), Interface Segregation (small focused interfaces), Dependency Inversion (depend on abstractions).

What is dependency injection and why use it?+

Supplying a class's dependencies from outside rather than creating them internally. It reduces coupling and makes code testable (you can inject mocks). Frameworks like Spring automate it.

How do you prevent SQL injection?+

Use PreparedStatement with parameter placeholders (?) instead of concatenating input into SQL, so data can never alter the query's structure.

🔩JVM & Memory

What lives on the stack vs. the heap?+

The stack holds method call frames and local variables (including references), cleared when a method returns. The heap holds all objects created with 'new' and is managed by the garbage collector.

How does garbage collection decide what to free?+

It reclaims objects that are no longer reachable from any live reference (roots like stack variables and static fields). Unreachable objects are collected automatically.

What is the JIT compiler?+

The Just-In-Time compiler translates frequently-executed ('hot') bytecode into optimized native machine code at runtime, so long-running Java programs speed up as they run.

Can you still leak memory in Java?+

Yes. If you keep references to objects you no longer need (e.g. adding to a static collection and never removing), the GC can't reclaim them - an accidental memory leak.

💼Spring & Persistence

What is Inversion of Control?+

The framework, not your code, drives the application flow and calls your code at the right time. The IoC container creates and wires your objects (beans) for you.

How does Spring Boot auto-configuration work?+

It inspects the dependencies on your classpath and configures sensible defaults (like an embedded web server or a datasource), so you write minimal configuration and override only what's specific.

What does @Transactional do?+

Spring wraps the annotated method in a proxy that starts a database transaction before it runs and commits on success or rolls back on a runtime exception.

How do you avoid the N+1 query problem in JPA?+

Fetch related data together with a JOIN FETCH in JPQL, an entity graph, or batch fetching - and enable SQL logging to see how many queries actually run.

🌿Spring Core & Boot

Constructor vs. field injection - which is better and why?+

Constructor injection. It makes dependencies explicit and final, guarantees a fully-initialized object, works without reflection (so it's test-friendly), and surfaces circular dependencies at startup. Field injection hides dependencies and can't be used in plain unit tests.

What's the difference between @Component, @Service, @Repository, and @Controller?+

All are stereotypes that register a bean via component scanning. @Service and @Controller are semantic markers; @Repository additionally translates persistence exceptions into Spring's DataAccessException hierarchy; @Controller/@RestController mark web handlers.

What is a Spring bean's default scope, and when would you change it?+

Singleton - one shared instance per container. Change to prototype for a new instance per lookup, or request/session for web-scoped state. Beware injecting a shorter-lived scope into a singleton (use a proxy or provider).

How does @SpringBootApplication bootstrap an app?+

It combines @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan - starting the container, scanning for beans, and auto-configuring infrastructure (embedded server, datasource) from the classpath.

How does auto-configuration decide what to configure?+

Conditional annotations (@ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty). Each auto-config backs off if you've defined your own bean or the required class isn't present - so you override only what you need.

How do you bind external configuration to a typed object?+

@ConfigurationProperties on a class or record binds a prefix (e.g. app.*) from application.yml/env vars, with validation and relaxed binding - cleaner and testable versus scattering @Value everywhere.

🌐Spring Web & Data

Why return DTOs from controllers instead of JPA entities?+

DTOs decouple the API contract from the persistence model, avoid leaking internal fields or lazy proxies (and LazyInitializationException), prevent accidental over-posting, and let the entity evolve without breaking clients.

How does Spring return standardized error responses?+

Throw domain exceptions and handle them in a @RestControllerAdvice that returns a ProblemDetail (RFC 9457) with status, title, and detail - one consistent, machine-readable error shape across the API.

What does @Transactional's readOnly=true buy you?+

It hints the provider to skip dirty checking/flushing and lets the DB/driver optimize (e.g. read replicas), improving read performance and signaling intent - the transaction still provides a consistent view.

Derived query methods vs. @Query - when each?+

Derived methods (findByEmail) are concise for simple lookups; @Query (JPQL or native) is better for joins, projections, JOIN FETCH, or anything the method-name DSL can't express clearly.

What is 'open session in view' and why disable it?+

It keeps the persistence context open for the whole request so lazy loads work in the view - but it hides N+1s and holds connections longer. Disabling it (open-in-view: false) forces you to fetch what you need in the service layer.

🔐Spring Security

How is a request authenticated and authorized in Spring Security?+

A filter chain intercepts the request, authenticates it (populating the SecurityContext), then authorization rules (URL matchers or method annotations) decide access - returning 401 if unauthenticated or 403 if authenticated but not permitted.

What's the difference between 401 and 403?+

401 Unauthorized means 'we don't know who you are' - missing or invalid credentials/token. 403 Forbidden means 'we know you, but you may not do this' - valid identity lacking the required role/authority.

Why store passwords with BCrypt rather than a plain hash?+

BCrypt is salted (defeats rainbow tables) and deliberately slow with a tunable work factor (defeats brute force). A fast hash like SHA-256 is unsuitable for passwords.

How does stateless JWT authentication work?+

On login the server issues a signed token carrying identity and roles; the client sends it on each request, and the server verifies the signature and trusts the claims without a session - enabling horizontal scaling. Guard the signing secret and set expiries.

How do you enforce role-based access at the method level?+

Enable method security and annotate methods with @PreAuthorize("hasRole('ADMIN')") (or @Secured) - the check runs via a proxy before the method executes, complementing URL-level rules.

🧪Spring Testing & Microservices

Describe the Spring test pyramid.+

Many fast unit tests (plain JUnit + Mockito, no Spring); fewer slice tests (@WebMvcTest, @DataJpaTest) that load one layer; and a few @SpringBootTest integration tests that wire the whole app - cheap feedback at the base, broad confidence at the top.

@WebMvcTest vs. @DataJpaTest vs. @SpringBootTest?+

@WebMvcTest loads just the web layer with the service mocked; @DataJpaTest loads JPA/repositories against an in-memory DB; @SpringBootTest starts the full context for end-to-end tests. Pick the narrowest slice that honestly covers the concern.

Why use Testcontainers instead of an in-memory database?+

Testcontainers runs the real database (e.g. PostgreSQL) in a container, catching dialect, constraint, and migration issues that H2 would mask - higher fidelity for integration tests, at the cost of needing Docker.

When should you split a monolith into microservices?+

When concrete pressures appear - independent scaling, independent deployment/team ownership, or fault isolation - not by default. Start with a well-structured (modular) monolith and split along clean boundaries only when the added distributed-systems complexity is justified.

What problems do a service registry and circuit breaker solve?+

A registry (e.g. Eureka) lets services find each other by name instead of hard-coded hosts, enabling scaling and self-healing. A circuit breaker (Resilience4j) fails fast with a fallback when a dependency is down, stopping a cascading outage.

🏢Jakarta EE & Enterprise Java

What is Jakarta EE, and how does it relate to Java EE and Spring?+

Jakarta EE is the successor to Java EE, moved from Oracle to the Eclipse Foundation - a set of enterprise specifications (JPA, Servlet, CDI, Bean Validation, JAX-RS...). Spring implements or integrates many of these specs rather than competing with them; Spring Boot 3+ runs on the Jakarta namespace.

Why did package names change from javax.* to jakarta.*?+

When Java EE became Jakarta EE, Oracle's trademark on 'javax' meant the specs had to be renamed. So javax.persistence became jakarta.persistence, etc. This is why upgrading to Spring Boot 3 (or a modern app server) requires a javax→jakarta migration of imports.

What is CDI, and how does it compare to Spring's DI?+

CDI (Contexts and Dependency Injection) is the Jakarta EE standard for dependency injection and contextual lifecycle management, using @Inject, @Named, and scopes like @RequestScoped. It's conceptually similar to Spring's container; Spring predates it and has a broader ecosystem, which is why Spring dominates in practice.

What is JAX-RS?+

The Jakarta RESTful Web Services spec for building REST APIs with annotations like @Path, @GET, and @Produces. Implementations include Jersey and RESTEasy. It's the standards-based counterpart to Spring MVC's @RestController.

What is an application server, and do you still need one?+

A full Jakarta EE server (WildFly, Open Liberty, Payara, WebLogic) provides the container and implementations of the EE specs; you deploy a WAR/EAR into it. Modern practice favors embedding the server (Spring Boot's embedded Tomcat) and shipping an executable jar, so standalone app servers are now mostly a legacy/enterprise concern.

What is MicroProfile?+

A set of specifications that extend Jakarta EE for cloud-native microservices - config, health, metrics, fault tolerance, JWT - implemented by runtimes like Quarkus, Open Liberty, and Helidon. It's the forward-looking, Spring-Boot-like face of the Jakarta ecosystem.