Hero Image
- Mihai Surdeanu

(#10) Tricky Java Questions for Interviews

Motto: Bring Spring to next level...

Q1: What’s printed to console when main method is debugged?

public class Main {

    public static void main(String[] args) {
        System.out.println(myFormat("%d milliseconds", 100));
    }

    private static String myFormat(String message, Object... arguments) {
        return String.format(message.toUpperCase(), arguments);
    }

}

Only one answer is correct:

  • 100 milliseconds
  • Runtime exception is thrown
  • A compilation error is signaled

Q2: Lombok + Spring context. A Spring context is fully initialized in your application. Inside it, there is one service – MyService, which depends on two other services injected by Spring. Looking at the implementation, are we sure both dependencies are injected properly? What do you think?

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class MyService {

    private final MyFirstService myFirstService;

    private MySecondService mySecondService;

}

Q3: Spring context. We are dealing with a small configuration class which defines two beans. One for providing a generic blue color and a second one for providing a class instance, based on that color. The question is: how many instances of Color class will be created behind the scene?

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {

    @Bean
    public Color provideColor() {
        return new Color("blue");
    }

    @Bean
    public Car provideCar() {
        return new Car(provideColor());
    }

}

Other Related Posts:

Microbenchmarking with Java

Microbenchmarking with Java

Hello guys,

Today, we are going to continue the series of articles about Java ecosystem. More specific, today, we are going to talk about JMH (Java Microbenchmark Harness).

2nd Apr 2022 - Mihai Surdeanu