Mihai Surdeanu

(#10) Tricky Java Questions for Interviews

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.

  1. 100 milliseconds
  2. Runtime exception is thrown
  3. 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());
    }

}

Mihai

Pasionat de IT. Pasionat de viață. Pasionat de tot ceea ce înseamnă a face o viață mai bună, plină de înțelegere, ajutor reciproc și iubire de aproape.

Adaugă comentariu

Arhive

Arhiva personală