Java Developer questions with answers - FAME-DEV/Java-Test GitHub Wiki
I'll provide both theoretical explanations and code examples for key concepts.
- Core Java Concepts String and String Pool Theory:
String is an immutable class in Java, meaning once created, its state cannot be changed String Pool is a special memory area in Java's heap memory When we create a string using literal notation, JVM first checks if the string exists in the pool. If it exists, the same reference is returned, otherwise a new string is created
Example: javaCopyString s1 = "hello"; // Creates string in pool String s2 = "hello"; // Reuses from pool String s3 = new String("hello"); // Creates new object in heap
System.out.println(s1 == s2); // true System.out.println(s1 == s3); // false System.out.println(s1.equals(s3)); // true Object-Oriented Programming (OOPs) Theory:
Encapsulation:
Bundling of data and methods that operate on that data within a single unit (class) Hiding internal details and providing an interface Achieved through access modifiers (private, protected, public)
Inheritance:
Mechanism where one class acquires properties and behaviors of another class Supports code reusability and establishes relationships between classes Java supports single inheritance through classes but multiple inheritance through interfaces
Polymorphism:
Ability of an object to take many forms Static Polymorphism (compile-time): Method overloading Dynamic Polymorphism (runtime): Method overriding
Example: javaCopy// Encapsulation public class BankAccount { private double balance; // data hiding
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
// Inheritance & Polymorphism abstract class Animal { abstract void makeSound(); }
class Dog extends Animal { @Override void makeSound() { System.out.println("Woof!"); } } Exception Handling Theory:
Mechanism to handle runtime errors Hierarchy: Throwable (Error, Exception) Checked Exceptions: Compile-time exceptions that must be handled Unchecked Exceptions: Runtime exceptions Custom exceptions can be created for business logic
Best Practices:
Always catch specific exceptions before general ones Close resources in finally block or use try-with-resources Don't catch exceptions you can't handle Document exceptions using @throws in JavaDoc
Example: javaCopypublic class ExceptionExample { public void readFile() throws IOException { try (FileReader fr = new FileReader("file.txt")) { // file processing } catch (FileNotFoundException e) { Logger.error("File not found", e); throw new BusinessException("File processing failed"); } catch (IOException e) { Logger.error("IO error", e); throw e; } } } Multithreading Theory:
Thread Lifecycle:
New Runnable Running Blocked/Waiting Terminated
Thread Safety Issues:
Race conditions Deadlock Starvation Livelock
Synchronization Mechanisms:
synchronized keyword volatile keyword Lock interface Atomic classes ThreadLocal
Example: javaCopypublic class ThreadSafeCounter { private volatile int count = 0; private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
// Using CompletableFuture (Modern approach) CompletableFuture future = CompletableFuture .supplyAsync(() -> "Hello") .thenApply(s -> s + " World") .thenAccept(System.out::println); Java Collection Framework Theory:
Core Interfaces:
Collection: Root interface List: Ordered collection Set: Unique elements Queue: FIFO structure Map: Key-value pairs
Common Implementations:
ArrayList: Dynamic array LinkedList: Doubly-linked list HashSet: Unique elements with O(1) lookup TreeSet: Sorted unique elements HashMap: Key-value with O(1) access TreeMap: Sorted key-value pairs
Selection Criteria:
Ordered vs Unordered Sorted vs Unsorted Random Access vs Sequential Access Thread Safety Requirements
Example: javaCopy// Using different collections List list = new ArrayList<>(); // Dynamic array Set set = new HashSet<>(); // Unique elements Map<String, Integer> map = new HashMap<>(); // Key-value pairs
// Thread-safe collections List syncList = Collections.synchronizedList(new ArrayList<>()); Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
// Using Stream API with collections list.stream() .filter(s -> s.length() > 5) .map(String::toUpperCase) .collect(Collectors.toList());
Java 8+ Features Lambda Expressions and Functional Interfaces Theory:
Lambda expressions are anonymous functions Enable functional programming in Java Functional interfaces have exactly one abstract method Common functional interfaces: Predicate, Function, Consumer, Supplier
Example: javaCopy// Functional interface @FunctionalInterface interface MathOperation { int operate(int a, int b); }
// Lambda usage MathOperation addition = (a, b) -> a + b; MathOperation multiplication = (a, b) -> a * b;
// Common functional interfaces Predicate isEven = num -> num % 2 == 0; Function<String, Integer> stringLength = str -> str.length(); Consumer printer = System.out::println; Supplier randomNumber = Math::random; Stream API Theory:
Enables functional-style operations on collections Two types: Intermediate operations (filter, map) and Terminal operations (collect, reduce) Supports parallel processing Lazy evaluation: operations are only performed when terminal operation is called
Example: javaCopyList employees = getEmployees();
// Stream operations List highPaidEmployeeNames = employees.stream() .filter(e -> e.getSalary() > 50000) // intermediate .map(Employee::getName) // intermediate .sorted() // intermediate .collect(Collectors.toList()); // terminal
// Parallel stream double averageSalary = employees.parallelStream() .mapToDouble(Employee::getSalary) .average() .orElse(0.0);
// Group by department Map<String, List> byDepartment = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment)); Optional Theory:
Container object to handle null values Reduces NullPointerException Promotes functional programming style Methods: map, flatMap, filter, orElse, orElseGet, orElseThrow
Example: javaCopypublic class OptionalExample { public Optional findUserById(String id) { User user = database.query(id); return Optional.ofNullable(user); }
public String getUserEmail(String id) {
return findUserById(id)
.map(User::getEmail)
.orElse("[email protected]");
}
public String getDisplayName(String id) {
return findUserById(id)
.filter(user -> user.getName() != null)
.map(User::getName)
.orElseGet(() -> "Anonymous" + id);
}
} Spring Framework Dependency Injection & IoC Theory:
IoC (Inversion of Control): Framework controls object creation and lifecycle DI (Dependency Injection): Dependencies are injected rather than created Types of injection: Constructor, Setter, Field Benefits: Loose coupling, easier testing, modular design
Example: javaCopy@Service public class UserService { private final UserRepository userRepository; private final EmailService emailService;
@Autowired // Constructor injection
public UserService(UserRepository userRepository,
EmailService emailService) {
this.userRepository = userRepository;
this.emailService = emailService;
}
} Spring Bean Lifecycle Theory:
Instantiation Populate Properties BeanNameAware BeanFactoryAware Pre-initialization ([@PostConstruct]) Initialize Post-initialization Pre-destroy ([@PreDestroy]) Destroy
Example: javaCopy@Component public class MyBean implements InitializingBean, DisposableBean { @PostConstruct public void init() { // initialization code }
@Override
public void afterPropertiesSet() {
// after properties are set
}
@PreDestroy
public void cleanup() {
// cleanup code
}
@Override
public void destroy() {
// destroy logic
}
} Spring MVC Theory:
Model-View-Controller pattern implementation DispatcherServlet as front controller Handles web requests through @Controller classes View resolution and rendering Support for REST APIs with @RestController
Example: javaCopy@RestController @RequestMapping("/api/users") public class UserController { private final UserService userService;
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
return userService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO user) {
User created = userService.create(user);
return ResponseEntity
.created(URI.create("/api/users/" + created.getId()))
.body(created);
}
@ExceptionHandler(ValidationException.class)
public ResponseEntity<String> handleValidationError(ValidationException e) {
return ResponseEntity
.badRequest()
.body(e.getMessage());
}
} Database Concepts (JPA/Hibernate) JPA Entity Relationships Theory:
@OneToOne @OneToMany/@ManyToOne @ManyToMany Cascade types Fetch types (LAZY/EAGER)
Example: javaCopy@Entity public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
private List<Employee> employees;
}
@Entity public class Employee { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "dept_id") private Department department;
@ManyToMany
@JoinTable(
name = "employee_project",
joinColumns = @JoinColumn(name = "employee_id"),
inverseJoinColumns = @JoinColumn(name = "project_id")
)
private Set<Project> projects;
} Common SQL Queries Theory:
JOIN types (INNER, LEFT, RIGHT, FULL) Aggregation functions Subqueries Window functions
Example: sqlCopy-- Find nth highest salary SELECT salary FROM ( SELECT DISTINCT salary FROM employees ORDER BY salary DESC ) AS temp LIMIT 1 OFFSET n-1;
-- Department wise average salary SELECT d.name, AVG(e.salary) as avg_salary FROM department d JOIN employee e ON d.id = e.dept_id GROUP BY d.name HAVING AVG(e.salary) > 50000;
-- Using window functions SELECT e.name, e.salary, d.name as dept_name, RANK() OVER (PARTITION BY e.dept_id ORDER BY e.salary DESC) as salary_rank FROM employee e JOIN department d ON e.dept_id = d.id; Would you like me to delve deeper into any particular topic or provide more specific examples?RetryClaude does not have the ability to run the code it generates yet.Ddelve deeper into springboot, with all important springboot and spring cloud topic should coverEditI'll provide a comprehensive breakdown of Spring Boot and Spring Cloud concepts with practical examples. Spring Boot Deep Dive
- Spring Boot Core Concepts Auto-Configuration javaCopy@SpringBootApplication // Combines @Configuration, @EnableAutoConfiguration, @ComponentScan public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
// Custom Auto-Configuration @Configuration @ConditionalOnClass(DataSource.class) public class DatabaseAutoConfiguration { @Bean @ConditionalOnMissingBean public DataSource dataSource() { // configuration logic } } Properties Configuration yamlCopy# application.yml spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: root jpa: hibernate: ddl-auto: update profiles: active: dev
app: feature: enabled: true security: jwt: secret: mysecret expiration: 86400 javaCopy@Configuration @ConfigurationProperties(prefix = "app.feature") public class FeatureProperties { private boolean enabled; // getters and setters } 2. Spring Boot Security Basic Security Configuration javaCopy@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationFilter jwtAuthFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.antMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(jwtAuthFilter,
UsernamePasswordAuthenticationFilter.class);
}
} JWT Implementation javaCopy@Component public class JwtTokenProvider { @Value("${app.security.jwt.secret}") private String jwtSecret;
public String generateToken(UserDetails userDetails) {
return Jwts.builder()
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 864000000))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
} 3. Spring Boot Testing javaCopy@SpringBootTest class UserServiceIntegrationTest { @Autowired private UserService userService;
@MockBean
private UserRepository userRepository;
@Test
void whenValidUser_thenUserShouldBeSaved() {
User user = new User("[email protected]");
when(userRepository.save(any(User.class))).thenReturn(user);
User saved = userService.createUser(user);
assertThat(saved.getEmail()).isEqualTo("[email protected]");
}
} Spring Cloud Components
- Service Discovery (Eureka) javaCopy// Service Registration @SpringBootApplication @EnableEurekaClient public class ServiceApplication { public static void main(String[] args) { SpringApplication.run(ServiceApplication.class, args); } }
// Eureka Server @SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } } 2. Circuit Breaker (Resilience4j) javaCopy@RestController public class ServiceController { @CircuitBreaker(name = "myService", fallbackMethod = "fallback") @GetMapping("/api/data") public ResponseEntity getData() { // service call that might fail }
public ResponseEntity<String> fallback(Exception e) {
return ResponseEntity.ok("Fallback response");
}
}
// Configuration resilience4j.circuitbreaker: instances: myService: slidingWindowSize: 10 failureRateThreshold: 50 waitDurationInOpenState: 5000 3. API Gateway (Spring Cloud Gateway) javaCopy@Configuration public class GatewayConfig { @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("user_service", r -> r .path("/users/") .filters(f -> f .rewritePath("/users/(?.*)", "/${segment}") .addRequestHeader("X-Response-Time", LocalDateTime.now().toString())) .uri("lb://USER-SERVICE")) .route("order_service", r -> r .path("/orders/") .uri("lb://ORDER-SERVICE")) .build(); } } 4. Config Server javaCopy// Config Server @SpringBootApplication @EnableConfigServer public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
// Client Configuration spring: cloud: config: uri: http://localhost:8888 fail-fast: true 5. Distributed Tracing (Sleuth & Zipkin) javaCopy@Service public class OrderService { private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private RestTemplate restTemplate;
public Order processOrder(Long orderId) {
log.info("Processing order: {}", orderId);
// The trace ID will be automatically propagated
return restTemplate.getForObject(
"http://inventory-service/check/" + orderId,
Order.class);
}
} 6. Message Broker Integration (Kafka) javaCopy@Configuration public class KafkaConfig { @Bean public ProducerFactory<String, String> producerFactory() { Map<String, Object> config = new HashMap<>(); config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); return new DefaultKafkaProducerFactory<>(config); } }
@Service public class MessageService { @Autowired private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String msg) {
kafkaTemplate.send("topic_name", msg);
}
@KafkaListener(topics = "topic_name", groupId = "group_id")
public void consume(String message) {
// process message
}
} 7. Spring Cloud Stream javaCopy@EnableBinding(Processor.class) public class StreamsConfig { @StreamListener(Processor.INPUT) @SendTo(Processor.OUTPUT) public String processMessage(String message) { return message.toUpperCase(); } }
spring: cloud: stream: bindings: input: destination: input-topic output: destination: output-topic