<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Syed Nazeer on Medium]]></title>
        <description><![CDATA[Stories by Syed Nazeer on Medium]]></description>
        <link>https://medium.com/@nazeersd.java?source=rss-9b1e6e0255e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ckXAhvjVnc8L8Hh1g3f6kA.png</url>
            <title>Stories by Syed Nazeer on Medium</title>
            <link>https://medium.com/@nazeersd.java?source=rss-9b1e6e0255e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 05:51:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nazeersd.java/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JWT in Production]]></title>
            <link>https://medium.com/@nazeersd.java/jwt-in-production-6bd104cb7b76?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bd104cb7b76</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[jwt-token]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 21:49:34 GMT</pubDate>
            <atom:updated>2026-06-25T21:49:34.201Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve created a POC in production style and summarized the whole project, pointed out the key files, behaviour, and where to look next.</p><h3><strong>Checklist</strong></h3><ol><li>Purpose &amp; high-level behavior</li><li>Main packages and responsibilities</li><li>Authentication/refresh/logout flows and security details</li><li>Important files and where to find them</li><li>Build/run instructions and tests</li></ol><h3><strong>Project summary</strong></h3><h4><strong>1. Purpose:</strong></h4><ol><li>User registration and login (returns access + refresh tokens)</li><li>Refresh-token rotation with reuse detection</li><li>Logout that deletes refresh tokens and blacklists access tokens</li><li>Scheduled cleanup of expired blacklisted tokens</li></ol><h4><strong>2. High-level architecture / main packages:</strong></h4><p><strong>com.wipro.controller — REST endpoints</strong></p><p><em>AuthController</em>( for /register, /login, /refresh, /logout)</p><p><strong>com.wipro.service — business logic:</strong></p><p><em>AuthService</em> (register/login/logout and blacklist logic)</p><p><em>RefreshTokenService</em> (create/rotate/validate/revoke refresh tokens)</p><p><em>BlacklistedTokenService</em> (persist &amp; clean blacklisted access tokens)</p><p><em>SecurityIncidentService</em> (revoking all refresh tokens for reuse incidents)</p><p><strong>com.wipro.repository — Spring Data JPA repositories:</strong></p><p><em>UserRepository, RefreshTokenRepository, BlacklistedTokenRepository, RoleRepository</em></p><p><strong>com.wipro.entity — JPA entities:</strong></p><p><em>User</em>, <em>Role</em>, <em>RefreshToken</em>, <em>BlacklistedToken</em></p><p><strong>com.wipro.security — JWT creation/validation and Spring Security integration </strong>(JWT filter, entry point)</p><p><strong>com.wipro.config — </strong><em>SecurityConfig</em><strong> </strong>(stateless security, JWT filter, password encoder)</p><p><strong>com.wipro.dto — request/response models</strong> (e.g., <em>LoginRequest</em>, <em>RegisterRequest</em>, <em>RefreshTokenRequest</em>, <em>AuthResponse</em>, <em>ApiResponse</em>)</p><p><strong>com.wipro.exception — custom exceptions </strong>(refresh reuse, expired tokens, user/username/email errors)</p><p><strong>com.wipro.scheduler — scheduled task(s) used for cleanup </strong>(scheduling is enabled at app bootstrap)</p><h4><strong>3. Core flows &amp; noteworthy behaviours:</strong></h4><ul><li><strong>Login/register</strong></li></ul><p><em>AuthController</em> calls the service layer to register or authenticate users and return <em>AuthResponse</em> (access + refresh tokens).</p><ul><li><strong>Refresh token rotation &amp; reuse detection</strong></li></ul><p><em>RefreshTokenService</em> issues new refresh tokens on use (rotation) and marks used refresh tokens revoked.</p><p>If a revoked refresh token is later presented (reused), a reuse-detection path revokes all the user’s refresh tokens (via <em>SecurityIncidentService</em>) and throws a <em>RefreshTokenReuseDetectedException</em>.</p><ul><li><strong>Logout &amp; access token blacklisting</strong></li></ul><p><em>AuthService.logout()</em> removes the user’s refresh tokens and stores the provided access token in <em>BlacklistedToken</em> with its expiry. Blacklisted tokens are checked by the JWT filter to deny use until expiry.</p><p>If an expired access token is supplied at logout, refresh tokens are still removed; there’s no need to store an already-expired access token.</p><ul><li><strong>Blacklist cleanup</strong></li></ul><p>A scheduled cleanup runs periodically to delete expired <em>BlacklistedToken</em> rows from the DB so the table doesn’t grow indefinitely.</p><ul><li><strong>Transactions &amp; revocations</strong></li></ul><p>Bulk revocation methods exist on the <em>RefreshTokenRepository</em> (e.g., <em>revokeAllByUserId</em>), and some revocations run in a separate transaction to guarantee containment of incidents.</p><h4><strong>4. Important files (paths you can open):</strong></h4><p><strong>Application bootstrap</strong></p><p><em>src/main/java/com/wipro/JwtAuthServiceApplication.java</em> (includes <a href="http://twitter.com/EnableScheduling">@EnableScheduling</a>)</p><p><strong>Security/config</strong></p><p><em>src/main/java/com/wipro/config/SecurityConfig.java</em></p><p><em>src/main/java/com/wipro/security/* </em>(JWT generation/validation, <em>JwtAuthenticationFilter, JwtAuthenticationEntryPoint</em>)</p><p><strong>Controller</strong></p><p><em>src/main/java/com/wipro/controller/AuthController.java</em></p><p><strong>Core services</strong></p><p><em>src/main/java/com/wipro/service/AuthService.java</em></p><p><em>src/main/java/com/wipro/service/RefreshTokenService.java</em></p><p><em>src/main/java/com/wipro/service/BlacklistedTokenService.java</em></p><p><em>src/main/java/com/wipro/service/SecurityIncidentService.java</em></p><p><strong>DTOs</strong></p><p><em>src/main/java/com/wipro/dto/*</em> (<em>LoginRequest, RegisterRequest, RefreshTokenRequest, AuthResponse,</em> etc.)</p><p><strong>Entities</strong></p><p><em>src/main/java/com/wipro/entity/User.java</em></p><p><em>src/main/java/com/wipro/entity/RefreshToken.java</em></p><p><em>src/main/java/com/wipro/entity/BlacklistedToken.java</em></p><p><em>src/main/java/com/wipro/entity/Role.java</em></p><p><strong>Repositories</strong></p><p><em>src/main/java/com/wipro/repository/UserRepository.java</em></p><p><em>src/main/java/com/wipro/repository/RefreshTokenRepository.java</em></p><p><em>src/main/java/com/wipro/repository/BlacklistedTokenRepository.java</em></p><p><strong>DB migrations</strong></p><p><em>src/main/resources/db/migration/V1__create_user_tables.sql</em></p><p><em>src/main/resources/db/migration/V2__create_refresh_token.sql</em></p><p><strong>Config &amp; build</strong></p><p><em>src/main/resources/application.properties</em></p><p>pom.xml</p><p><strong>Tests</strong></p><p><em>src/test/java/com/wipro/JwtAuthServiceApplicationTests.java</em> (basic test skeleton)</p><h4><strong>5. Build &amp; run</strong></h4><p>Build system: Maven (<em>pom.xml</em>)</p><p>Typical commands:</p><ul><li>mvn spring-boot:run</li><li>or: mvn package &amp;&amp; java -jar target/&lt;artifact&gt;.jar&lt;/artifact&gt;</li></ul><p><em>application.properties</em> contains environment-specific settings (database and JWT expiry/keys) — open it to confirm values for token TTLs and DB connection.</p><h3><strong>Things to watch for / recommended checks</strong></h3><ul><li>Verify JWT secret/keys and token expiry values in application.properties before running.</li><li>Ensure the database is reachable and that Flyway migrations in <em>src/main/resources/db/migration</em> run successfully.</li><li>Check <em>JwtAuthenticationFilter</em> is checking the blacklist repository (<em>BlacklistedTokenRepository</em>) when validating access tokens.</li><li>Review the scheduled cleanup frequency if the blacklist can grow quickly in your environment.</li></ul><p><a href="https://github.com/snazeergit/json_web_token_service_prod">GitHub - snazeergit/json_web_token_service_prod</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bd104cb7b76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WILP — Wipro]]></title>
            <link>https://medium.com/@nazeersd.java/wilp-wipro-70a444146476?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/70a444146476</guid>
            <category><![CDATA[wilp]]></category>
            <category><![CDATA[wase]]></category>
            <category><![CDATA[wadic]]></category>
            <category><![CDATA[wipro]]></category>
            <category><![CDATA[wista]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 20:24:10 GMT</pubDate>
            <atom:updated>2026-06-23T20:25:24.107Z</atom:updated>
            <content:encoded><![CDATA[<p>Wipro WILP programs combine <strong>employment + higher education</strong>, allowing employees to earn a degree while working at Wipro.</p><p>Work Integrated Learning Programs are : <strong>SIM</strong>, <strong>WASE</strong>, <strong>WADIC</strong>, <strong>WIMS</strong>, and <strong>WISTA</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DvAMbaIsA_xvgmJK2vtdA.png" /></figure><h4><strong>1. SIM</strong> — Strategic Initiatives in Management</h4><p>🎯 <strong>Focus</strong>:<br> Management / Business Leadership</p><p>📚 <strong>Program</strong>:<br> Sponsored MBA (usually with partner institutes like IIMs or similar)</p><p>👨‍💼 <strong>Target Audience</strong>:<br> High-potential employees moving into management roles</p><p>📈 <strong>Outcome</strong>:<br> Prepares for roles like:<br> → Project Manager<br> → Delivery Manager<br> → Business Leader</p><h4>2. WASE — Wipro Academy of Software Excellence</h4><p>🎯 <strong>Focus</strong>: <br> Software Engineering (Core tech program)</p><p>📚 <strong>Program</strong>:<br> M.Tech (Software Engineering)in collaboration with BITS Pilani</p><p>👨‍💻 <strong>Target Audience:</strong><br> Freshers (BSc / BCA / Diploma)</p><p>💡<strong> Key Points:</strong><br> One of <strong>Wipro’s flagship</strong> programs<br> Strong focus on Java, Data Structures, System Design</p><p>📈 <strong>Outcome</strong>:<br> Prepares for roles like:<br> → Software Engineer<br> → Senior Engineer<br> → Architect track</p><h4>3. WADIC — Wipro Academy of Digital &amp; Innovation Consulting</h4><p>🎯 <strong>Focus</strong>:<br> Digital, Consulting, Emerging Tech</p><p>📚 <strong>Program</strong>:<br> Specialized learning in:<br> Cloud<br> AI/ML<br> Digital Transformation<br> Consulting skills</p><p><strong>👨‍💻 Target Audience:<br></strong> Employees aligned to digital &amp; consulting roles</p><p><strong>📈 Outcome:<br></strong> Roles like:<br> → Digital Consultant<br> → Cloud Architect<br> → Transformation Specialist</p><h4>4. WIMS — Wipro Infrastructure Management School</h4><p><strong>🎯 Focus:<br></strong> IT Infrastructure &amp; Operations</p><p>📚 <strong>Program</strong>:<br> Training in:<br> Networking<br> System Administration<br> Cloud Infrastructure<br> ITIL processes</p><p>👨‍💻 <strong>Target Audience:</strong><br> Infra / Support / Operations employees</p><p>📈<strong> Outcome:</strong><br> Roles like:<br> → Infrastructure Engineer<br> → Cloud Ops Engineer<br> → SRE / Platform Engineer</p><h4>5. WISTA — Wipro Integrated Skills &amp; Talent Academy</h4><p>🎯<strong> Focus:</strong><br> Continuous upskilling across all roles</p><p>📚 <strong>Program:</strong><br> Internal academy providing:<br> Role-based learning paths<br> Certification prep (AWS, Azure, Java, etc.)<br> Leadership &amp; soft skills training</p><p>👨‍💻<strong> Target Audience:</strong><br> All employees(lateral hires, experienced professionals, architects)</p><p>💡 <strong>Key Points:</strong><br> Unlike others, this is not a degree program.<br> It’s a continuous learning ecosystem.</p><p>📈 <strong>Outcome:</strong><br> Helps in:<br> Promotions (e.g., C1 → C2)<br> Role transitions<br> Skill alignment with client demand</p><h4>🆚 Quick Comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlLiJ4ajP0CiccSi9b9KhQ.png" /></figure><h4>🧠 Architect-Level Insight</h4><p>IF you’re in C1 Architect band: WISTA + WADIC are most relevant.<br><strong>Focus areas:</strong><br> Cloud architecture (AWS/Azure)<br> Domain consulting<br> System design &amp; scalability<br> <br>These programs directly impact:<br> C2 promotion readiness<br> Client-facing architecture roles</p><p>Strategically use WISTA + AWS certs for your growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70a444146476" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT(Json Web Token)]]></title>
            <link>https://medium.com/@nazeersd.java/jwt-poc-9747c1bb7d52?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9747c1bb7d52</guid>
            <category><![CDATA[json-web-token]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[spring-security]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 15:26:37 GMT</pubDate>
            <atom:updated>2026-06-19T11:56:22.053Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Interview-ready Spring Boot example</strong> implementing:</p><p>Two endpoints (GET, POST)<br>JWT Authentication (stateless)<br>Spring Security integration<br>Clean architecture (filter + util + config)</p><h3>1. Project Dependencies (Maven)</h3><pre>&lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- API --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>            &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>            &lt;version&gt;0.11.5&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- Implementation --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>            &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>            &lt;version&gt;0.11.5&lt;/version&gt;<br>            &lt;scope&gt;runtime&lt;/scope&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- JSON Serializer --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>            &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>            &lt;version&gt;0.11.5&lt;/version&gt;<br>            &lt;scope&gt;runtime&lt;/scope&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>            &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br>            &lt;version&gt;2.8.16&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;<br>            &lt;scope&gt;runtime&lt;/scope&gt;<br>            &lt;optional&gt;true&lt;/optional&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>            &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>            &lt;optional&gt;true&lt;/optional&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><h3>2. JWT Utility Class</h3><pre>package com.wipro.util;<br><br>import io.jsonwebtoken.Claims;<br>import io.jsonwebtoken.Jwts;<br>import io.jsonwebtoken.security.Keys;<br>import org.springframework.stereotype.Component;<br><br>import javax.crypto.SecretKey;<br>import java.nio.charset.StandardCharsets;<br>import java.util.Date;<br><br>@Component<br>public class JwtUtil {<br><br>    // Secret should be at least 256 bits (32 chars minimum for HS256)<br>    private final String SECRET = &quot;mySecretKeymySecretKeymySecretKey12&quot;;<br><br>    private final long EXPIRATION = 1000 * 60 * 60; // 1 hour<br><br>    // Generate secure key<br>    private SecretKey getSigningKey() {<br>        return Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));<br>    }<br><br>    // Generate Token<br>    public String generateToken(String username) {<br>        return Jwts.builder()<br>                .setSubject(username)   // use this for compatibility<br>                .setIssuer(&quot;nazeer-app&quot;)<br>                .setIssuedAt(new Date())<br>                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))<br>                .signWith(getSigningKey())<br>                .compact();<br>    }<br><br>    // Extract Username<br>    public String extractUsername(String token) {<br>        return getClaims(token).getSubject();<br>    }<br><br>    // Validate Token<br>    public boolean validateToken(String token, String username) {<br>        return username.equals(extractUsername(token)) &amp;&amp; !isExpired(token);<br>    }<br><br>    // Check Expiry<br>    private boolean isExpired(String token) {<br>        return getClaims(token).getExpiration().before(new Date());<br>    }<br><br>    // Parse claims (NEW parser API)<br>    private Claims getClaims(String token) {<br>        return Jwts.parserBuilder()<br>                .setSigningKey(getSigningKey())<br>                .build()<br>                .parseClaimsJws(token)<br>                .getBody();<br>    }<br>}</pre><h3>3. JWT Filter (Core Security Logic)</h3><pre>package com.wipro.security;<br><br>import com.wipro.util.JwtUtil;<br>import jakarta.servlet.*;<br>import jakarta.servlet.http.*;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.userdetails.*;<br>import org.springframework.stereotype.Component;<br><br>import java.io.IOException;<br><br>@Component<br>public class JwtFilter extends GenericFilter {<br><br>    @Autowired<br>    private JwtUtil jwtUtil;<br><br>    @Autowired<br>    private UserDetailsService userDetailsService;<br><br>    @Override<br>    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)<br>            throws IOException, ServletException {<br><br>        HttpServletRequest req = (HttpServletRequest) request;<br>        String authHeader = req.getHeader(&quot;Authorization&quot;);<br><br>        if (authHeader != null &amp;&amp; authHeader.startsWith(&quot;Bearer &quot;)) {<br><br>            String token = authHeader.substring(7);<br>            String username = jwtUtil.extractUsername(token);<br><br>            if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br><br>                UserDetails userDetails = userDetailsService.loadUserByUsername(username);<br><br>                if (jwtUtil.validateToken(token, username)) {<br>                    UsernamePasswordAuthenticationToken auth =<br>                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());<br><br>                    SecurityContextHolder.getContext().setAuthentication(auth);<br>                }<br>            }<br>        }<br><br>        chain.doFilter(request, response);<br>    }<br>}</pre><h3>4. Security Configuration (Spring Boot 3+ Style)</h3><pre>package com.wipro.security;<br><br>import org.springframework.context.annotation.*;<br>import org.springframework.security.authentication.*;<br>import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.crypto.bcrypt.*;<br>import org.springframework.security.crypto.password.PasswordEncoder;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;<br><br>@Configuration<br>public class SecurityConfig {<br><br>    private final JwtFilter jwtFilter;<br><br>    public SecurityConfig(JwtFilter jwtFilter) {<br>        this.jwtFilter = jwtFilter;<br>    }<br><br>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br><br>        http.csrf(csrf -&gt; csrf.disable())<br>                .authorizeHttpRequests(auth -&gt; auth<br>                        // Allow Swagger endpoints<br>                        .requestMatchers(<br>                                &quot;/swagger-ui/**&quot;,<br>                                &quot;/v3/api-docs/**&quot;,<br>                                &quot;/swagger-ui.html&quot;<br>                        ).permitAll()<br><br>                        // Allow login API<br>                        .requestMatchers(&quot;/login&quot;).permitAll()<br><br>                        // Secure everything else<br>                        .anyRequest().authenticated()<br>                )<br>                .addFilterBefore(jwtFilter,<br>                        UsernamePasswordAuthenticationFilter.class);<br><br>        return http.build();<br>    }<br><br>    @Bean<br>    public AuthenticationManager authManager(AuthenticationConfiguration config) throws Exception {<br>        return config.getAuthenticationManager();<br>    }<br><br>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br>}</pre><h3>5. User Service (Hardcoded for Demo)</h3><pre>package com.wipro.service;<br><br>import org.springframework.security.core.userdetails.*;<br>import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;<br>import org.springframework.stereotype.Service;<br><br>import java.util.Collections;<br><br>@Service<br>public class CustomUserService implements UserDetailsService {<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) {<br><br>        // Hardcoded user for simplicity<br>        return new User(&quot;admin&quot;,<br>                new BCryptPasswordEncoder().encode(&quot;password&quot;),<br>                Collections.emptyList());<br>    }<br>}</pre><h3>6. Controller with GET &amp; POST APIs</h3><pre>package com.wipro.controller;<br>import com.wipro.model.AuthRequest;<br>import com.wipro.util.JwtUtil;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.security.authentication.*;<br>import org.springframework.web.bind.annotation.*;<br><br>@RestController<br>public class UserController {<br><br>    @Autowired<br>    private JwtUtil jwtUtil;<br><br>    @Autowired<br>    private AuthenticationManager authManager;<br><br>    // LOGIN API (POST)<br>    @PostMapping(&quot;/login&quot;)<br>    public String login(@RequestBody AuthRequest request) {<br><br>        authManager.authenticate(<br>                new UsernamePasswordAuthenticationToken(<br>                        request.getUsername(),<br>                        request.getPassword()<br>                )<br>        );<br><br>        return jwtUtil.generateToken(request.getUsername());<br>    }<br><br>    // GET API (Protected)<br>    @GetMapping(&quot;/hello&quot;)<br>    public String hello() {<br>        return &quot;Hello, JWT Secured World!&quot;;<br>    }<br>}</pre><h3>7. Request DTO</h3><pre>package com.wipro.dto;<br><br>import lombok.AllArgsConstructor;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br><br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class AuthRequest {<br>    private String username;<br>    private String password;<br>}</pre><h3>8. Add Swagger JWT Configuration</h3><p>By default, Swagger UI <strong>does NOT know about JWT authentication</strong>, so it won’t show the 🔒 Authorize button. You need to <strong>define a security scheme (Bearer token)</strong>.</p><pre>package com.wipro.config;<br><br>import io.swagger.v3.oas.models.OpenAPI;<br>import io.swagger.v3.oas.models.Components;<br>import io.swagger.v3.oas.models.info.Info;<br>import io.swagger.v3.oas.models.security.SecurityRequirement;<br>import io.swagger.v3.oas.models.security.SecurityScheme;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>@Configuration<br>public class SwaggerConfig {<br><br>    @Bean<br>    public OpenAPI customOpenAPI() {<br>        return new OpenAPI()<br>                .info(new Info().title(&quot;JWT API&quot;).version(&quot;1.0&quot;))<br>                .addSecurityItem(new SecurityRequirement().addList(&quot;BearerAuth&quot;))<br>                .components(new Components()<br>                        .addSecuritySchemes(&quot;BearerAuth&quot;,<br>                                new SecurityScheme()<br>                                        .name(&quot;Authorization&quot;)<br>                                        .type(SecurityScheme.Type.HTTP)<br>                                        .scheme(&quot;bearer&quot;)<br>                                        .bearerFormat(&quot;JWT&quot;)<br>                        ));<br>    }<br>}</pre><h3>9. How Flow Works (Important for Interviews)</h3><h4>Step-by-step:</h4><ol><li>Client calls:</li></ol><pre>POST /login<br>{<br>  &quot;username&quot;: &quot;admin&quot;,<br>  &quot;password&quot;: &quot;password&quot;<br>}</pre><p>2. Server validates → returns JWT</p><p>3. Client calls protected API:</p><pre>GET /hello<br>Authorization: Bearer &lt;token&gt;</pre><p>4. JwtFilter</p><ul><li>Extracts token</li><li>Validates it</li><li>Sets authentication in SecurityContext</li></ul><p>5. Request proceeds.</p><h3>10. Sample CURL</h3><pre># Login<br>curl -X POST http://localhost:8080/login \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{&quot;username&quot;:&quot;admin&quot;,&quot;password&quot;:&quot;password&quot;}&#39;<br><br># Access API<br>curl http://localhost:8080/hello \<br>-H &quot;Authorization: Bearer &lt;TOKEN&gt;&quot;</pre><h3>11. Invoke endpoints using Swagger</h3><p>Request: POST <a href="http://localhost:8080/login">http://localhost:8080/login</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q18Y7IDCp9mwcMdRwMjIig.png" /></figure><p>Response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23aks826ZpoeETO82e4Mpg.png" /></figure><p>Request: GET <a href="http://localhost:8080/hello">http://localhost:8080/hello</a></p><p>Only add Bearer token to Authorize value field and authorize and close. Please do not append <strong>“Bearer</strong>” keyword at the start of the token as BearerAuth type selected is <strong>(http, Bearer).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xvnp6m7oBzaOxYcHyEUuQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1-cOp9p2ha5hGeO98rFXg.png" /></figure><p>Response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rjno-N7LlOnWmURHIf_qPw.png" /></figure><h3>12. Interview Tips (Architect Level)</h3><p><strong>Why JWT?</strong></p><ul><li>Stateless authentication</li><li>No server-side session required</li><li>Scalable for microservices</li></ul><p><strong>Where to store token?</strong></p><ul><li>Browser → HttpOnly Cookie (secure)</li><li>API clients → Authorization header</li></ul><p><strong>Security Improvements</strong></p><ul><li>Use <strong>refresh tokens</strong></li><li>Externalize secret (Vault / AWS Secrets Manager)</li><li>Use RSA instead of shared secret (HS256 → RS256)</li></ul><p><strong>Production Best Practices</strong></p><ul><li>Token expiry handling</li><li>Exception handling filter</li><li>Role-based authorization (RBAC)</li><li>Use Spring Security OAuth2 resource server for enterprise apps</li></ul><p>Next level: <br>Extend this to <strong>Spring Boot + JWT + Role-based access + DB + Microservices-ready architecture + AWS deployment</strong></p><p><a href="https://github.com/snazeergit/json_web_token_service_basic">GitHub - snazeergit/json_web_token_service_basic</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9747c1bb7d52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototype Pattern]]></title>
            <link>https://medium.com/@nazeersd.java/prototype-pattern-6409f1dc3ccf?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6409f1dc3ccf</guid>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 19:39:10 GMT</pubDate>
            <atom:updated>2026-06-16T19:39:10.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prototype Design Pattern in Java</h3><p>The <strong>Prototype Pattern</strong> is a <strong>Creational Design Pattern</strong> that creates new objects by <strong>copying (cloning) an existing object</strong> instead of creating them from scratch using new.</p><p>It is useful when object creation is expensive or complex.</p><h3>Real-World Example</h3><p>Imagine a game where creating a character involves:</p><ul><li>Loading images</li><li>Loading weapons</li><li>Setting attributes</li><li>Initializing skills</li></ul><p>Instead of creating each character from scratch, you create one character and clone it whenever needed.</p><h3>UML Diagram</h3><pre>                +----------------+<br>                |   Prototype    |<br>                +----------------+<br>                | clone()        |<br>                +----------------+<br>                        ^<br>                        |<br>                +----------------+<br>                |    Vehicle     |<br>                +----------------+<br>                | model          |<br>                | color          |<br>                +----------------+<br>                | clone()        |<br>                +----------------+</pre><h3>Example:</h3><h4>Prototype Interface</h4><pre>public interface Prototype {<br>    Prototype clone();<br>}</pre><h4>Concrete Prototype</h4><pre>public class Vehicle implements Prototype {<br>    private String model;<br>    private String color;<br>    public Vehicle(String model, String color) {<br>        this.model = model;<br>        this.color = color;<br>    }<br>    @Override<br>    public Vehicle clone() {<br>        return new Vehicle(model, color);<br>    }<br>    public void display() {<br>        System.out.println(<br>            &quot;Model: &quot; + model +<br>            &quot;, Color: &quot; + color<br>        );<br>    }<br>}</pre><h4>Client</h4><pre>public class Main {<br>    public static void main(String[] args) {<br>        Vehicle car1 =<br>            new Vehicle(&quot;BMW X5&quot;, &quot;Black&quot;);<br>        Vehicle car2 = car1.clone();<br>        car1.display();<br>        car2.display();<br>        System.out.println(car1 == car2);<br>    }<br>}</pre><h4>Output</h4><pre>Model: BMW X5, Color: Black<br>Model: BMW X5, Color: Black<br>false</pre><p>The cloned object has the same data but is a different object in memory.</p><h3>Using Java’s Cloneable Interface</h3><p>Java provides the Cloneable marker interface and Object.clone() method.</p><pre>class Vehicle implements Cloneable {<br>    private String model;<br>    public Vehicle(String model) {<br>        this.model = model;<br>    }<br>    @Override<br>    protected Vehicle clone()<br>            throws CloneNotSupportedException {<br>        return (Vehicle) super.clone();<br>    }<br>}</pre><p>Usage:</p><pre>Vehicle v1 = new Vehicle(&quot;BMW&quot;);<br>Vehicle v2 = v1.clone();</pre><p>However, many developers avoid Cloneable because it has design limitations and can be error-prone.</p><h3>Shallow Copy vs Deep Copy</h3><h4>Shallow Copy</h4><p>Copies primitive fields and object references.</p><pre>Original Vehicle<br>      |<br>      +----&gt; Engine Object</pre><pre>Cloned Vehicle<br>      |<br>      +----&gt; Same Engine Object</pre><p>Both vehicles share the same Engine.</p><h4>Example</h4><pre>class Engine {<br>    String type;<br>}</pre><pre>class Vehicle implements Cloneable {<br>    Engine engine;<br>    @Override<br>    public Vehicle clone()<br>            throws CloneNotSupportedException {<br>        return (Vehicle) super.clone();<br>    }<br>}</pre><h4>Deep Copy</h4><p>Copies nested objects as well.</p><pre>Original Vehicle<br>      |<br>      +----&gt; Engine Object</pre><pre>Cloned Vehicle<br>      |<br>      +----&gt; New Engine Object</pre><h4>Example</h4><pre>class Engine {<br>    String type;</pre><pre>Engine(String type) {<br>        this.type = type;<br>    }<br>    Engine cloneEngine() {<br>        return new Engine(type);<br>    }<br>}<br>class Vehicle {<br>    private String model;<br>    private Engine engine;<br>    Vehicle(String model, Engine engine) {<br>        this.model = model;<br>        this.engine = engine;<br>    }<br>    public Vehicle clone() {<br>        return new Vehicle(<br>            model,<br>            engine.cloneEngine()<br>        );<br>    }<br>}</pre><h4>When to Use Prototype Pattern</h4><p>Use it when:</p><p>→ Object creation is expensive</p><p>→ Many similar objects are required</p><p>→ You want to avoid complex constructors</p><p>→ Runtime object copying is needed</p><p>Examples:</p><ul><li>Game characters</li><li>Document templates</li><li>Configuration objects</li><li>UI components</li><li>Microservice request templates</li></ul><h4>Advantages</h4><ul><li>Faster than creating complex objects repeatedly.</li><li>Reduces object creation cost.</li><li>Hides complex initialization logic.</li><li>Allows dynamic object creation at runtime.</li></ul><h4>Disadvantages</h4><ul><li>Deep cloning can be difficult.</li><li>Circular references can complicate cloning.</li><li>Maintaining clone logic becomes harder as objects grow.</li></ul><h4>Difference from Factory Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GU4efwYhba4yojv8cchv-A.png" /></figure><h4>Simple Comparison</h4><pre>// Factory<br>Vehicle car = vehicleFactory.createVehicle();<br><br>// Prototype<br>Vehicle clonedCar = existingCar.clone();</pre><p><strong>Key idea:</strong> Prototype says <em>“copy an existing object”</em>, while Factory says <em>“create a new object.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6409f1dc3ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder Pattern]]></title>
            <link>https://medium.com/@nazeersd.java/builder-pattern-b699d6d7da7e?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b699d6d7da7e</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 13:56:25 GMT</pubDate>
            <atom:updated>2026-06-15T13:56:25.746Z</atom:updated>
            <content:encoded><![CDATA[<p>Builder Design Pattern using an <strong>inner static class</strong> is a common and clean way to create immutable objects in Java, especially when constructors become complex (many parameters, optional fields, etc.).</p><p><strong>Employee class using Builder Pattern:</strong></p><pre>package org.wipro.dp.builder;<br><br>public class User {<br>    private final Integer age;<br>    private final String name;<br>    private final String phone;<br>    private final String email;<br><br>    private User(Builder builder) {<br>        this.age = builder.age;<br>        this.name = builder.name;<br>        this.phone = builder.phone;<br>        this.email = builder.email;<br>    }<br><br>    public Integer getAge() {<br>        return this.age;<br>    }<br><br>    public String getName() {<br>        return this.name;<br>    }<br><br>    public String getPhone() {<br>        return this.phone;<br>    }<br><br>    public String getEmail() {<br>        return this.email;<br>    }<br><br>    public static class Builder {<br>        private Integer age;<br>        private String name;<br>        private String phone;<br>        private String email;<br><br>        public Builder(Integer age, String name) {<br>            this.age = age;<br>            this.name = name;<br>        }<br><br>        public Builder phone(String phone) {<br>            this.phone = phone;<br>            return this;<br>        }<br><br>        public Builder email(String email) {<br>            this.email = email;<br>            return this;<br>        }<br><br>        public User build() {<br>            return new User(this);<br>        }<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;User{&quot; +<br>                &quot;id=&quot; + age +<br>                &quot;, name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, salary=&quot; + phone +<br>                &quot;, address=&#39;&quot; + email + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p><strong>Client:</strong> We create multiple Employee objects passing different properties.</p><pre>package org.wipro;<br><br>import org.wipro.dp.Singleton;<br>import org.wipro.dp.builder.Employee;<br><br>public class App {<br>    public static void main(String[] args) {<br>  <br>        User u1 = new User.Builder(10, &quot;Syed Nazeer&quot;).phone(&quot;1234&quot;).email(&quot;Kodathi&quot;).build();<br>        User u2 = new User.Builder(10, &quot;Syed Nazeer&quot;).phone(&quot;1234&quot;).build();<br>        User u3 = new User.Builder(10, &quot;Syed Nazeer&quot;).email(&quot;Kodathi&quot;).build();<br><br>        System.out.println(u1.toString());<br>        System.out.println(u2.toString());<br>        System.out.println(u3.toString());<br><br>    }<br>}</pre><p>Output:</p><pre>User{id=10, name=&#39;Syed Nazeer&#39;, salary=1234, address=&#39;Kodathi&#39;}<br>User{id=10, name=&#39;Syed Nazeer&#39;, salary=1234, address=&#39;null&#39;}<br>User{id=10, name=&#39;Syed Nazeer&#39;, salary=null, address=&#39;Kodathi&#39;}</pre><p>UML Diagram:</p><pre>+-----------------------------+<br>|            User             |<br>+-----------------------------+<br>| - name : String             |<br>| - age  : int                |<br>| - email : String            |<br>| - phone : String            |<br>+-----------------------------+<br>| + getName() : String        |<br>| + getAge() : int            |<br>| + getEmail() : String       |<br>| + getPhone() : String       |<br>+-----------------------------+<br>| &lt;&lt;private&gt;&gt; User(Builder)   |<br>+-----------------------------+<br>              ▲<br>              |<br>              |<br>+-----------------------------+<br>|     User.Builder (static)   |<br>+-----------------------------+<br>| - name : String             |<br>| - age  : int                |<br>| - email : String            |<br>| - phone : String            |<br>+-----------------------------+<br>| + Builder(name, age)        |<br>| + email(String) : Builder   |<br>| + phone(String) : Builder   |<br>| + build() : User            |<br>+-----------------------------+</pre><h3>Key UML Relationships</h3><h3>1. Composition / Tight Association</h3><ul><li>User is <strong>constructed using Builder</strong></li><li>Builder is a <strong>static inner class</strong></li><li>Represented by logical containment (inner class)</li></ul><h3>Mermaid UML Diagram (Visual)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnURGwFyZKktAzF4MgQ8iQ.png" /></figure><h3>Interview Explanation (How to Describe UML)</h3><p><em>“User is an immutable class with private fields and no setters. It has a private constructor that accepts a Builder object. The Builder is a static inner class responsible for step-by-step object construction. The build() method returns the final User object.”</em></p><h3>Key UML Points to Highlight</h3><ul><li><strong>Encapsulation</strong> → fields are private</li><li><strong>Immutability</strong> → no setters in User</li><li><strong>Builder static inner class</strong></li><li><strong>Fluent interface</strong> (methods return Builder)</li><li><strong>Object creation delegated to Builder</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b699d6d7da7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns]]></title>
            <link>https://medium.com/@nazeersd.java/design-patterns-23ed7b991a9b?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/23ed7b991a9b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 08:51:19 GMT</pubDate>
            <atom:updated>2026-06-14T15:04:57.144Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns in Java</h3><p><strong>Design Patterns</strong> are reusable solutions to common software design problems. They help make code more flexible, maintainable, and scalable.</p><p>Design patterns are generally categorised into three groups:</p><p><strong>Creational</strong>, <strong>Structural</strong> and <strong>Behavioural</strong> patterns.</p><h3>1. Creational Patterns</h3><p>These deal with object creation mechanisms.</p><p><strong>Singleton: </strong>Ensures only one instance of a class exists.</p><p><strong>Factory Method: </strong>Creates objects without specifying the exact class.</p><p><strong>Abstract Factory: </strong>Creates families of related objects.</p><p><strong>Builder: </strong>Constructs complex objects step by step.</p><p><strong>Prototype: </strong>Creates objects by cloning existing ones.</p><h4>Example: Singleton Pattern</h4><pre>public class Singleton {<br>    <br>    private static Singleton instance;<br>    <br>    private Singleton() {}<br>    <br>    public static Singleton getInstance() {<br>        if (instance == null) {<br>            instance = new Singleton();<br>        }<br>        return instance;<br>    }<br><br>}</pre><h3>2. Structural Patterns</h3><p>These focus on how classes and objects are composed.</p><p><strong>Adapter: </strong>Converts one interface into another.</p><p><strong>Bridge: </strong>Separates abstraction from implementation.</p><p><strong>Composite: </strong>Treats individual and group objects uniformly.</p><p><strong>Decorator: </strong>Adds functionality dynamically.</p><p><strong>Facade: </strong>Provides a simplified interface.</p><p><strong>Flyweight: </strong>Reduces memory usage by sharing objects.</p><p><strong>Proxy: </strong>Controls access to another object.</p><h4>Example: Decorator Pattern</h4><pre>interface Coffee {<br>    String getDescription();<br>}<br><br>class SimpleCoffee implements Coffee {<br>    public String getDescription() {<br>        return &quot;Simple Coffee&quot;;<br>    }<br>}<br><br>class MilkDecorator implements Coffee {<br>    private Coffee coffee;<br>    public MilkDecorator(Coffee coffee) {<br>        this.coffee = coffee;<br>    }<br>    public String getDescription() {<br>        return coffee.getDescription() + &quot;, Milk&quot;;<br>    }<br>}</pre><h3>3. Behavioural Patterns</h3><p>These focus on communication between objects.</p><p><strong>Observer: </strong>Notifies multiple objects about state changes.</p><p><strong>Strategy: </strong>Encapsulates interchangeable algorithms.</p><p><strong>Command: </strong>Encapsulates requests as objects.</p><p><strong>Iterator: </strong>Sequentially accesses collection elements.</p><p><strong>Mediator: </strong>Centralizes communication between objects.</p><p><strong>Memento: </strong>Saves and restores object state.</p><p><strong>State: </strong>Changes behaviour based on state.</p><p><strong>Template Method: </strong>Defines an algorithm skeleton.</p><p><strong>Visitor: </strong>Adds operations without modifying classes.</p><p><strong>Chain of Responsibility: </strong>Passes requests along a chain of handlers.</p><p><strong>Interpreter: </strong>Implements a language grammar.</p><h4>Example: Strategy Pattern</h4><pre>interface PaymentStrategy {<br>    void pay(int amount);<br>}<br>class CreditCardPayment implements PaymentStrategy {<br>    public void pay(int amount) {<br>        System.out.println(&quot;Paid using Credit Card: &quot; + amount);<br>    }<br>}<br>class PayPalPayment implements PaymentStrategy {<br>    public void pay(int amount) {<br>        System.out.println(&quot;Paid using PayPal: &quot; + amount);<br>    }<br>}<br>class ShoppingCart {<br>    private PaymentStrategy strategy;<br>    public ShoppingCart(PaymentStrategy strategy) {<br>        this.strategy = strategy;<br>    }<br>    public void checkout(int amount) {<br>        strategy.pay(amount);<br>    }<br>}</pre><p>Usage:</p><pre>ShoppingCart cart = new ShoppingCart(new CreditCardPayment());<br>cart.checkout(1000);</pre><h3>Frequently Used Design Patterns in Java Interviews</h3><ol><li><strong>Singleton</strong></li><li><strong>Factory Method</strong></li><li><strong>Builder</strong></li><li><strong>Strategy</strong></li><li><strong>Observer</strong></li><li><strong>Decorator</strong></li><li><strong>Adapter</strong></li><li><strong>MVC (Architectural Pattern)</strong></li></ol><h3>Real-World Examples</h3><ul><li><strong>Singleton</strong> → Database connection, Logger</li><li><strong>Factory</strong> → JDBC DriverManager</li><li><strong>Builder</strong> → StringBuilder, Lombok Builder</li><li><strong>Observer</strong> → Event listeners, GUI frameworks</li><li><strong>Decorator</strong> → Java I/O Streams (BufferedInputStream)</li><li><strong>Strategy</strong> → Sorting algorithms, Payment methods</li></ul><h3>Advantages</h3><ul><li>Improves code reusability</li><li>Reduces coupling</li><li>Increases maintainability</li><li>Makes applications easier to extend</li><li>Encourages best practices and clean architecture</li></ul><p>A common interview question is to explain the <strong>Factory</strong>, <strong>Singleton</strong>, <strong>Builder</strong>, <strong>Strategy</strong>, and <strong>Observer</strong> patterns with real-world examples and Java code. These are considered the most important patterns for Java developers.</p><p><a href="https://github.com/snazeergit/DP/tree/master/src/main/java/org/ltim">DP/src/main/java/org/ltim at master · snazeergit/DP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23ed7b991a9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Pattern]]></title>
            <link>https://medium.com/@nazeersd.java/factory-pattern-6c22e9cfa09d?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c22e9cfa09d</guid>
            <category><![CDATA[factory-method]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[factory]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 08:50:42 GMT</pubDate>
            <atom:updated>2026-06-14T15:03:56.034Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>Factory Design Pattern</strong> is a <strong>creational design pattern</strong> that provides an interface for creating objects without exposing the object creation logic to the client. Instead of using new directly, the client asks a factory to create the object.</p><h3>Why Use the Factory Pattern?</h3><ul><li>Encapsulates object creation logic.</li><li>Reduces coupling between client code and concrete classes.</li><li>Makes code easier to extend and maintain.</li><li>Supports the <strong>Open/Closed Principle</strong> (open for extension, closed for modification).</li></ul><h3><strong>Factory Method vs Factory Method Pattern</strong></h3><h4>Generic Factory Method (just a method that creates objects)</h4><p>Any method that creates and returns an object can be called a factory method.</p><pre>public static Vehicle createVehicle() {<br>    return new Car();<br>}</pre><p>Here, “factory method” simply means <strong>a method responsible for object creation</strong>.</p><p>Both Simple Factory and Abstract Factory contain such methods.</p><h4>Factory Method Pattern (GoF Design Pattern)</h4><p>This is a specific design pattern from the Gang of Four.</p><p>It intends to define an interface for creating an object while allowing subclasses to decide which class to instantiate.</p><h3>Types of Factory Patterns</h3><h4>1. Simple Factory Pattern</h4><p>A single factory class creates different objects based on input.</p><pre>Vehicle vehicle = VehicleFactory.createVehicle(&quot;CAR&quot;);</pre><p>Creates <strong>one object. The factory</strong> decides <strong>which object</strong> to create using conditions.</p><h4>2. Factory Method Pattern</h4><p>Defines an interface for creating objects, but subclasses decide which class to instantiate.</p><pre>VehicleFactory factory = new CarFactory();<br>Vehicle vehicle = factory.createVehicle();</pre><p>The chosen factory already knows <strong>which object</strong> to create.</p><h4>3. Abstract Factory Pattern</h4><p>Creates families of related objects.</p><p>Example:</p><pre>VehicleFactory factory = new IndiaVehicleFactory();<br>Car car = factory.createCar();<br>Bike bike = factory.createBike();</pre><p>Creates a <strong>family of related objects</strong> (IndiaCar and IndiaBike).</p><h4>Advantages:</h4><p>→ Loose coupling<br> → Better maintainability<br> → Centralised object creation<br> → Easy to add new product types<br> → Supports SOLID principles</p><h4>Disadvantages:</h4><p>→ More classes and complexity<br> → The factory may become large if many product types exist</p><h4>When to Use:</h4><p>Use the Factory Pattern when:</p><ul><li>The exact type of object is decided at runtime.</li><li>Object creation is complex.</li><li>You want to hide the creation logic from clients.</li><li>Multiple implementations share a common interface.</li></ul><p><strong>Examples:</strong> database drivers, logging frameworks, payment gateways, notification services, UI component libraries, and parsers.</p><h3>Simple Example (Java)</h3><h4>Without Factory</h4><pre>public class Main {<br>    public static void main(String[] args) {<br>        Car car = new Car();<br>        car.drive();<br>    }<br>}<br>class Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving a car&quot;);<br>    }<br>}</pre><p>The client is tightly coupled to Car.</p><h4>1. With Simple Factory Pattern</h4><h4>Product Interface</h4><pre>interface Vehicle {<br>    void drive();<br>}</pre><h4>Concrete Products</h4><pre>class Car implements Vehicle {<br>    public void drive() {<br>        System.out.println(&quot;Driving a car&quot;);<br>    }<br>}</pre><pre>class Bike implements Vehicle {<br>    public void drive() {<br>        System.out.println(&quot;Riding a bike&quot;);<br>    }<br>}</pre><h4>Factory Class</h4><pre>class VehicleFactory {<br>public static Vehicle createVehicle(String type) {<br>        if (type.equalsIgnoreCase(&quot;car&quot;)) {<br>            return new Car();<br>        }<br>        if (type.equalsIgnoreCase(&quot;bike&quot;)) {<br>            return new Bike();<br>        }<br>        throw new IllegalArgumentException(&quot;Unknown vehicle type&quot;);<br>    }<br>}</pre><h4>Client Code</h4><pre>public class Main {<br>    public static void main(String[] args) {<br>        Vehicle vehicle = VehicleFactory.createVehicle(&quot;car&quot;);<br>        vehicle.drive();<br>    }<br>}</pre><h4>Output</h4><pre>Driving a car</pre><p>For the <strong>Vehicle Factory Pattern</strong> example, the UML class diagram would look like this:</p><pre>+----------------+<br>|    Vehicle     | &lt;&lt;interface&gt;&gt;<br>+----------------+<br>| + drive()      |<br>+----------------+<br>        ^<br>        |<br>  -------------------<br>  |                 |<br>  |                 |<br>+--------+      +--------+<br>| Car    |      | Bike   |<br>+--------+      +--------+<br>|        |      |        |<br>+--------+      +--------+<br>|+drive()|      |+drive()|<br>+--------+      +--------+<br><br><br><br>       +----------------------+<br>       |   VehicleFactory     |<br>       +----------------------+<br>       |                      |<br>       +----------------------+<br>       | +createVehicle(type) |<br>       +----------------------+<br>                |<br>                | creates<br>                v<br>         +--------------+<br>         |   Vehicle    |<br>         +--------------+<br><br><br>       +-------------+<br>       |    Client   |<br>       +-------------+<br>       |             |<br>       +-------------+<br>              |<br>              | uses<br>              v<br>       +----------------------+<br>       |   VehicleFactory     |<br>       +----------------------+</pre><h4>This diagram clearly shows the three key participants of the Factory Pattern:</h4><ol><li><strong>Product</strong> → Vehicle</li><li><strong>Concrete Products</strong> → Car, Bike</li><li><strong>Factory</strong> → VehicleFactory</li><li><strong>Client</strong> → Uses the factory instead of creating objects directly.</li></ol><h3>2. With Factory Method Pattern</h3><h4>Product Interface</h4><pre>interface Vehicle {<br>    void drive();<br>}</pre><h4>Concrete Products</h4><pre>class Car implements Vehicle {<br>    public void drive() {<br>        System.out.println(&quot;Driving a car&quot;);<br>    }<br>}</pre><pre>class Bike implements Vehicle {<br>    public void drive() {<br>        System.out.println(&quot;Riding a bike&quot;);<br>    }<br>}</pre><h4>Creator Factory</h4><pre>interface VehicleFactory {<br>    Vehicle createVehicle(); <br>}</pre><h4>Concrete Factories</h4><pre>class CarFactory implements VehicleFactory {<br><br>    @Override<br>    public Vehicle createVehicle() {<br>        return new Car();<br>    }<br>}</pre><pre>class BikeFactory implements VehicleFactory {<br><br>    @Override<br>    public Vehicle createVehicle() {<br>        return new Bike();<br>    }<br>}</pre><h4>Client Code</h4><pre>public class Main {<br>    public static void main(String[] args) {<br>       VehicleFactory factory = new CarFactory();<br>       Vehicle vehicle = factory.createVehicle();<br>       vehicle.drive();<br>    }<br>}</pre><h4>Output</h4><pre>Driving a car</pre><p>For the <strong>Vehicle Factory Method Pattern</strong> example, the UML class diagram would look like this:</p><pre>                         &lt;&lt;interface&gt;&gt;<br>                         VehicleFactory<br>                         ----------------<br>                         + createVehicle() : Vehicle<br>                                 ^<br>                                 |<br>                 ----------------+----------------<br>                 |                               |<br>                 |                               |<br>        +----------------+             +----------------+<br>        |   CarFactory   |             |  BikeFactory   |<br>        +----------------+             +----------------+<br>        |                |             |                |<br>        +----------------+             +----------------+<br>        | +createVehicle()|            | +createVehicle()|<br>        +----------------+             +----------------+<br>                 |                               |<br>                 | creates                       | creates<br>                 v                               v<br><br>                     &lt;&lt;interface&gt;&gt;<br>                         Vehicle<br>                         ----------------<br>                         + drive() : void<br>                                ^<br>                                |<br>                  --------------+--------------<br>                  |                           |<br>                  |                           |<br>           +-------------+             +-------------+<br>           |     Car     |             |    Bike     |<br>           +-------------+             +-------------+<br>           |             |             |             |<br>           +-------------+             +-------------+<br>           | +drive()    |             | +drive()    |<br>           +-------------+             +-------------+</pre><p><strong>UML with Client</strong></p><pre>                           Client(Main)<br>                                |<br>                                | uses<br>                                v<br><br>                         &lt;&lt;interface&gt;&gt;<br>                         VehicleFactory<br>                         + createVehicle(): Vehicle<br>                                 ^<br>                                 |<br>                 ----------------+----------------<br>                 |                               |<br>                 |                               |<br>           CarFactory                      BikeFactory<br>                 |                               |<br>                 | creates                       | creates<br>                 v                               v<br><br>                         &lt;&lt;interface&gt;&gt;<br>                            Vehicle<br>                            + drive()<br>                                ^<br>                                |<br>                  --------------+--------------<br>                  |                           |<br>                 Car                        Bike</pre><h4>Relationship Summary:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_W8T5B4h_-gbT7MyL4705g.png" /></figure><h3>3. With Abstract Factory Pattern</h3><p>The <strong>Abstract Factory Pattern</strong> provides an interface for creating <strong>families of related objects</strong> without specifying their concrete classes.</p><h4>Vehicle Example</h4><p>Suppose you manufacture vehicles for different regions:</p><ul><li>India Factory → Bike, Car</li><li>USA Factory → Bike, Car</li></ul><p>The client should not know which concrete classes are being created.</p><h4>1. Product Interfaces</h4><pre>interface Car {<br>    void drive();<br>}</pre><pre>interface Bike {<br>    void ride();<br>}</pre><h4>2. Concrete Products</h4><h4>India Vehicles</h4><pre>class IndiaCar implements Car {<br>    @Override<br>    public void drive() {<br>        System.out.println(&quot;Driving India Car&quot;);<br>    }<br>}</pre><pre>class IndiaBike implements Bike {<br>    @Override<br>    public void ride() {<br>        System.out.println(&quot;Riding India Bike&quot;);<br>    }<br>}</pre><h4>USA Vehicles</h4><pre>class USACar implements Car {<br>    @Override<br>    public void drive() {<br>        System.out.println(&quot;Driving USA Car&quot;);<br>    }<br>}<br></pre><pre>class USABike implements Bike {<br>    @Override<br>    public void ride() {<br>        System.out.println(&quot;Riding USA Bike&quot;);<br>    }<br>}</pre><h4>3. Abstract Factory</h4><pre>interface VehicleFactory {<br>    Car createCar();<br>    Bike createBike();<br>}</pre><p>Notice that the factory creates a <strong>family of products</strong> (Car and Bike).</p><h4>4. Concrete Factories</h4><h4>India Factory</h4><pre>class IndiaVehicleFactory implements VehicleFactory {<br>    @Override<br>    public Car createCar() {<br>        return new IndiaCar();<br>    }<br>    @Override<br>    public Bike createBike() {<br>        return new IndiaBike();<br>    }<br>}</pre><h4>USA Factory</h4><pre>class USAVehicleFactory implements VehicleFactory {<br>    @Override<br>    public Car createCar() {<br>        return new USACar();<br>    }<br>    @Override<br>    public Bike createBike() {<br>        return new USABike();<br>    }<br>}</pre><h4>5. Client Code</h4><pre>public class Main {<br>    public static void main(String[] args) {<br>        VehicleFactory factory = new IndiaVehicleFactory();<br>        Car car = factory.createCar();<br>        Bike bike = factory.createBike();<br>        car.drive();<br>        bike.ride();<br>    }<br>}</pre><h4>Output</h4><pre>Driving India Car<br>Riding India Bike</pre><p>Here’s a <strong>UML Class Diagram</strong> for the <strong>Abstract Factory</strong> Vehicle example:</p><pre>                            +------------------+<br>                            |  VehicleFactory  |<br>                            +------------------+<br>                            | +createCar()     |<br>                            | +createBike()    |<br>                            +------------------+<br>                                      ^<br>                    ------------------|------------------<br>                    |                                    |<br>                    |                                    |<br>      +---------------------------+      +---------------------------+<br>      | IndiaVehicleFactory       |      | USAVehicleFactory         |<br>      +---------------------------+      +---------------------------+<br>      | +createCar()              |      | +createCar()              |<br>      | +createBike()             |      | +createBike()             |<br>      +---------------------------+      +---------------------------+<br>             |          |                         |          |<br>             | creates  | creates                 | creates  | creates<br>             v          v                         v          v<br><br>      +---------------+                  +---------------+<br>      |  IndiaCar     |                  |   USACar      |<br>      +---------------+                  +---------------+<br>      | +drive()      |                  | +drive()      |<br>      +---------------+                  +---------------+<br>             ^                                   ^<br>             |                                   |<br>             | implements                        | implements<br>             |                                   |<br>      +---------------+                  +---------------+<br>      |     Car       |                  |     Car       |<br>      +---------------+                  +---------------+<br>      | +drive()      |<br>      +---------------+<br><br>      +---------------+                  +---------------+<br>      |  IndiaBike    |                  |   USABike     |<br>      +---------------+                  +---------------+<br>      | +ride()       |                  | +ride()       |<br>      +---------------+                  +---------------+<br>             ^                                   ^<br>             |                                   |<br>             | implements                        | implements<br>             |                                   |<br>      +---------------+                  +---------------+<br>      |    Bike       |                  |    Bike       |<br>      +---------------+                  +---------------+<br>      | +ride()       |<br>      +---------------+</pre><p>A cleaner UML using standard notation:</p><pre>                    &lt;&lt;interface&gt;&gt;<br>                   VehicleFactory<br>              +----------------------+<br>              + createCar(): Car<br>              + createBike(): Bike<br>              +----------------------+<br>                       ^<br>                       |<br>        +--------------+--------------+<br>        |                             |<br>+-------------------+      +-------------------+<br>|IndiaVehicleFactory|      | USAVehicleFactory |<br>+-------------------+      +-------------------+<br>|+createCar()       |      |+createCar()       |<br>|+createBike()      |      |+createBike()      |<br>+-------------------+      +-------------------+<br><br>      | creates                     | creates<br>      v                             v<br><br>      &lt;&lt;interface&gt;&gt;               &lt;&lt;interface&gt;&gt;<br>          Car                         Bike<br>      +---------+                 +---------+<br>      + drive() |                 + ride()  |<br>      +---------+                 +---------+<br>          ^                           ^<br>          |                           |<br>    +-----------+               +-----------+<br>    | IndiaCar  |               | IndiaBike |<br>    +-----------+               +-----------+<br><br>          ^                           ^<br>          |                           |<br>    +-----------+               +-----------+<br>    |  USACar   |               |  USABike  |<br>    +-----------+               +-----------+</pre><h3>Relationship Summary</h3><ul><li><strong>VehicleFactory</strong> → Abstract Factory</li><li><strong>IndiaVehicleFactory</strong>, <strong>USAVehicleFactory</strong> → Concrete Factories</li><li><strong>Car</strong>, <strong>Bike</strong> → Abstract Products</li><li><strong>IndiaCar</strong>, <strong>USACar</strong>, <strong>IndiaBike</strong>, <strong>USABike</strong> → Concrete Products</li><li>Client depends only on:</li><li>VehicleFactory</li><li>Car</li><li>Bike</li></ul><h4>Why is it called “Abstract Factory”?</h4><p>Because:</p><ul><li>VehicleFactory is an <strong>abstract factory</strong> (an interface).</li><li>It defines methods for creating a <strong>group of related products</strong>.</li><li>Concrete factories (IndiaVehicleFactory, USAVehicleFactory) decide which actual objects to create.</li></ul><h4>Factory Method vs Abstract Factory</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*1iskVK1vD2kpH82N-ke4UA.png" /></figure><p>Think of it this way:</p><ul><li><strong>Factory Method</strong> → “Give me a Vehicle.”</li><li><strong>Abstract Factory</strong> → “Give me all vehicles for a specific market (Car + Bike).”</li></ul><h3>Real-World Example</h3><p>Imagine a notification system:</p><pre>Notification notification =<br>        NotificationFactory.create(&quot;EMAIL&quot;);</pre><p>The factory decides whether to create:</p><ul><li>EmailNotification</li><li>SMSNotification</li><li>PushNotification</li></ul><p>The client only knows about the Notification interface.</p><p><a href="https://github.com/snazeergit/DP/tree/master/src/main/java/org/ltim/factory">DP/src/main/java/org/ltim/factory at master · snazeergit/DP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c22e9cfa09d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Format Specifiers]]></title>
            <link>https://medium.com/@nazeersd.java/java-format-specifiers-8dbacaf79802?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dbacaf79802</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[format-specifiers]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 20:34:32 GMT</pubDate>
            <atom:updated>2026-06-09T20:34:32.274Z</atom:updated>
            <content:encoded><![CDATA[<p>In System.out.printf() and String.format(), Java uses <strong>format specifiers</strong> that start with %. However, System.out.println() does not recognise format specifiers.</p><h4>Common Format Specifiers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41z2_7ZFQn1qZDdoVq2Ztg.png" /></figure><h4>Examples</h4><h4>%d– Integer</h4><pre>int age = 35;<br>System.out.printf(&quot;Age: %d%n&quot;, age);</pre><p>Output:</p><pre>Age: 35</pre><h4>%s– String</h4><pre>String name = &quot;Armaan&quot;;<br>System.out.printf(&quot;Name: %s%n&quot;, name);</pre><p>Output:</p><pre>Name: Armaan</pre><h4>%f– Decimal Number</h4><pre>double salary = 12345.6789;<br>System.out.printf(&quot;Salary: %f%n&quot;, salary);</pre><p>Output:</p><pre>Salary: 12345.678900</pre><p>Control decimal places:</p><pre>System.out.printf(&quot;%.2f%n&quot;, salary);</pre><p>Output:</p><pre>12345.68</pre><h4>%c– Character</h4><pre>char grade = &#39;A&#39;;<br>System.out.printf(&quot;Grade: %c%n&quot;, grade);</pre><h4>%b– Boolean</h4><pre>boolean passed = true;<br>System.out.printf(&quot;Passed: %b%n&quot;, passed);</pre><h4>%x– Hexadecimal</h4><pre>int num = 255;<br>System.out.printf(&quot;%x%n&quot;, num);</pre><p>Output:</p><pre>ff</pre><p>Uppercase:</p><pre>System.out.printf(&quot;%X%n&quot;, num);</pre><p>Output:</p><pre>FF</pre><h4>%e– Scientific Notation</h4><pre>double value = 12345.67;<br>System.out.printf(&quot;%e%n&quot;, value);</pre><p>Output:</p><pre>1.234567e+04</pre><h3>Width and Alignment</h3><h4>Right Align</h4><pre>System.out.printf(&quot;%10s%n&quot;, &quot;Java&quot;);</pre><p>Output:</p><pre>Java</pre><h4>Left Align</h4><pre>System.out.printf(&quot;%-10s%n&quot;, &quot;Java&quot;);</pre><p>Output:</p><pre>Java</pre><h3>Multiple Values</h3><pre>String name = &quot;Armaan&quot;;<br>int exp = 12;<br>double salary = 25.75;</pre><pre>System.out.printf(<br>    &quot;Name: %s, Experience: %d years, Salary: %.2f LPA%n&quot;,<br>    name,<br>    exp,<br>    salary<br>);</pre><p>Output:</p><pre>Name: Armaan, Experience: 12 years, Salary: 25.75 LPA</pre><h4>%%- to print percentage symbol</h4><pre><br>float percent=100;<br>System.out.printf(&quot;Percentage: %f%%%n&quot;,percent);<br>System.out.printf(&quot;Percentage: %.2f%%%n&quot;,percent);<br>System.out.printf(&quot;Percentage: %.0f%%%n&quot;,percent);<br>String p=&quot;99&quot;;<br>System.out.printf(&quot;Percentage: %s%%%n&quot;,p);<br></pre><p>Output:</p><pre>Percentage: 100.000000%<br>Percentage: 100.00%<br>Percentage: 100%<br>Percentage: 99%<br></pre><h4>System.out.println() vs System.out.printf() :</h4><p>println accepts the ‘+’ symbol to append and prints all the format specifiers as they are in double quotes. In contrast, printf accepts the comma(,) symbol and applies formatting based on the format specifiers specified in double quotes.</p><pre>String percent=&quot;100&quot;;<br> System.out.println(&quot;Percentage: &quot;+percent+&quot;%&quot;);<br> System.out.printf(&quot;Percentage: %s%%%n&quot;,percent);<br>System.out.println(&quot;Percentage: %s%%%n&quot;+percent+&quot;%&quot;);</pre><p>Output:</p><pre>Percentage: 100%<br>Percentage: 100%<br>Percentage: %s%%%n100%</pre><h3>Interview Tip</h3><p>The format specifiers most commonly used in real projects are:</p><ul><li>%s → String</li><li>%d → int, long</li><li>%f → float, double</li><li>%c → char</li><li>%b → boolean</li><li>%n → newline</li><li>%% → prints %</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dbacaf79802" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String Templates]]></title>
            <link>https://medium.com/@nazeersd.java/string-templates-5dc86b8aff2c?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dc86b8aff2c</guid>
            <category><![CDATA[java-21-features]]></category>
            <category><![CDATA[string-templates]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 18:43:05 GMT</pubDate>
            <atom:updated>2026-06-14T08:32:45.625Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What are String Templates?</h3><p><strong>String Templates</strong> are a <strong>preview feature (Java 21, refined in Java 22)</strong> that allow embedding expressions into strings safely and declaratively.</p><p>Think of it as:</p><pre>String interpolation + validation + processing</pre><h3>2. Problem Before String Templates</h3><p>Before Java 21:</p><h4>String concatenation</h4><pre>String name = &quot;Nazeer&quot;;<br>String s = &quot;Hello &quot; + name;</pre><h4>String.format (unsafe, error-prone)</h4><pre>String s = String.format(&quot;Hello %s&quot;, name);</pre><p>Problems:</p><ul><li>No compile-time validation</li><li>SQL injection risks</li><li>Hard to read for complex strings</li></ul><h3>3. Basic Syntax (Core Concept)</h3><pre>String name = &quot;Nazeer&quot;;<br>String message = STR.&quot;Hello {name}&quot;;</pre><p>STR → template processor<br>\{} → embedded expression</p><h3>4. Key Components</h3><h4>4.1 Template Expression</h4><pre>STR.&quot;Hello {name}&quot;</pre><p>Breakdown:</p><ul><li>STR → processor</li><li>&quot;Hello \{name}&quot; → template</li><li>\{name} → expression</li></ul><h4>4.2 Template Processor</h4><p>Acts like an <strong>interpreter for templates</strong></p><pre>String result = STR.&quot;Value = {10 + 20}&quot;;</pre><p>Output:</p><pre>Value = 30</pre><h3>5. Built-in Processors</h3><h4>5.1 STR (Default)</h4><pre>String s = STR.&quot;Sum = {10 + 20}&quot;;</pre><p>Equivalent to:</p><p>“Sum = “ + (10 + 20);</p><h4>5.2 RAW (Advanced)</h4><pre>StringTemplate template = RAW.&quot;Hello {name}&quot;;</pre><p>Gives:</p><ul><li>fragments</li><li>values</li></ul><p>Used for custom processing</p><h3>6. Multiple Expressions</h3><pre>String name = &quot;Nazeer&quot;;<br>int age = 30;<br>String s = STR.&quot;{name} is {age} years old&quot;;</pre><p>Clean &amp; readable</p><h3>7. Expressions Power (Very Important)</h3><pre>String result = STR.&quot;Square = {Math.pow(5,2)}&quot;;<br>String result = STR.&quot;Upper = {name.toUpperCase()}&quot;;</pre><p>Any Java expression allowed</p><h3>8. Multi-line Templates</h3><pre>String sql = STR.&quot;&quot;&quot;<br>SELECT *<br>FROM users<br>WHERE name = {name}<br>&quot;&quot;&quot;;</pre><p>Combines:</p><ul><li>text blocks</li><li>interpolation</li></ul><h3>9. The Real Power: Custom Processors</h3><p>This is where String Templates shine (interview gold)</p><h3>Example: SQL Injection Safe Processor</h3><pre>StringTemplate.Processor&lt;String, RuntimeException&gt; SQL =<br>template -&gt; {<br>  StringBuilder sb = new StringBuilder();<br>  Iterator&lt;String&gt; fragments = template.fragments().iterator();<br>  Iterator&lt;Object&gt; values = template.values().iterator();<br><br>  while (fragments.hasNext()) {<br>    sb.append(fragments.next());<br>    if (values.hasNext()) {<br>      sb.append(&quot;?&quot;); // replace with placeholder<br>    }<br>  }<br><br>  return sb.toString();<br>};<br><br>String query = SQL.&quot;SELECT * FROM users WHERE name = {name}&quot;;</pre><p>Output:</p><pre>SELECT * FROM users WHERE name = ?</pre><p>Prevents SQL injection</p><h4>Example: Logging Template</h4><pre>var LOG = StringTemplate.Processor.of(<br>template -&gt; template.interpolate()<br>);<br>String msg = LOG.&quot;User {name} logged in at {System.currentTimeMillis()}&quot;;</pre><h3>10. StringTemplate API (Important)</h3><h4>Core Interface</h4><pre>public interface StringTemplate {<br>List&lt;String&gt; fragments();<br>List&lt;Object&gt; values();<br>}</pre><h4>Example</h4><pre>StringTemplate st = RAW.&quot;Hello {name}&quot;;</pre><p>Gives:</p><p>fragments: [“Hello “, “”]</p><p>values: [“Nazeer”]</p><h3>11. Internal Working (Senior-Level Insight)</h3><p>Template:</p><pre>&quot;Hello \{name}&quot;</pre><p>Becomes:</p><ul><li>fragments → [“Hello “, “”]</li><li>values → [name]</li></ul><p>Processor:</p><pre>combine(fragments, values)</pre><h3>12. Security Advantage</h3><h4>Without templates (danger)</h4><pre>String query = &quot;SELECT * FROM users WHERE name = &#39;&quot; + name + &quot;&#39;&quot;;</pre><p>SQL Injection risk</p><h4>With templates + processor</h4><pre>SQL.&quot;SELECT * FROM users WHERE name = {name}&quot;;</pre><p>Safe parameter binding</p><h3>13. Performance Consideration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*-xl1lWzEHheFQXnfR4cz2w.png" /></figure><p>Compiled efficiently → no major overhead</p><h3>14. Limitations (Important)</h3><h4>Preview Feature</h4><ul><li>Java 21 → Preview</li><li>Java 22 → Preview (refined)</li><li>May change in future</li></ul><h4>Must enable preview</h4><p>— enable-preview — release 21</p><h4>Not widely adopted yet</h4><ul><li>Limited framework support</li></ul><h3>15. Real-World Use Cases</h3><h4>1. SQL Queries</h4><pre>SQL.&quot;SELECT * FROM orders WHERE id = {id}&quot;;</pre><h4>2. JSON Building</h4><pre>String json = STR.&quot;&quot;&quot;<br>{<br>&quot;name&quot;: &quot;{name}&quot;,<br>&quot;age&quot;: {age}<br>}<br>&quot;&quot;&quot;;</pre><h4>3. Logging</h4><pre>logger.info(STR.&quot;User {userId} logged in&quot;);</pre><h4>4. REST Responses</h4><pre>return STR.&quot;Hello {user.getName()}&quot;;</pre><h3>16. Comparison</h3><h4>String Templates vs String.format</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*IKNRfwwZkxmwEBPq8bee9w.png" /></figure><h4>Template vs Concatenation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*hhFrQQhw3BUa5UKGSmZ_Ug.png" /></figure><h3>17. Best Practices (Architect Level)</h3><h4>1. Use STR for simple interpolation</h4><p>STR.”Hello {name}”</p><h4>2. Use custom processors for security-critical code</h4><ul><li>SQL</li><li>HTML</li><li>Logging</li></ul><h4>3. Avoid business logic inside templates</h4><p>// Bad</p><pre>STR.&quot;{user.calculateSalary()}&quot;</pre><p>// Better</p><pre>var salary = user.calculateSalary();<br>STR.&quot;Salary: {salary}&quot;</pre><h4>4. Use with Text Blocks for DSLs</h4><h3>18. Interview Questions</h3><h4>What problem do String Templates solve?</h4><p>Safe, readable, extensible string interpolation</p><h4>Difference between STR and RAW?</h4><p>STRRAWReturns StringReturns StringTemplateImmediate processingDeferred processing</p><h4>Are String Templates safe by default?</h4><p>Only with a proper processor</p><h4>Can we replace String.format?</h4><p>Mostly yes (cleaner + safer)</p><h3>19. Future Direction</h3><ul><li>Likely stable in upcoming Java versions</li><li>Integration with:</li><li>SQL APIs</li><li>JSON libraries</li><li>Logging frameworks</li></ul><h3>Final Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*uM-qvdqbuSPy74dnfPJwAg.png" /></figure><h3>Architect-Level Insight</h3><p>String Templates are not just interpolation. They introduce:</p><pre>String + Data + Processor = Safe DSL Engine</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dc86b8aff2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Concurrency]]></title>
            <link>https://medium.com/@nazeersd.java/structured-concurrency-1154d81ca20f?source=rss-9b1e6e0255e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1154d81ca20f</guid>
            <category><![CDATA[java-21-features]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <dc:creator><![CDATA[Syed Nazeer]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 18:42:36 GMT</pubDate>
            <atom:updated>2026-06-08T18:42:36.497Z</atom:updated>
            <content:encoded><![CDATA[<h4>Structured Concurrency in Java (Everything You Need to Know)</h4><p><strong>Structured Concurrency</strong> is a modern concurrency model introduced as a preview feature in Java (starting with Java 21) to simplify managing multiple concurrent tasks.</p><p>It is part of the effort led by Ron Pressler under OpenJDK’s Project Loom.</p><h4>Why Was Structured Concurrency Introduced?</h4><p>Traditional Java concurrency has several problems:</p><pre>ExecutorService executor = Executors.newFixedThreadPool(2);</pre><pre>Future&lt;User&gt; userFuture = executor.submit(this::getUser);<br>Future&lt;Order&gt; orderFuture = executor.submit(this::getOrders);</pre><pre>User user = userFuture.get();<br>Order order = orderFuture.get();</pre><p>Problems:</p><ol><li>Tasks are not related logically.</li><li>If one task fails, the other keeps running.</li><li>Cancellation is difficult.</li><li>Resource leaks are possible.</li><li>Debugging becomes harder.</li></ol><p>Structured Concurrency treats related concurrent tasks as a <strong>single unit of work</strong>.</p><h4>Real-World Example</h4><p>Suppose an API endpoint needs:</p><pre>GET /dashboard</pre><p>To build the response it needs:</p><ul><li>User Profile Service</li><li>Order Service</li><li>Recommendation Service</li></ul><p>Instead of:</p><pre>Future&lt;User&gt; user;<br>Future&lt;Orders&gt; orders;<br>Future&lt;Recommendations&gt; recs;</pre><p>You create a task scope:</p><pre>Dashboard Request<br>│<br>├── User Service<br>├── Order Service<br>└── Recommendation Service</pre><p>All child tasks belong to the parent request.</p><h4>Core Class</h4><p>Java provides:</p><pre>StructuredTaskScope</pre><p>Package:</p><pre>java.util.concurrent</pre><h4>Basic Example</h4><pre>try (var scope =<br>        new StructuredTaskScope.ShutdownOnFailure()) {</pre><pre>    Subtask&lt;String&gt; user =<br>            scope.fork(() -&gt; fetchUser());</pre><pre>    Subtask&lt;String&gt; orders =<br>            scope.fork(() -&gt; fetchOrders());</pre><pre>    scope.join();<br>    scope.throwIfFailed();</pre><pre>    System.out.println(user.get());<br>    System.out.println(orders.get());<br>}</pre><h4>What Happens Internally?</h4><h4>fork()</h4><p>Creates a child task.</p><pre>scope.fork(() -&gt; fetchUser());</pre><p>Think of it as:</p><pre>Parent Task<br>   |<br>   +--&gt; Child Task</pre><h4>join()</h4><p>Waits for all child tasks.</p><pre>scope.join();</pre><p>Equivalent conceptually to:</p><pre>future1.get();<br>future2.get();<br>future3.get();</pre><p>but managed as a group.</p><h4>throwIfFailed()</h4><p>Checks whether any child task failed.</p><pre>scope.throwIfFailed();</pre><p>If any child throws an exception:</p><pre>RuntimeException<br>IOException<br>SQLException</pre><p>It rethrows it.</p><h4>ShutdownOnFailure</h4><p>Most commonly used scope.</p><pre>StructuredTaskScope.ShutdownOnFailure</pre><p>Behavior:</p><pre>Task A -&gt; Success<br>Task B -&gt; Failure<br>Task C -&gt; Running</pre><p>When B fails:</p><pre>Task C gets cancelled<br>Scope terminates<br>Exception propagated</pre><p>This prevents wasted work.</p><h4>Example</h4><pre>try (var scope =<br>        new StructuredTaskScope.ShutdownOnFailure()) {</pre><pre>    var user =<br>        scope.fork(() -&gt; getUser());</pre><pre>    var payment =<br>        scope.fork(() -&gt; getPayment());</pre><pre>    scope.join();<br>    scope.throwIfFailed();</pre><pre>    return combine(user.get(), payment.get());<br>}</pre><p>If payment fails:</p><pre>User task cancelled<br>Request fails immediately</pre><h4>ShutdownOnSuccess</h4><p>Another built-in policy.</p><pre>StructuredTaskScope.ShutdownOnSuccess</pre><p>Used when you only need the first successful result.</p><p>Example:</p><pre>Search Google<br>Search Bing<br>Search Yahoo</pre><p>Return whichever responds first.</p><pre>try (var scope =<br>        new StructuredTaskScope.ShutdownOnSuccess&lt;String&gt;()) {</pre><pre>    scope.fork(() -&gt; searchA());<br>    scope.fork(() -&gt; searchB());<br>    scope.fork(() -&gt; searchC());</pre><pre>    scope.join();</pre><pre>    return scope.result();<br>}</pre><h3>Comparison with CompletableFuture</h3><h4>CompletableFuture</h4><pre>CompletableFuture&lt;User&gt; user =<br>    supplyAsync(this::getUser);</pre><pre>CompletableFuture&lt;Order&gt; order =<br>    supplyAsync(this::getOrder);</pre><pre>return user.thenCombine(order, Dashboard::new);</pre><p>Problems:</p><ul><li>Complex chains</li><li>Hard cancellation</li><li>Task relationships are implicit</li><li>Stack traces can be difficult</li></ul><h4>Structured Concurrency</h4><pre>try (var scope =<br>        new StructuredTaskScope.ShutdownOnFailure()) {</pre><pre>    var user = scope.fork(this::getUser);<br>    var order = scope.fork(this::getOrder);</pre><pre>    scope.join();<br>    scope.throwIfFailed();</pre><pre>    return new Dashboard(<br>            user.get(),<br>            order.get());<br>}</pre><p>Advantages:</p><ul><li>Readable</li><li>Easier debugging</li><li>Better cancellation</li><li>Clear parent-child relationship</li></ul><h4>Relationship with Virtual Threads</h4><p>Structured Concurrency works extremely well with:</p><p>Virtual Threads</p><p>Example:</p><pre>Thread.ofVirtual().start(...);</pre><p>Every forked task can run in a virtual thread.</p><p>Benefits:</p><pre>Thousands of tasks<br>Low memory usage<br>Simple programming model</pre><h4>Hierarchical Task Management</h4><p>Without Structured Concurrency:</p><pre>Thread A<br>Thread B<br>Thread C<br>Thread D</pre><p>No relationship.</p><p>With Structured Concurrency:</p><pre>Dashboard Request<br>│<br>├── User Task<br>├── Order Task<br>└── Recommendation Task</pre><p>Like a tree structure.</p><p>When the parent ends:</p><pre>Children end<br>Resources released</pre><h4>Timeout Example</h4><pre>try (var scope =<br>        new StructuredTaskScope.ShutdownOnFailure()) {</pre><pre>    var user = scope.fork(this::getUser);</pre><pre>    scope.joinUntil(<br>            Instant.now().plusSeconds(2));</pre><pre>    scope.throwIfFailed();</pre><pre>    return user.get();<br>}</pre><p>If the timeout is reached:</p><pre>Task cancelled<br>Timeout exception thrown</pre><h3>Production Use Cases</h3><h4>1. API Aggregation</h4><pre>Frontend Request<br>│<br>├── User Service<br>├── Product Service<br>└── Pricing Service</pre><p>Very common in microservices.</p><h4>2. Parallel Database Queries</h4><pre>Customer<br>Orders<br>Invoices</pre><p>Fetch simultaneously.</p><h4>3. Search Systems</h4><pre>ElasticSearch Cluster 1<br>ElasticSearch Cluster 2<br>ElasticSearch Cluster 3</pre><p>Take the first successful result.</p><h4>4. Multi-region Calls</h4><pre>India Region<br>US Region<br>Europe Region</pre><p>Return the fastest response.</p><h3>Interview Questions</h3><h4>What is Structured Concurrency?</h4><p>A concurrency model where related tasks are grouped into a single scope and managed as one unit.</p><h4>Why is it better than ExecutorService?</h4><ul><li>Automatic cancellation</li><li>Better error propagation</li><li>Clear lifecycle management</li><li>Parent-child task relationship</li></ul><h4>Difference between StructuredTaskScope and CompletableFuture?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R64y0wfmhcXIPAE1bdiQkg.png" /></figure><h4>Difference between ShutdownOnFailure and ShutdownOnSuccess?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_wGuSsojxqhFL6ZbIMQkw.png" /></figure><h4>Important Version Information</h4><p>Structured Concurrency has been evolving through multiple preview/incubator releases in Java. If you’re preparing for interviews on <strong>Java 21+</strong>, focus on:</p><ul><li>StructuredTaskScope</li><li>fork()</li><li>join()</li><li>throwIfFailed()</li><li>ShutdownOnFailure</li><li>ShutdownOnSuccess</li><li>Integration with Virtual Threads</li></ul><p>These are the concepts most commonly discussed in modern Java backend interviews, especially for senior developers working with microservices and Project Loom features.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1154d81ca20f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>