






























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!































Introduction
1 Core Java & OOPs
1 public class StringExample { 2 public static void main(String[] args) { 3 String str = ”Hello”; 4 str += ” World”; // New object 5 System.out.println(str); // Hello World 6 StringBuilder sb = new StringBuilder(”Hello”); 7 sb.append(” World”); 8 System.out.println(sb); // Hello World 9 StringBuffer sbf = new StringBuffer(”Hello”); 10 sbf.append(” World”); 11 System.out.println(sbf); // Hello World 12 } 13 }
1 public class EqualsExample { 2 public static void main(String[] args) { 3 String s1 = new String(”Hello”); 4 String s2 = new String(”Hello”); 5 System.out.println(s1 == s2); // false 6 System.out.println(s1.equals(s2)); // true 7 String s3 = ”Hello”; 8 String s4 = ”Hello”; 9 System.out.println(s3 == s4); // true 10 } 11 }
1 class Animal { 2 void sound() { System.out.println(”Animal sound”); } 3 } 4 class Dog extends Animal { 5 void sound() { System.out.println(”Dog barks”); } // Override 6 void sound(String type) { System.out.println(”Dog ” + type); } // Overload 7 } 8 public class PolymorphismExample { 9 public static void main(String[] args) { 10 Dog dog = new Dog(); 11 dog.sound(); // Dog barks 12 dog.sound(”growls”); // Dog growls 13 } 14 }
1 public class Singleton { 2 private static Singleton instance; 3 private Singleton() {} 4 public static synchronized Singleton getInstance() { 5 if (instance == null) instance = new Singleton(); 6 return instance; 7 } 8 public static void main(String[] args) { 9 Singleton s1 = Singleton.getInstance(); 10 Singleton s2 = Singleton.getInstance(); 11 System.out.println(s1 == s2); // true 12 }
1 import java.util.HashMap; 2 class Employee { 3 int id; String name; 4 Employee(int id, String name) { this.id = id; this.name = name; } 5 @Override public int hashCode() { return id * 31 + name.hashCode(); } 6 @Override public boolean equals(Object obj) { 7 if (!(obj instanceof Employee)) return false; 8 Employee other = (Employee) obj; 9 return id == other.id && name.equals(other.name); 10 } 11 } 12 public class HashMapEmployee { 13 public static void main(String[] args) { 14 HashMap<Employee, String> map = new HashMap<>(); 15 Employee e1 = new Employee(1, ”Alice”); 16 map.put(e1, ”Developer”); 17 System.out.println(map.get(new Employee(1, ”Alice”))); // Developer 18 } 19 }
1 public final class ImmutableClass { 2 private final int value; 3 public ImmutableClass(int value) { this.value = value; } 4 public int getValue() { return value; } 5 public static void main(String[] args) { 6 ImmutableClass obj = new ImmutableClass(42); 7 System.out.println(obj.getValue()); // 42 8 } 9 }
1 public class VolatileSynchronized { 2 private volatile boolean running = true; 3 public synchronized void update() { running = false; } 4 public static void main(String[] args) throws InterruptedException { 5 VolatileSynchronized vs = new VolatileSynchronized(); 6 new Thread(() -> { while (vs.running) {} System.out.println(”Stopped”); }).start(); 7 Thread.sleep(1000); 8 vs.update(); 9 } 10 }
1 public class ObjectCreation { 2 public static void main(String[] args) throws Exception { 3 ObjectCreation obj1 = new ObjectCreation(); 4 ObjectCreation obj2 = (ObjectCreation) Class.forName(”ObjectCreation”). newInstance(); 5 } 6 }
1 import org.springframework.http.; 2 import org.springframework.web.bind.annotation.; 3 @RestController 4 public class ResponseEntityExample { 5 @GetMapping(”/user”) 6 public ResponseEntity
1 @FunctionalInterface 2 interface MyFunction { void apply(String s); } 3 public class FunctionalInterfaceExample { 4 public static void main(String[] args) { 5 MyFunction func = s -> System.out.println(s); 6 func.apply(”Hello”); // Hello 7 } 8 }
1 import java.util.function.Consumer; 2 public class FunctionalInterfaceWork { 3 public static void main(String[] args) { 4 Consumer
1 import org.springframework.stereotype.Component; 2 import org.springframework.beans.factory.annotation.Autowired; 3 @Component 4 class Service { public void serve() { System.out.println(”Serving”); } } 5 @Component
6 public String getView() { return ”view”; } 7 } 8 @RestController 9 public class MyRestController { 10 @GetMapping(”/api”) 11 public String getData() { return ”Data”; } 12 }
1 import org.springframework.boot.; 2 import org.springframework.boot.autoconfigure.; 3 @SpringBootApplication 4 public class Application { 5 public static void main(String[] args) { 6 SpringApplication.run(Application.class, args); 7 } 8 }
1 import org.springframework.stereotype.*; 2 @Service 3 public class MyService { 4 public void serve() { System.out.println(”Service”); } 5 }
1 import org.springframework.web.bind.annotation.*; 2 @RestController 3 public class PathVariableExample { 4 @GetMapping(”/user/{id}”) 5 public String getUser(@PathVariable int id) { 6 return ”User ID: ” + id; 7 } 8 }
1 // Run Application.java to start Tomcat
1 // Access http://localhost:
2 Java 8 Features
1 import java.util.*; 2 public class Java8Features { 3 public static void main(String[] args) { 4 List
1 import java.util.*; 2 public class LambdaExample { 3 public static void main(String[] args) { 4 List
1 import java.util.*; 2 public class LambdaCode { 3 public static void main(String[] args) { 4 List
1 import java.util.; 2 import java.util.stream.; 3 public class StreamExample { 4 public static void main(String[] args) { 5 List
1 import java.util.; 2 import java.util.stream.; 3 public class GroupingByExample { 4 public static void main(String[] args) { 5 List
1 import java.util.Optional; 2 class Employee { 3 String name; 4 Employee(String name) { this.name = name; } 5 } 6 public class OptionalExample { 7 public static void main(String[] args) { 8 Optional
1 import java.util.; 2 import java.util.stream.; 3 public class RemoveDuplicates { 4 public static void main(String[] args) { 5 List
1 import java.util.; 2 import java.util.stream.; 3 class Employee { 4 double salary; 5 Employee(double salary) { this.salary = salary; } 6 double getSalary() { return salary; } 7 } 8 public class ThirdHighestSalary { 9 public static void main(String[] args) { 10 List
11 new Employee(50000), new Employee(70000), new Employee(60000) 12 ); 13 double thirdHighest = employees.stream() 14 .map(Employee::getSalary) 15 .distinct() 16 .sorted(Comparator.reverseOrder()) 17 .skip(2) 18 .findFirst() 19 .orElse(0.0); 20 System.out.println(thirdHighest); // 0.0 (if <3 salaries) 21 } 22 }
3 Spring Boot & Microservices
1 # application-dev.properties 2 server.port=
1 import org.springframework.context.annotation.*; 2 @Profile(”dev”) 3 @Component 4 public class DevConfig {}
1 # application.properties 2 spring.profiles.active=dev
1 import org.springframework.http.; 2 import org.springframework.web.bind.annotation.; 3 @RestController 4 public class ExceptionController { 5 @ExceptionHandler(NullPointerException.class) 6 public ResponseEntity
1 import org.springframework.kafka.annotation.*; 2 @Service 3 public class KafkaConsumer { 4 @KafkaListener(topics = ”myTopic”) 5 public void consume(String message) { 6 System.out.println(message); 7 } 8 }
1 import org.springframework.kafka.core.; 2 import org.springframework.stereotype.; 3 @Service 4 public class KafkaProducer { 5 @Autowired 6 private KafkaTemplate<String, String> kafkaTemplate; 7 public void sendMessage(String msg) { 8 kafkaTemplate.send(”myTopic”, msg); 9 } 10 }
1 import org.springframework.context.annotation.; 2 import org.springframework.security.config.annotation.web.builders.; 3 @Configuration 4 @EnableWebSecurity 5 public class SecurityConfig { 6 @Bean 7 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 8 http.authorizeRequests().anyRequest().authenticated().and().httpBasic() ; 9 return http.build(); 10 } 11 }
1 import io.jsonwebtoken.*; 2 public class JwtExample { 3 public String generateToken(String username) { 4 return Jwts.builder() 5 .setSubject(username) 6 .signWith(SignatureAlgorithm.HS512, ”secret”) 7 .compact(); 8 }
1 import org.springframework.http.; 2 import org.springframework.web.bind.annotation.; 3 @RestController 4 @RequestMapping(”/api/v1”) 5 public class ApiController { 6 @GetMapping(”/users”) 7 public ResponseEntity<List
1 import org.springframework.web.bind.annotation.*; 2 @RestController 3 public class UserController { 4 @PostMapping(”/users”) public String createUser() { return ”Created”; } 5 @PutMapping(”/users/{id}”) public String updateUser(@PathVariable int id) { return ”Updated”; } 6 @PatchMapping(”/users/{id}”) public String patchUser(@PathVariable int id ) { return ”Patched”; } 7 }
1 import org.springframework.web.bind.annotation.*; 2 @RestController 3 @RequestMapping(”/api/v1”) 4 public class VersionedController { 5 @GetMapping(”/users”) 6 public String getUsers() { return ”Version 1”; } 7 }
1 import org.springframework.web.bind.annotation.*; 2 @RestController 3 public class IdempotentController { 4 @PutMapping(”/users/{id}”) 5 public ResponseEntity
1 import org.springframework.http.; 2 import org.springframework.web.bind.annotation.; 3 @ControllerAdvice 4 public class GlobalExceptionHandler { 5 @ExceptionHandler(Exception.class) 6 public ResponseEntity
1 // See above
1 import org.springframework.context.annotation.*; 2 @ComponentScan(basePackages = ”com.example”, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MyClass.class)) 3 @Configuration 4 public class AppConfig {}
1 import org.springframework.stereotype.*; 2 @Component 3 public class MyComponent {}
1 import org.springframework.cache.annotation.*; 2 @Service 3 public class OptimizedService { 4 @Cacheable(”data”) 5 public String getData() { return ”Data”; } 6 }
1 import org.springframework.data.jpa.repository.*; 2 public interface UserRepository extends JpaRepository<User, Long> { 3 @Query(”SELECT u FROM User u WHERE u.active = true”) 4 List
1 # application.properties 2 management.endpoints.web.exposure.include=*
1 // See Circuit Breaker (Question 6)
1 # application.properties 2 spring.config.import=configserver:http://config-server
1 import org.springframework.cloud.netflix.eureka.*; 2 @SpringBootApplication 3 @EnableEurekaClient 4 public class Application {}
1 import feign.*; 2 @FeignClient(name = ”user-service”) 3 interface UserClient { 4 @GetMapping(”/users”) 5 List
1 import io.github.resilience4j.circuitbreaker.annotation.; 2 import io.github.resilience4j.retry.annotation.; 3 @Service 4 public class ResilientService { 5 @CircuitBreaker(name = ”myService”)