<?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 TARA RAM GOYAL on Medium]]></title>
        <description><![CDATA[Stories by TARA RAM GOYAL on Medium]]></description>
        <link>https://medium.com/@tararamgoyal4_92353?source=rss-30b35ab11904------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qjRW7AYsMecSGd0-eEgTlA.jpeg</url>
            <title>Stories by TARA RAM GOYAL on Medium</title>
            <link>https://medium.com/@tararamgoyal4_92353?source=rss-30b35ab11904------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:53:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tararamgoyal4_92353/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[Filter vs Interceptor vs Spring AOP in Spring Boot: The Only Guide You’ll Ever Need]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/filter-vs-interceptor-vs-spring-aop-in-spring-boot-the-only-guide-youll-ever-need-b668774f2055?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/b668774f2055</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[back-interview]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-07-27T02:31:01.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtMO8DaFtvMsXvs0-NC7Tg.png" /></figure><h4>Execution Flow • Internal Working • Real-World Examples • Best Practices • Interview Questions</h4><blockquote><strong>“If you can’t explain the difference between a Filter, an Interceptor, and Spring AOP in under two minutes, you’re probably not interview-ready.”</strong></blockquote><p>This is one of those Spring Boot topics that almost every Java developer encounters — whether during an interview, while debugging an application, or when designing a production system.</p><h4>Why Does Spring Boot Have Three Different Mechanisms?</h4><p>At first glance, all three seem to do the same thing.</p><p>They can all execute code before or after your application logic.</p><p><strong>They operate at different layers of your application.</strong></p><p>Layer Responsibility Spring Component</p><p><em>HTTP Infrastructure Process raw HTTP requests Filter Spring MVC Process controller requests Interceptor Business Layer Reusable business concerns Spring AOP</em></p><h4>The Complete Request Lifecycle</h4><pre>HTTP Request<br>      │<br>      ▼<br>Servlet Container<br>      │<br>      ▼<br>Filter<br>      │<br>      ▼<br>DispatcherServlet<br>      │<br>      ▼<br>Interceptor (preHandle)<br>      │<br>      ▼<br>Controller<br>      │<br>      ▼<br>Spring AOP Proxy<br>      │<br>      ▼<br>Service<br>      │<br>      ▼<br>Repository<br>      │<br>      ▼<br>Database</pre><h4>1. Filter — The First Line of Defense</h4><p>A <strong>Filter</strong> belongs to the <strong>Servlet API</strong> and executes <strong>before Spring MVC</strong>.</p><h4>Responsibilities</h4><ul><li>JWT Authentication</li><li>CORS</li><li>Character Encoding</li><li>Request Logging</li><li>Response Compression</li><li>XSS Protection</li><li>Request Wrapping</li></ul><h4>Advantages</h4><ul><li>Runs before Spring MVC</li><li>Can modify Request and Response</li><li>Framework independent</li><li>Ideal for infrastructure concerns</li></ul><h4>Limitations</h4><ul><li>Doesn’t know which controller will execute</li><li>Cannot access HandlerMethod</li><li>Not suitable for business logic</li></ul><h4>2. Interceptor — The Controller Gatekeeper</h4><p>An <strong>Interceptor</strong> executes around controller execution.</p><pre>preHandle()<br>   ↓<br>Controller<br>   ↓<br>postHandle()<br>   ↓<br>View Rendering<br>   ↓<br>afterCompletion()</pre><h4>Common Use Cases</h4><ul><li>Authorization</li><li>Audit Logging</li><li>API Metrics</li><li>Request Timing</li><li>Locale Switching</li><li>User Activity Tracking</li></ul><h4>Advantages</h4><ul><li>Access to controller metadata</li><li>Easy integration with Spring MVC</li></ul><h4>Limitations</h4><ul><li>Spring MVC only</li><li>Cannot intercept service methods</li></ul><h4>3. Spring AOP — The Cross-Cutting Expert</h4><p>Spring AOP intercepts <strong>Spring Bean methods</strong> to implement reusable cross-cutting concerns.</p><h4>Common Use Cases</h4><ul><li>Logging</li><li>Transactions</li><li>Retry</li><li>Performance Monitoring</li><li>Caching</li><li>Exception Handling</li></ul><h4>Advice Types</h4><ul><li>@Before</li><li>@After</li><li>@AfterReturning</li><li>@AfterThrowing</li><li>@Around</li></ul><h4>Quick Comparison</h4><p>Feature Filter Interceptor Spring AOP</p><p>Layer Servlet Spring MVC Spring Bean HTTP Request ✅ ✅ ❌ Controller Access ❌ ✅ Indirect Service Access ❌ ❌ ✅ Modify Request ✅ Limited ❌ Business Logic ❌ ❌ ✅ Executes First ✅ ❌ ❌</p><h4>When Should You Use Which?</h4><p>Requirement Best Choice</p><p>JWT Authentication Filter CORS Filter Authorization Interceptor Audit Logging Interceptor Transactions Spring AOP Performance Monitoring Spring AOP Retry Mechanism Spring AOP Caching Spring AOP</p><h4>Common Interview Questions</h4><h4>Which executes first?</h4><p><strong>Filter → Interceptor → Controller → AOP → Service</strong></p><h4>Can Spring AOP replace Filters?</h4><p>No. Filters process raw HTTP requests before Spring MVC, while AOP intercepts Spring Bean methods.</p><h4>Can an Interceptor replace a Filter?</h4><p>Not completely. Infrastructure concerns like CORS, request wrapping, and encoding belong in Filters.</p><h4>Which should I use for JWT authentication?</h4><p><strong>Filter</strong></p><h4>Which advice is used most frequently?</h4><p><strong>@Around</strong></p><h3>Memory Trick</h3><pre>🌐 HTTP Layer<br>      │<br>   Filter<br>      │<br>🎮 Controller Layer<br>      │<br>Interceptor<br>      │<br>⚙ Business Layer<br>      │<br>Spring AOP</pre><blockquote><strong><em>Filter = HTTP</em></strong><em><br></em><strong><em>Interceptor = Controller</em></strong><em><br></em><strong><em>Spring AOP = Business Logic</em></strong></blockquote><p>If you want to read a one-page infographic interview guide, you can refer to my <a href="https://www.linkedin.com/in/tararamgoyal/">LinkedIn </a>post</p><h4>Final Thoughts</h4><p>Filters, Interceptors, and Spring AOP are complementary tools, each designed for a specific layer of your application. Understanding their responsibilities and execution order will help you design cleaner applications and confidently answer Spring Boot interview questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b668774f2055" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Fish Tagging in Java Logging: A Comprehensive Guide]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/the-power-of-fish-tagging-in-java-logging-a-comprehensive-guide-aa8b936d7ae7?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa8b936d7ae7</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[structured-logging]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 04:50:01 GMT</pubDate>
            <atom:updated>2025-08-17T04:50:01.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVqkcteWbrjWDyxrGPGeng.png" /></figure><h4>Introduction</h4><p>In today’s distributed systems, understanding the flow of a request across services is crucial. Fish tagging, or contextual logging, is a powerful technique that helps developers trace and debug applications by adding contextual information to log statements. As a Java professional with 5+ years of experience, I’ve seen how proper logging strategies can make or break an application’s maintainability.</p><h4>Why Do We Need Fish Tagging?</h4><p>In a typical enterprise application:</p><ul><li>Multiple users interact with the system simultaneously</li><li>A single request might span multiple services</li><li>Asynchronous processing is common</li><li>Debugging without context is like finding a needle in a haystack</li></ul><p>Without contextual information, logs are nearly impossible to correlate, making debugging a headache.</p><h4>The Importance of Fish Tagging</h4><ol><li><strong>Enhanced Debugging</strong>: Quickly identify all logs related to a specific request</li><li><strong>Performance Analysis</strong>: Track request flow across service boundaries</li><li><strong>Audit Compliance</strong>: Maintain proper audit trails for security and compliance</li><li><strong>Operational Visibility</strong>: Gain insights into application behavior in production</li><li><strong>Reduced MTTR</strong>: Faster incident resolution with better context</li></ol><h4>MDC vs ThreadContext: The Showdown</h4><blockquote>Mapped Diagnostic Context (MDC)</blockquote><ul><li>Part of SLF4J/Logback</li><li>Thread-bound by default</li><li>Simple key-value storage</li><li>Automatically inherits values to child threads (with proper configuration)</li><li>Lighter weight</li></ul><blockquote>ThreadContext (Log4j2)</blockquote><ul><li>Part of Log4j2</li><li>More feature-rich than MDC</li><li>Supports three types of context: Thread, Stack, and Global</li><li>Better for complex scenarios with nested contexts</li><li>More configuration options</li></ul><h4>When to Use Which?</h4><ol><li>Use <strong>MDC</strong> for simple request-scoped context in SLF4J/Logback</li><li>Use <strong>ThreadContext</strong> if you need advanced features or are using Log4j2 directly</li></ol><h4>Tech Stack for Our Implementation</h4><ol><li><strong>Java 17</strong>: For modern Java features</li><li><strong>Spring Boot 3.4.0</strong>: As our application framework</li><li><strong>Log4j2</strong>: For advanced logging capabilities</li><li><strong>Maven</strong>: For dependency management</li><li><strong>JWT</strong>: For authentication (to demonstrate user context)</li></ol><h4>Project Structure</h4><p>src/main/java/com/codisthan/<br>├── configuration/<br>│ ├── JwtAuthenticationFilter.java<br>│ ├── SecurityConfiguration.java<br>│ └── LoggingConfig.java<br>├── controller/<br>│ └── ApiController.java<br>├── service/<br>│ └── BusinessService.java<br>├── dto/<br>│ └── ApiResponse.java<br>└── FishTaggingApplication.java</p><p>src/main/resources/<br>├── application.properties<br>└── log4j2.xml</p><p><strong>Add Dependencies to `<em>pom.xml</em>`</strong></p><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-data-jpa&lt;/artifactId&gt;<br>            &lt;exclusions&gt;<br>                &lt;exclusion&gt;<br>                    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>                    &lt;artifactId&gt;spring-boot-starter-logging&lt;/artifactId&gt;<br>                &lt;/exclusion&gt;<br>            &lt;/exclusions&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-security&lt;/artifactId&gt;<br>        &lt;/dependency&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>        &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;/dependency&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;/dependency&gt;<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;exclusions&gt;<br>                &lt;exclusion&gt;<br>                    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>                    &lt;artifactId&gt;spring-boot-starter-logging&lt;/artifactId&gt;<br>                &lt;/exclusion&gt;<br>            &lt;/exclusions&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-log4j2&lt;/artifactId&gt;<br>        &lt;/dependency&gt;</pre><h4>Configure Log4j2 Pattern</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;Configuration status=&quot;WARN&quot;&gt;<br>    &lt;Properties&gt;<br>        &lt;Property name=&quot;LOG_PATTERN&quot;&gt;%d{yyyy-MM-dd HH:mm:ss:SSS} [%t] %notEmpty{[%X{username}, %X{requestId}]} %-5p %c : %m%n<br>        &lt;/Property&gt;<br>        &lt;Property name=&quot;APP_LOG_ROOT&quot;&gt;logs&lt;/Property&gt;<br>    &lt;/Properties&gt;<br>    &lt;Appenders&gt;<br>        &lt;Console name=&quot;Console&quot; target=&quot;SYSTEM_OUT&quot;&gt;<br>            &lt;PatternLayout pattern=&quot;${LOG_PATTERN}&quot;/&gt;<br>        &lt;/Console&gt;<br><br>        &lt;RollingFile name=&quot;RollingFile&quot; fileName=&quot;${APP_LOG_ROOT}/app.log&quot;<br>                     filePattern=&quot;${APP_LOG_ROOT}/app-%d{yyyyMMdd}-%i.log.gz&quot;&gt;<br>            &lt;PatternLayout pattern=&quot;${LOG_PATTERN}&quot;/&gt;<br>            &lt;Policies&gt;<br>                &lt;SizeBasedTriggeringPolicy size=&quot;20MB&quot;/&gt;<br>            &lt;/Policies&gt;<br>            &lt;DefaultRolloverStrategy max=&quot;10&quot;/&gt;<br>        &lt;/RollingFile&gt;<br>    &lt;/Appenders&gt;<br>    &lt;Loggers&gt;<br>        &lt;SpringProfile name=&quot;dev&quot;&gt;<br>            &lt;Logger name=&quot;org.hibernate&quot; level=&quot;info&quot;/&gt;<br>            &lt;Logger name=&quot;org.hibernate.SQL&quot; level=&quot;debug&quot;/&gt;<br>            &lt;Logger name=&quot;org.hibernate.type.descriptor.sql&quot; level=&quot;trace&quot;/&gt;<br>            &lt;Root level=&quot;info&quot;&gt;<br>                &lt;AppenderRef ref=&quot;Console&quot;/&gt;<br>                &lt;AppenderRef ref=&quot;RollingFile&quot;/&gt;<br>            &lt;/Root&gt;<br>        &lt;/SpringProfile&gt;<br><br>    &lt;/Loggers&gt;<br>&lt;/Configuration&gt;</pre><p><strong><em>Note: If you have trouble understanding the log4j2 file, don’t worry; I will. In another blog article, I’ll go over logging and the log4j2.xml file.</em></strong></p><h4>JWT Authentication Filter with Context</h4><pre>package com.codisthan.configuration;<br><br>import com.codisthan.service.impl.ApplicationUserDetailService;<br>import com.codisthan.service.impl.JwtService;<br>import jakarta.servlet.FilterChain;<br>import jakarta.servlet.ServletException;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletResponse;<br>import org.apache.logging.log4j.ThreadContext;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.lang.NonNull;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.Authentication;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.filter.OncePerRequestFilter;<br>import org.springframework.web.servlet.HandlerExceptionResolver;<br><br>import java.io.IOException;<br><br>/**<br> * @author codisthan<br> * Created By: TararamGoyal<br> * Date: 15-08-2025<br> * Time: 18:26<br> * Project Name: fish-tagging<br> */<br>@Component<br>public class JwtAuthenticationFilter extends OncePerRequestFilter {<br><br><br>    private final HandlerExceptionResolver handlerExceptionResolver;<br>    private final JwtService jwtService;<br>    private final ApplicationUserDetailService applicationUserDetailService;<br><br>    @Autowired<br>    public JwtAuthenticationFilter(JwtService jwtService, ApplicationUserDetailService applicationUserDetailService, HandlerExceptionResolver handlerExceptionResolver) {<br>        this.jwtService = jwtService;<br>        this.applicationUserDetailService = applicationUserDetailService;<br>        this.handlerExceptionResolver = handlerExceptionResolver;<br>    }<br><br>    @Override<br>    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {<br>        final String authHeader = request.getHeader(&quot;Authorization&quot;);<br>         <br>        String requestId = request.getHeader(&quot;X-Request-ID&quot;);<br>        if (requestId == null || requestId.isEmpty()) {<br>            requestId = UUID.randomUUID().toString();<br>        }<br>        <br>        // adding requestId<br>        ThreadContext.put(&quot;requestId&quot;, requestId);<br><br>        if (authHeader == null || !authHeader.startsWith(&quot;Bearer &quot;)) {<br>            filterChain.doFilter(request, response);<br><br>            return;<br>        }<br><br>        try {<br>            final String jwt = authHeader.substring(7);<br>            final String username= jwtService.extractUsername(jwt);<br>            //adding username<br>            ThreadContext.put(&quot;username&quot;, username);<br>            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();<br><br>            if (userEmail != null &amp;&amp; authentication == null) {<br>                UserDetails userDetails = applicationUserDetailService.loadUserByUsername(userEmail);<br><br>                if (jwtService.isTokenValid(jwt, userDetails)) {<br>                    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());<br>                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));<br>                    SecurityContextHolder.getContext().setAuthentication(authToken);<br>                }<br>            }<br><br>            //filterChain.doFilter(request, response);<br>        } catch (Exception exception) {<br>            handlerExceptionResolver.resolveException(request, response, null, exception);<br>        }<br>        filterChain.doFilter(request, response);<br>        ThreadContext.clearMap();<br>    }<br><br>}</pre><h4>Sample Controller</h4><pre>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class ApiController {<br>    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);<br>    <br>    @GetMapping(&quot;/data&quot;)<br>    public ResponseEntity&lt;ApiResponse&gt; getData() {<br>        logger.info(&quot;Fetching data for user&quot;);<br>        // Your business logic here<br>        return ResponseEntity.ok(new ApiResponse(&quot;Data retrieved successfully&quot;));<br>    }<br>    <br>    @PostMapping(&quot;/process&quot;)<br>    public ResponseEntity&lt;ApiResponse&gt; processData(@RequestBody String data) {<br>        logger.info(&quot;Processing data: {}&quot;, data);<br>        // Your business logic here<br>        return ResponseEntity.ok(new ApiResponse(&quot;Data processed successfully&quot;));<br>    }<br>}</pre><h4>Sample Log Output</h4><pre>2025-08-17 14:30:45.123 [http-nio-8080-exec-1] INFO  c.c.controller.ApiController [goyal.tara,550e8400-e29b-41d4-a716-446655440000] - Fetching data for user<br>2025-08-17 14:30:45.124 [http-nio-8080-exec-1] INFO  c.c.controller.ApiController [goyal.tara,550e8400-e29b-41d4-a716-446655440000] - Completed request processing</pre><h3>How Fish Tagging Improves Log Analysis</h3><p>Fish tagging transforms raw logs into meaningful, actionable data. Here’s how it enhances log analysis:</p><h4><strong><em>Correlation of Distributed Traces</em></strong></h4><ul><li><strong>End-to-End Visibility</strong>: Track a single user request across microservices</li><li><strong>Distributed Transaction Monitoring</strong>: Follow business transactions that span multiple services</li><li><strong>Dependency Analysis</strong>: Understand service dependencies through request flow</li></ul><h4><strong><em>Enhanced Debugging Capabilities</em></strong></h4><ul><li><strong>Contextual Filtering</strong>: Filter logs by user, session, or request ID</li><li><strong>Temporal Analysis</strong>: Correlate logs with specific timeframes or events</li><li><strong>Pattern Recognition</strong>: Identify recurring issues through tagged patterns</li></ul><h4><strong><em>Performance Optimization</em></strong></h4><ul><li><strong>Bottleneck Identification</strong>: Spot slow operations by tracking request duration</li><li><strong>Resource Utilization</strong>: Correlate system metrics with specific user actions</li><li><strong>Capacity Planning</strong>: Understand usage patterns for better resource allocation</li></ul><h4><strong><em>Security and Compliance</em></strong></h4><ul><li><strong>Audit Trails</strong>: Maintain clear records of user actions</li><li><strong>Anomaly Detection</strong>: Identify suspicious patterns through tagged user activities</li><li><strong>Regulatory Compliance</strong>: Meet requirements for data access logging</li></ul><h4><strong><em>Operational Intelligence</em></strong></h4><ul><li><strong>User Journey Mapping</strong>: Understand how users navigate through the system</li><li><strong>Error Rate Analysis</strong>: Calculate error rates by user, service, or feature</li><li><strong>A/B Testing</strong>: Compare performance across different user segments</li></ul><h4><strong><em>Advanced Analytics Integration</em></strong></h4><ul><li><strong>Machine Learning</strong>: Feed tagged logs into ML models for predictive analysis</li><li><strong>Business Metrics</strong>: Correlate technical logs with business KPIs</li><li><strong>Root Cause Analysis</strong>: Quickly trace issues back to their source</li></ul><blockquote>Example: Analyzing Performance Issues</blockquote><pre>-- Find slowest requests by user<br>SELECT <br>    mdc:userId as user,<br>    mdc:requestId as request,<br>    avg(duration) as avg_duration_ms<br>FROM logs<br>WHERE <br>    logger = &#39;com.example.ApiController&#39; <br>    AND level = &#39;INFO&#39;<br>    AND message LIKE &#39;Processing request%&#39;<br>GROUP BY mdc:userId, mdc:requestId<br>ORDER BY avg_duration_ms DESC<br>LIMIT 10;</pre><h4>Best Practices for Fish Tagging</h4><ol><li><strong>Keep Context Minimal</strong>: Only store what you need for debugging</li><li><strong>Clear Context</strong>: Always clear context in finally blocks</li><li><strong>Use Meaningful Keys</strong>: Make keys self-documenting</li><li><strong>Consider Performance</strong>: Be mindful of the context size</li><li><strong>Standardize</strong>: Use consistent context keys across services</li><li><strong>Security</strong>: Never log sensitive information</li></ol><h4>Advanced: Asynchronous Processing</h4><p>For async operations, you need to pass the context explicitly:</p><pre>@Async<br>public CompletableFuture&lt;Void&gt; asyncProcess() {<br>    // Copy context at the start<br>    Map&lt;String, String&gt; context = ThreadContext.getImmutableContext();<br>    <br>    return CompletableFuture.runAsync(() -&gt; {<br>        try {<br>            // Set the context in the async thread<br>            ThreadContext.putAll(context);<br>            logger.info(&quot;Processing in async thread&quot;);<br>            // Your async logic<br>        } finally {<br>            ThreadContext.clearAll();<br>        }<br>    });<br>}</pre><h3>Conclusion</h3><p>Fish tagging is an essential technique for modern Java applications. By implementing proper contextual logging, you’ll significantly improve your ability to debug and monitor applications in production. The small investment in setting up proper logging patterns pays huge dividends when troubleshooting complex issues.</p><p>Remember, the key to effective logging is consistency. Choose an approach (MDC or ThreadContext) and stick with it across your services for maximum benefit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa8b936d7ae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testcontainers: Simplifying Integration Testing in Java with Spring Boot]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/testcontainers-simplifying-integration-testing-in-java-with-spring-boot-57fdc6b1c670?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/57fdc6b1c670</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 09:21:16 GMT</pubDate>
            <atom:updated>2025-08-16T09:21:16.113Z</atom:updated>
            <content:encoded><![CDATA[<p>I’d be happy to help you write integration tests using Testcontainers and show you how it makes a Java developer’s life easier!</p><p>Integration testing is crucial for modern applications, especially those interacting with databases and external services. Traditionally, setting up test environments was cumbersome, error-prone, and hard to maintain. Testcontainers solves this by providing lightweight, disposable containers for your tests, making integration testing reliable and repeatable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8enDppVNlqS7eC9hcy8IsA.png" /></figure><h4>What is Testcontainers?</h4><p><em>Testcontainers is a Java library that lets you spin up Docker containers directly from your test code. It’s perfect for testing with real databases, message brokers, or any service that can run in a container.</em></p><h4>Why Use Testcontainers?</h4><ol><li>Isolation: Each test runs in a fresh environment.</li><li>Consistency: Tests behave the same on any machine.</li><li>Automation: No manual setup or teardown required.</li><li>Realism: Tests use real services, not mocks or in-memory alternatives.</li></ol><p><strong>Integrating Testcontainers in a Spring Boot Project</strong><br>Let’s see how you can use Testcontainers in a Spring Boot project, referencing the setup from our <strong>pom.xml</strong>.</p><ol><li>Add Dependencies<br>Your pom.xml should include</li></ol><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-testcontainers&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>   &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>   &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;Write a Test Using Testcontainers<br>Here’s a sample JUnit test that starts a PostgreSQL container and injects its connection details into Spring Boot</pre><p>2. Write a Test Using Testcontainers<br>Here’s a sample JUnit test that starts a PostgreSQL container and injects its connection details into Spring Boot:</p><pre>package com.codisthan.controller;<br><br>import com.codisthan.dto.ProductDTO;<br>import com.codisthan.service.ProductService;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.DeleteMapping;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PathVariable;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.PutMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import java.util.List;<br><br>/**<br> * Author: Codisthan<br> * Created By: Tara Ram<br> * Date: 14-08-2025<br> * Time: 17:40<br> * Project Name: TestContainer<br> */<br>@RestController<br>@RequestMapping(&quot;/products&quot;)<br>public class ProductController {<br><br>    private final ProductService service;<br><br>    public ProductController(ProductService service) {<br>        this.service = service;<br>    }<br><br>    @PostMapping<br>    public ResponseEntity&lt;ProductDTO&gt; addProduct(@RequestBody ProductDTO dto) {<br>        return new ResponseEntity&lt;&gt;(service.addProduct(dto), HttpStatus.CREATED);<br>    }<br><br><br>    @PutMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;ProductDTO&gt; updateProduct(@PathVariable(&quot;id&quot;) int id, @RequestBody ProductDTO dto) {<br>        return new ResponseEntity&lt;&gt;(service.updateProduct(id, dto), HttpStatus.OK);<br>    }<br><br><br>    @GetMapping<br>    public ResponseEntity&lt;List&lt;ProductDTO&gt;&gt; getProducts() {<br>        return new ResponseEntity&lt;&gt;(service.getProducts(), HttpStatus.OK);<br>    }<br><br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;ProductDTO&gt; getProduct(@PathVariable(&quot;id&quot;) int id) {<br>        return new ResponseEntity&lt;&gt;(service.getProduct(id), HttpStatus.OK);<br>    }<br><br>    @DeleteMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;?&gt; deleteProduct(@PathVariable(&quot;id&quot;) int id) {<br>        service.deleteProduct(id);<br>        return new ResponseEntity&lt;&gt;(HttpStatus.OK);<br>    }<br>}</pre><pre>package com.codisthan.controller;<br><br>import com.codisthan.dto.ProductDTO;<br>import com.codisthan.repository.ProductRepository;<br>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.boot.test.web.client.TestRestTemplate;<br>import org.springframework.boot.testcontainers.service.connection.ServiceConnection;<br>import org.springframework.http.HttpEntity;<br>import org.springframework.http.HttpMethod;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.test.context.jdbc.Sql;<br>import org.testcontainers.containers.PostgreSQLContainer;<br>import org.testcontainers.junit.jupiter.Container;<br>import org.testcontainers.junit.jupiter.Testcontainers;<br><br>import java.util.List;<br><br>import static org.assertj.core.api.Assertions.assertThat;<br>/**<br> * Author: Codisthan<br> * Created By: Tara Ram<br> * Date: 14-08-2025<br> * Time: 17:45<br> * Project Name: TestContainer<br> */<br><br>@Testcontainers<br>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)<br>@Sql(statements = {<br>        &quot;INSERT INTO product ( name, description, price) VALUES ( &#39;Laptop&#39;, &#39;Dell XPS&#39;, 78000.00)&quot;<br>})<br>class ProductControllerIntTest {<br><br>    @Container<br>    @ServiceConnection<br>    static PostgreSQLContainer&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;(&quot;postgres:16.0&quot;);<br><br>    @Autowired<br>    TestRestTemplate restTemplate;<br><br>    @Autowired<br>    ProductRepository repository;<br><br>    private String baseUrl = &quot;/products&quot;;<br><br><br>    @Test<br>    void connectionEstablished() {<br>        assertThat(postgres.isCreated()).isTrue();<br>        assertThat(postgres.isRunning()).isTrue();<br>    }<br><br><br>    @Test<br>    void shouldCreateNewProductWhenProductIsValid() {<br>        ProductDTO productDTO = new ProductDTO(0, &quot;Notebook&quot;, &quot;Classmate note book&quot;, 35.0);<br>        ResponseEntity&lt;ProductDTO&gt; response = restTemplate.exchange(baseUrl, HttpMethod.POST, new HttpEntity&lt;ProductDTO&gt;(productDTO), ProductDTO.class);<br>        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);<br>        assertThat(response.getBody()).isNotNull();<br>        assertThat(response.getBody().name()).isEqualTo(&quot;Notebook&quot;);<br>    }<br><br>    @Test<br>    void shouldUpdateProductWhenProductIsValid() {<br>        ProductDTO updated = new ProductDTO(1, &quot;Laptop&quot;, &quot;Dell Laptop&quot;, 74000.00);<br>        ResponseEntity&lt;ProductDTO&gt; updateProductResponse = restTemplate.exchange(baseUrl + &quot;/1&quot;, HttpMethod.PUT, new HttpEntity&lt;ProductDTO&gt;(updated), ProductDTO.class);<br><br>        assertThat(updateProductResponse.getBody().id()).isEqualTo(1);<br>        assertThat(updateProductResponse.getBody().name()).isEqualTo(&quot;Laptop&quot;);<br>        assertThat(updateProductResponse.getBody().price()).isEqualTo(74000.00);<br>    }<br><br>    @Test<br>    void shouldFindAllProducts() {<br>        ResponseEntity&lt;List&lt;ProductDTO&gt;&gt; response = restTemplate.exchange(<br>                baseUrl,<br>                HttpMethod.GET,<br>                null,<br>                new org.springframework.core.ParameterizedTypeReference&lt;List&lt;ProductDTO&gt;&gt;() {<br>                }<br>        );<br>        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);<br>        assertThat(response.getBody()).isNotNull();<br>        assertThat(response.getBody()).hasSizeGreaterThan(0);<br>    }<br><br>    @Test<br>    void shouldFindProductWhenValidProdcutID() {<br>        ResponseEntity&lt;ProductDTO&gt; response = restTemplate.exchange(baseUrl + &quot;/1&quot;, HttpMethod.GET, null, ProductDTO.class);<br>        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);<br>    }<br><br>    @Test<br>    void shouldDeleteWithValidID() {<br>        ResponseEntity&lt;Void&gt; response = restTemplate.exchange(baseUrl + &quot;/1&quot;, HttpMethod.DELETE, null, Void.class);<br>        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);<br>    }<br><br>    @Test<br>    void shouldThrowNotFoundWhenInvalidProductID() {<br>        ResponseEntity&lt;ProductDTO&gt; response = restTemplate.exchange(baseUrl + &quot;/999&quot;, HttpMethod.GET, null, ProductDTO.class);<br>        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);<br>    }<br><br>}</pre><h4>How Does This Help Developers?</h4><ol><li>No Local Database Needed: Developers don’t need to install or configure PostgreSQL locally.</li><li>Clean State: Each test starts with a fresh database.</li><li>CI/CD Friendly: Tests run the same way on developer machines and CI servers.</li><li>Easy to Extend: Add containers for Redis, Kafka, etc., as needed.</li></ol><h4>Conclusion</h4><p>Testcontainers makes integration testing effortless and reliable. By using real services in isolated containers, you ensure your tests are robust and your development workflow is smooth. If you’re building Spring Boot applications, integrating Testcontainers is a must for modern, professional Java development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57fdc6b1c670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How can Java get Epoch time, and what is it?]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/how-can-java-get-epoch-time-and-what-is-it-644102fa9083?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/644102fa9083</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[epoch]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 06:56:54 GMT</pubDate>
            <atom:updated>2023-07-30T06:56:54.466Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ll investigate what epoch time is and how to get it in Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iTxTuvcQq45oZs7L" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In computer science, the epoch time, often known as Unix time, is the number of seconds from January 1, 1970. In other words, it is the amount of seconds since that date.</p><p>The epoch is a specific point in time. Thus, epoch time refers to the number of seconds since the zero point.</p><h3><strong>Why Is an Epoch Required?</strong></h3><p>A computer needs a starting value before it can add some seconds on top of it. Adding some value to an unknown point in time makes no sense. The epoch time has been included to provide an initial zero point.</p><h3><strong>Facts about Epoch Time</strong></h3><ul><li>Epoch time, sometimes referred to as Unix time or POSIX time, is a method of expressing timestamps as the duration of time since an established reference point known as the “<strong><em>epoch</em></strong>.”</li><li>The epoch is the fixed point in time from which all subsequent timestamps are calculated.</li><li>The epoch time is defined in the context of Unix-based operating systems and programming as the amount of seconds that have passed since January 1, 1970, at 00:00:00 Coordinated Universal Time (UTC). This is often known as the “Unix Epoch”.</li><li>Using epoch time offers various benefits, including: -<br>- <strong><em>Simplicity: </em></strong>Representing time as a single integer (number of seconds) simplifies date and time computations in programming.<br>- <strong><em>Portability</em>:</strong> Epoch time is not reliant on any time zone, making it simple to store and transfer timestamps across different systems and locations.<br>- <strong><em>Precision:</em></strong> Using seconds as the unit of measurement provides sufficient precision for many applications.</li></ul><h3><strong>How to get epoch in java</strong></h3><p>As java is more popular for this type of calculation and for designing complicated applications, I’ve included a code snippet for your reference below -</p><pre>package epoch;<br><br>import java.time.Instant;<br>import java.time.LocalDateTime;<br>import java.time.ZoneId;<br>import java.time.ZoneOffset;<br>import java.time.format.DateTimeFormatter;<br><br>public class EpochExample {<br><br>    public static void main(String[] args) {<br><br>        //get Epoch from current Instant<br>        long epochInMillisecond = Instant.now().toEpochMilli();<br><br>        System.out.println(&quot;Epoch in Millisecond: &quot; + epochInMillisecond);<br><br>        Instant instant = Instant.ofEpochMilli(epochInMillisecond);<br><br>        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();<br>        String formattedDate = localDateTime.format(DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd HH:mm&quot;));<br>        System.out.println(&quot;Java System Local Date Time: &quot; + formattedDate);<br><br>        <br>        //get epoch of specific zone DateTime<br>        long epochSecond = localDateTime.toEpochSecond(ZoneOffset.of(&quot;+04:00&quot;));<br>        instant = Instant.ofEpochSecond(epochSecond);<br>        localDateTime = instant.atZone(ZoneId.of(&quot;Asia/Kolkata&quot;)).toLocalDateTime();<br>        formattedDate = localDateTime.format(DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd HH:mm&quot;));<br>        System.out.println(&quot;Java Specific Zone Local Date Time: &quot; + formattedDate);<br>    }<br>}<br><br>/***<br>  Output<br>  Epoch in Millisecond: 1690699823712<br>  Java System Local Date Time: 2023/07/30 12:20<br>  Java Specific Zone Local Date Time: 2023/07/30 13:53<br>***/<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=644102fa9083" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[private is not a private in Java?]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/private-is-not-a-private-in-java-69ce1627b66b?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ce1627b66b</guid>
            <category><![CDATA[ocjp]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[reflections]]></category>
            <category><![CDATA[scjp]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 04:06:43 GMT</pubDate>
            <atom:updated>2023-06-27T04:06:43.600Z</atom:updated>
            <content:encoded><![CDATA[<p>With an example of code, I’ll demonstrate the benefits of Java’s reflection API and how you can modify or access even private members and methods of a class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*waAvB7OvFL7ABQD3" /><figcaption>Photo by <a href="https://unsplash.com/ko/@tonydetroit?utm_source=medium&amp;utm_medium=referral">Tony Detroit</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>Before I begin working on the Reflection API, let me first clarify what reflection is. Reflection is the process of analyzing all of a class’s capabilities during runtime. For example, if I have a class for that class, what are the exact modifiers list, who is the super-class, and what interfaces are implemented in the respective class, as well as the details of each variable, constructor details, and method declaration details? I’d like to collect all of these details. To perform this with all of these characteristics, we require a Java API called the Reflection API.</p><p><strong>Where will we use a reflection API?</strong></p><p>The Reflection API can be used in a variety of scenarios and to build a range of tools. I’ve included some of these in the list below:</p><ol><li>Compiler Construction</li><li>JVM Architecture Design</li><li>Server Design</li><li>Framework Design</li><li>IDE Design etc.</li></ol><blockquote>The Reflection API is not at all useful in project development.</blockquote><p>Consider the following scenario in the context of compiler construction. Declaring an outer class as private causes a compile-time error in Java while declaring an inner class is permitted. However, outside classes cannot be declared private. Compile will raise an error stating that private modifiers are not permitted in this scenario. The compiler will raise this type of error.</p><p>The java.lang and java.lang.reflect packages provide classes for Java reflection.</p><h3>java.lang.reflect and java.lang packages</h3><p>This package contains all of the classes required by the Reflection API.</p><ol><li><strong>Class </strong>—This class is present in the <strong>java.lang</strong> package and is used to bring the metadata about a specific class.</li><li><strong>Field </strong>—This class is present in the <strong>java.lang.reflect</strong> package and is used to bring the metadata of declared variables of the specified class.</li><li><strong>Method </strong>— This class can be found in the <strong>java.lang.reflect</strong> package and is used to provide complete metadata about a class’s defined methods.</li><li><strong>Constructor </strong>— This class exists in the <strong>java.lang.reflect</strong> package and is used to provide complete metadata about a class’s declared constructors.</li><li><strong>Modifiers</strong> —This class is also present in the <strong>java.lang.reflect</strong> package and is used to provide detailed metadata about a method, class, or member variable’s declared or used modifier.</li></ol><p><strong>Class </strong>objects can be created in the following ways:</p><pre>//Way - 1 <br>Class class = new Class.forName(&quot;Employee&quot;);<br><br>//Way - 2<br>Employee emp = new Employee();<br><br>Class class = emp.getClass();<br><br>//Way - 3<br>Class c = Employee.class;</pre><p><strong>Class </strong>methods that are commonly used -</p><ol><li><strong>getName()</strong> — This is used to get the name of the entity, and that entity can be the class, interface, array, enum, method, etc. of the class object. The method returns the name of the entity as a String. Signature of <strong>getName() :</strong></li></ol><pre>public String getName()</pre><p>2<strong>. </strong><strong>getSuperclass() — </strong>This is used to get the metadata of the superclass of this entity. The method returns the superclass of this entity. Signature of <strong>getSuperclass() :</strong></p><pre>public native Class&lt;? super T&gt; getSuperclass()</pre><p>3<strong>. </strong><strong>getInterfaces() — </strong>This is used to get the interfaces directly implemented by this entity. This entity can be a class or an interface. The method returns an array of interfaces directly implemented by this entity.</p><pre>public Class&lt;?&gt;[] getInterfaces()</pre><p>4<strong>. </strong><strong>getModifiers() — </strong>It returns an int value. Then with the use <strong>Modifier </strong>class, the name of modifiers corresponding to that value is fetched.</p><pre>public native int getModifiers()</pre><p>5. <strong>getFields() —</strong>This is used to get the fields of this class, which are the fields that are public and its members. The method returns the fields of this class in the form of an array of Field objects.</p><pre>public Field[] getFields() throws SecurityException</pre><p>6. <strong>getDeclaredFields() — </strong>This is used to get the fields of this class, which are the fields that are private, public, protected, or default and their members, but not the inherited ones. The method returns the fields of this class in the form of an array of Field objects.</p><pre>public Field[] getDeclaredFields() throws SecurityException</pre><p>7.<strong> </strong><strong>getMethods() — </strong>This<strong> </strong>is used to get the methods of this class, which are the methods that are public and its members or the members of its member classes and interfaces. The method returns the methods of this class in the form of an array of Method objects.</p><pre>public Method[] getMethods() throws SecurityException</pre><p><strong>8. </strong><strong>getDeclaredMethods() — </strong>this is used to get the methods of this class, which are the methods that are private, public, protected, or default, and its members or the members of its member classes and interfaces, but not the inherited methods. The method returns the methods of this class in the form of an array of Method objects.</p><pre>public Method[] getDeclaredMethods() throws SecurityException</pre><p><strong>9. </strong><strong>getConstructors() — </strong>This is used to get the constructors of this class, which are the constructors that are public. The method returns the constructors of this class in the form of an array of Constructor objects.</p><pre>public Constructor&lt;?&gt;[] getConstructors() throws SecurityException</pre><p><strong>10. </strong><strong>getDeclaredConstructors() — </strong>This is used to get the specified constructor of this class with the specified parameter type. The method returns the specified constructor of this class in the form of a Constructor object.</p><pre>public Constructor&lt;?&gt;[] getDeclaredConstructors() throws SecurityException</pre><p>Now, for your convenience, I’ve created a complete example applying the following method:</p><pre>public class Product {<br>    <br>    public int productId;<br>    public String productName;<br>    public String category;<br>    public long price;<br><br>}</pre><p>I create a class called <strong>Product </strong>and retrieved the <strong>Product </strong>class’s complete metadata here.</p><pre>import java.lang.reflect.Modifier;<br><br>public class ReflectionAPI {<br><br>    public static void main(String[] args) throws ClassNotFoundException {<br><br>        Class name = Class.forName(&quot;org.example.Product&quot;);<br>        System.out.println(&quot;Name:   &quot;+name.getName());<br>        System.out.println(&quot;Super Class:    &quot; + name.getSuperclass().getName());<br>        Class[] interfaces= name.getInterfaces();<br>        System.out.println(&quot;Interfaces List:    &quot;);<br>        for(Class cls: interfaces){<br>            System.out.println(cls.getName());<br>        }<br>        System.out.println();<br>        int i = name.getModifiers();<br>        System.out.println(&quot;Access Modifiers:   &quot;+ Modifier.toString(i));<br>    }<br>}<br><br>/***<br>  Output <br>  Name:   org.example.Product<br>  Super Class:    java.lang.Object<br>  Interfaces List:    <br>  Access Modifiers:   public<br>***/<br></pre><p><strong>Field</strong> methods that are commonly used -</p><ol><li><strong>getName()</strong> — This is used to get the name of the field represented by this Field object. When a class contains a field and we want to get the name of that field then we can use this method to return the name of the Field as a String.</li></ol><pre>public String getName()</pre><p>2. <strong>getType() —</strong> This method returns a Class object that identifies the declared type for the field represented by this Field object.</p><pre>public Class&lt;?&gt; getType()</pre><p><strong>3. </strong><strong>getXXX() —</strong>This method returns the value of the field represented by this Field, on the specified object. In the case of primitive type, The value is automatically wrapped in an object. To obtain values for String, Object, and wrapper classes, field classes provide methods such as getInt(), getBoolean(), getString(), get(), and so on.</p><p>Now, for your convenience, I’m going to create a complete example using the above method of the <strong>Field </strong>class.</p><pre>public class Product {<br>    public int productId = 1245;<br>    private String productName;<br>    public String category;<br>    private long price;<br>}</pre><p>I create a class called <strong>Product </strong>and retrieved the <strong>Product </strong>class’s complete metadata about <strong>Field</strong> here.</p><pre>import java.lang.reflect.Field;<br>import java.lang.reflect.Modifier;<br><br>public class ReflectionAPI {<br><br>    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException {<br>        Class name = Class.forName(&quot;org.example.Product&quot;);<br>        System.out.println(&quot;Class Name:   &quot; + name.getName());<br><br>        Field[] declaredFields = name.getDeclaredFields();<br><br>        for (Field field : declaredFields) {<br>            System.out.println(&quot;Field Name: &quot;+field.getName());<br>            System.out.println(&quot;FieldData type: &quot; + field.getType().getName());<br>            System.out.println(&quot;Field Access Modifiers: &quot; + Modifier.toString(field.getModifiers()));<br>        }<br>    }<br>}<br><br>/***<br>  Output<br>  Class Name:   org.example.Product<br>  <br>  Field Name: productId<br>  FieldData type: int<br>  Field Access Modifiers: public<br><br>  Field Name: productName<br>  FieldData type: java.lang.String<br>  Field Access Modifiers: private<br><br>  Field Name: category<br>  FieldData type: java.lang.String<br>  Field Access Modifiers: private static<br><br>  Field Name: price<br>  FieldData type: long<br>  Field Access Modifiers: private<br><br>***/<br></pre><p><strong>Method</strong>methods that are commonly used -</p><ol><li><strong>getName()</strong> — This method is used to get the name of the method of a class and return it as a String.</li></ol><pre>public String getName()</pre><p>2. <strong>getReturnType() —</strong>This method of the Method the class returns a Class object that represents the return type, declared in the method at the time of creating the method.</p><pre>public Class&lt;?&gt; getReturnType()</pre><p>3. <strong>getParameterTypes() — </strong>This method returns an array of Class objects that represents the parameter types, declared in the method at the time of coding. The getParameterTypes() returns an array of length 0 if the method object takes no parameters.</p><pre>public Class&lt;?&gt;[] getParameterTypes()</pre><p><strong>4. </strong><strong>getExceptionTypes()</strong> — This method returns an array of Class objects that represents the exception types and throws in the method at the time of compile or run time. This returns an array of length 0 if the method does not throw an exception.</p><pre>public Class&lt;?&gt;[] getExceptionTypes()</pre><pre><br>import java.sql.SQLException;<br><br>public class Product {<br>    public int productId = 1245;<br>    private String productName;<br>    private  String category;<br>    private long price;<br><br>    public void addProduct(int productId, String productName, String category, long price) throws ClassNotFoundException, ClassCastException{<br>    }<br>    public String searchProduct(String productName) throws ArithmeticException, InterruptedException{<br>        return &quot;&quot;;<br><br>    }<br>    public String deleteProduct(int eno) throws SQLException {<br>        return &quot;&quot;;<br>    }<br>}</pre><p>I create a class called <strong>Product </strong>and retrieved the <strong>Product </strong>class’s complete metadata about <strong>Method</strong> here.</p><pre>import java.lang.reflect.Method;<br>import java.lang.reflect.Modifier;<br><br>public class ReflectionAPI {<br><br>    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException {<br>        Class name = Class.forName(&quot;org.example.Product&quot;);<br>        System.out.println(&quot;Class Name:   &quot; + name.getName());<br>        <br>        Method[] declaredMethods = name.getDeclaredMethods();<br>        <br>        for (Method method : declaredMethods) {<br><br>            System.out.println(&quot;Method Name: &quot; + method.getName());<br>            System.out.println(&quot;Return Type:&quot; + method.getReturnType().getName());<br>            System.out.println(&quot;Modifier:&quot; + Modifier.toString(method.getModifiers()));<br>            Class[] parameterTypes = method.getParameterTypes();<br>            System.out.print(&quot;Parameter Types:&quot;);<br><br>            for (Class parameter : parameterTypes) {<br>                System.out.println(parameter.getName());<br>            }<br><br>            Class[] exceptionTypes = method.getExceptionTypes();<br>            System.out.println(&quot;Exception Types :&quot;);<br>            for (Class exception : exceptionTypes) {<br>                System.out.println(exception.getName());<br>            }<br>        }<br>    }<br>}<br><br>/****<br>  Output -<br>    Class Name:   org.example.Product<br><br>    Method Name: searchProduct<br>    Return Type:java.lang.String<br>    Modifier:public<br>    Parameter Types:java.lang.String<br>    Exception Types :<br>      java.lang.ArithmeticException<br>      java.lang.InterruptedException<br><br>    Method Name: addProduct<br>    Return Type:void<br>    Modifier:public<br>    Parameter Types:int<br>      java.lang.String<br>      java.lang.String<br>      long<br>    Exception Types :<br>      java.lang.ClassNotFoundException<br>      java.lang.ClassCastException<br><br>    Method Name: deleteProduct<br>    Return Type:java.lang.String<br>    Modifier:public<br>    Parameter Types:int<br>    Exception Types :<br>      java.sql.SQLException<br>****/<br></pre><p><strong>Constructor() </strong>methods that are commonly used<strong>-</strong></p><ol><li><strong>getName()</strong> — This method is used to get the name of the constructor of a class and return it as a String.</li></ol><pre>public String getName()</pre><p>2.<strong> </strong><strong>getParameterType() -</strong>This method returns an array of Class objects that represents the parameter types, declared in the constructor at the time of coding. The getParameterTypes() returns an array of length 0 if the constructor object takes no parameters.</p><pre>public Class&lt;?&gt;[] getParameterTypes()</pre><p>3. <strong>getExceptionTypes() — </strong>This method returns an array of Class objects that represents the exception types and throws in the method at the time of compile or run time. This returns an array of length 0 if the method does not throw an exception.</p><pre>public Class&lt;?&gt;[] getExceptionTypes()</pre><pre>public class Product {<br>    public int productId = 1245;<br>    private String productName;<br>    private String category;<br>    private long price;<br><br>    public Product(int productId, String productName, String category, long price) throws ClassCastException, ArithmeticException {<br>        this.productId = productId;<br>        this.productName = productName;<br>        this.category = category;<br>        this.price = price;<br>    }<br><br>    public Product(int productId, String productName, String category) throws java.rmi.RemoteException, java.sql.SQLException {<br>        this.productId = productId;<br>        this.productName = productName;<br>        this.category = category;<br>    }<br><br>    public Product(int productId, String productName) throws InterruptedException {<br>        this.productId = productId;<br>        this.productName = productName;<br>    }<br><br>    public Product(String category) {<br>        this.category = category;<br>    }<br><br>    public Product() {<br>    }</pre><pre>import java.lang.reflect.Constructor;<br>import java.lang.reflect.Modifier;<br><br>public class ReflectionAPI {<br><br>    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException {<br>        Class name = Class.forName(&quot;org.example.Product&quot;);<br>        System.out.println(&quot;Class Name:   &quot; + name.getName());<br><br>        Constructor[] constructors = name.getDeclaredConstructors();<br><br>        for (Constructor constructor : constructors) {<br>            System.out.println(&quot;Name: &quot; + constructor.getName());<br>            System.out.println(&quot;Access Modifiers: &quot; + Modifier.toString(constructor.getModifiers()));<br><br>            Class[] parameterTypes = constructor.getParameterTypes();<br>            System.out.println(&quot;Parameter Type List: &quot;);<br>            for (Class parameter : parameterTypes) {<br>                System.out.println(parameter.getName());<br>            }<br>            Class[] exceptionTypes = constructor.getExceptionTypes();<br>            System.out.println(&quot;Exception List: &quot;);<br>            for (Class exception : exceptionTypes) {<br>                System.out.println(exception.getName());<br>            }<br>        }<br>    }<br>}<br><br>/****<br>  Output <br>    Class Name:   org.example.Product<br>    Name: org.example.Product<br>    Access Modifiers: public<br>    Parameter Type List: <br>    Exception List: <br><br>    Name: org.example.Product<br>    Access Modifiers: public<br>    Parameter Type List: <br>       java.lang.String<br>    Exception List: <br><br>    Name: org.example.Product<br>    Access Modifiers: public<br>    Parameter Type List: <br>      int<br>      java.lang.String<br>    Exception List: <br>      java.lang.InterruptedException<br><br>    Name: org.example.Product<br>    Access Modifiers: public<br>    Parameter Type List: <br>      int<br>      java.lang.String<br>      java.lang.String<br>    Exception List: <br>      java.rmi.RemoteException<br>      java.sql.SQLException<br><br>    Name: org.example.Product<br>    Access Modifiers: public<br>    Parameter Type List: <br>      int<br>      java.lang.String<br>      java.lang.String<br>      long<br>    Exception List: <br>      java.lang.ClassCastException<br>      java.lang.ArithmeticException<br>****/<br></pre><p>It’s now time to write code to build objects, even if the constructor is private, and access and modify private members. The code below shows it.</p><pre><br>public class Order {<br>    private int orderId = 4523;<br>    private int customerId;<br>    private String address;<br>    <br>    private Order(int orderId) {<br>        this.orderId = orderId;<br>        System.out.println(&quot;This is private constructor&quot;);<br>    }<br><br>    public void display() {<br>        System.out.println(&quot;Value of a &quot; + this.orderId);<br>    }<br>}</pre><pre><br>import java.lang.reflect.Constructor;<br>import java.lang.reflect.InvocationTargetException;<br>import java.lang.reflect.Modifier;<br><br>public class ReflectionAPI {<br><br>    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {<br><br>        Class order = Class.forName(&quot;org.example.Order&quot;);<br>        <br>        Constructor[] declaredConstructors = order.getDeclaredConstructors();<br><br>        for (Constructor constructor : declaredConstructors) {<br><br>            System.out.println(constructor.getName());<br>            constructor.setAccessible(true);<br>            Order ordered = (Order) constructor.newInstance(23);<br>            ordered.display();<br>        }<br><br>    }<br>}<br><br>/***<br>  Output-<br>    org.example.Order<br>    This is parameter constructor<br>    Value of a 23<br>***/<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ce1627b66b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why do we use the generic in Java?]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/why-do-we-use-the-generic-in-java-582f2f90d209?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/582f2f90d209</guid>
            <category><![CDATA[ocjp]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[scjp]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 08:22:17 GMT</pubDate>
            <atom:updated>2023-06-07T08:22:17.855Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, I’ll guide you on why we use the generic, and when to use it with real-world examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nCzLhvsMdbNMuWRh" /><figcaption>Photo by <a href="https://unsplash.com/@safarslife?utm_source=medium&amp;utm_medium=referral">Safar Safarov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>The primary goal of generics is to offer type safety and overcome typecasting difficulties.</p><p><strong>Case 1: — </strong>Type Safety: Arrays are type-safe in that we can give a grantee the types of elements present inside the array. For example, if our programming requirement is to hold only string types of elements, then we can choose a string type of array. By mistake, if we are trying to add any other type of elements, we will get a compile-time error.</p><pre>String[] names = new String[100];<br>names[0] = &quot;ibm&quot;;<br>names[1] = &quot;intel&quot;;<br>names[2] = &quot;dell&quot;;<br>names[3] = new Integer(10); //Compile-Time Error - java: incompatible types: java.lang.Integer cannot be converted to java.lang.String<br>names[3] = &quot;hp&quot;;</pre><p>Hence, the String array can contain only the String type of object; due to this, we can give the grantee the elements present inside the array. Hence, arrays are safe to use with respect to type because they are type-safe.</p><p>However, because collections are not type-safe, we cannot provide the grantee with the type of element contained within the collection. For example, if our programming need is to hold just a String type of element and we chose ArrayList by mistake, we will not get any compile-time errors and the program may fail at run-time.</p><pre>ArrayList names = new ArrayList();<br>        names.add(&quot;ibm&quot;);<br>        names.add(&quot;intel&quot;);<br>        names.add(&quot;dell&quot;);<br>        names.add(new Integer(10));<br><br>        String name1 = (String) names.get(0);<br>        String name2 = (String) names.get(1);<br>        String name3 = (String) names.get(2);<br>        String name4 = (String) names.get(3); //Run-Time Error java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String</pre><p>As a result, we are unable to provide the grantee with the type of elements contained within the collection because this collection is not type-safe.</p><p><strong>Case 2: —</strong> Type Casting: In the case of arrays, type casting is not required upon retrieval because there is a grantee for the type of element existing within the array.</p><pre>String[] names = new String[100];<br>names[0] = &quot;ibm&quot;;<br>String company = names[0]; //Type casting not required<br>System.out.println(company);<br>/***<br>Output<br>  ibm<br>***/</pre><p>However, in the case of collections, we must conduct type casting during retrieval because there is no guarantee for the type of elements consisted of within the collection.</p><pre>ArrayList names = new ArrayList();<br>names.add(&quot;ibm&quot;);<br>String company =  names.get(0);<br>String company = (String) names.get(0);</pre><p>As a result, typecasting is a major headache in the collection.</p><p>To overcome the above problem of collection, Java people introduced the generic concept in Java 1.5v. Hence, the main objectives of generics are:</p><ol><li>To provide type safety</li><li>To Resolve type casting problem</li></ol><p>For instance, we may make a generic ArrayList that only contains objects of the string type as follows:</p><pre>ArrayList&lt;String &gt; names = new ArrayList&lt;&gt;();</pre><p>We can only add String objects to this ArrayList. By accident; if we try to add another type, we will get a compile-time error.</p><pre>ArrayList&lt;String &gt; names = new ArrayList&lt;&gt;();<br>names.add(&quot;intel&quot;);<br>names.add(&quot;dell&quot;);<br>names.add(new Integer(10));//Compile-Time Error - java: incompatible types: java.lang.Integer cannot be converted to java.lang.String</pre><p>Therefore, through generic, we are getting a type of safety grantee.</p><p>We are not obligated to do typecasting at the moment of retrieval.</p><pre>ArrayList&lt;String &gt; names = new ArrayList&lt;&gt;();<br>names.add(&quot;intel&quot;);<br>String company = names.get(0) //Type casting is not required.</pre><p>So, type-casting issues can be resolved with generics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9hAR9sE2ugTIe1B5KDyFg.png" /></figure><ol><li><strong>Conclusion 1: — </strong>The polymorphism concept is applicable only for base types but not for parameter types (the use of parent references to hold child objects is the concept of polymorphism).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*gD5jlDBibo4QtSyNGvjmbA.png" /></figure><p>2. <strong>Conclusion 2: —</strong>We can specify any class or interface name for the type parameter, but not a primitive. If we try to give primitives, we will receive a compile-time error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*jJ6o_Qx9tvxWLRFe-DMJ0g.png" /></figure><h3>Generic Classes</h3><p>ArrayList non-generic version was declared as follows until Java1.4v:</p><pre>class ArrayList {<br>    add(Object o) {<br><br>    }<br><br>    Object get(int index) {<br>        <br>    }<br>}</pre><p>The argument to add the add() method is an object, and hence we can add any type of element to the ArrayList. Due to this, we were missing type safety.</p><p>The return type of the get() method is an object; hence, at the time of retrieval, we have to perform type casting.</p><p>But in Java 1.5v, a generic version of ArrayList is declared as follows:</p><pre>class ArrayList &lt;T&gt; {   //T is Type Parameter <br>    add(T t) {<br><br>    }<br><br>    T get(int index) {<br>        <br>    }<br>}</pre><p>Based on our run-time requirement, T will be replaced with our provided type. For example, to hold only the String type of object, a generic version of the ArrayList the object can be created as follows:</p><pre>ArrayList&lt;String &gt; names = new ArrayList&lt;&gt;();</pre><p>For this requirement, the compiler considers the following version of the ArrayList class:</p><pre>class ArrayList &lt;String&gt; {   //T is Type Parameter <br>    add(String s) {<br><br>    }<br><br>    String get(int index) {<br>        <br>    }<br>}</pre><p>The argument type of the add method is String type; hence, we can add only Stringtype objects. By mistake. If we are trying to add any other type, we get a compile-time error.</p><pre>ArrayList&lt;String &gt; names = new ArrayList&lt;&gt;();<br>names.add(&quot;ibm&quot;);<br>names.add(&quot;intek&quot;);<br>names.add(new Integer(10)); //Compile-Time Error</pre><p>As a result of generic, we may achieve type safety; the return type of the get() method is String therefore, we do not need to type cast while retrieving.</p><pre>ArrayList&lt;String &gt; names = new ArrayList&lt;&gt;();<br>names.add(&quot;ibm&quot;);<br>names.add(&quot;intek&quot;);<br>String name = names.get(0); // Type casting not required.</pre><p>In generic, we are associating a type parameter to the class; these types of parameter-raised classes are nothing but generic classes or template classes. Based on our requirements, we can also define our own generic classes.</p><pre>class Account&lt;T&gt; {<br>}<br><br>Account&lt;Gold&gt; goldAccount = new Account&lt;Gold&gt;();<br>Account&lt;Platinum&gt; platinumAccount = new Account&lt;Platinum&gt;();<br>  <br></pre><p>Now I’m here, adding the complete code of the generic class.</p><pre>class Generator&lt;T&gt; {<br><br>    T obj;<br><br>    public Generator(T obj) {<br>        this.obj = obj;<br>    }<br><br>    public void show() {<br>        System.out.println(&quot;The type of Object: &quot; + obj.getClass().getName());<br>    }<br><br>    public T getObject() {<br>        return obj;<br>    }<br>}<br><br>public class GenericClassExamplel {<br><br>    public static void main(String[] args) {<br>      <br>        Generator&lt;Integer&gt; intTypeGeneric = new Generator&lt;Integer&gt;(10);<br>        Generator&lt;Double&gt; doubleTypeGeneric = new Generator&lt;Double&gt;(14.0);<br>        Generator&lt;String&gt; stringTypeGeneric = new Generator&lt;String&gt;(&quot;Generic&quot;);<br>        <br>        System.out.println(&quot;--------------------Integer-----------------&quot;);<br>        intTypeGeneric.show();<br>        System.out.println(intTypeGeneric.getObject());<br>        <br>        System.out.println(&quot;--------------------Double-----------------&quot;);<br>        doubleTypeGeneric.show();<br>        System.out.println(doubleTypeGeneric.getObject());<br>        <br>        System.out.println(&quot;--------------------String-----------------&quot;);<br>        stringTypeGeneric.show();<br>        System.out.println(stringTypeGeneric.getObject());<br><br>    }<br>}<br><br>/*****<br>Output<br>  --------------------Integer-----------------<br>  The type of Object: java.lang.Integer<br>  10<br>  --------------------Double-----------------<br>  The type of Object: java.lang.Double<br>  14.0<br>  --------------------String-----------------<br>  The type of Object: java.lang.String<br>  Generic<br><br>*****/<br></pre><h3>Bounded Types</h3><p>We can bound type parameters for a particular range by using the extend keyword. Such a type is called a <strong>“bounded type”</strong>.</p><pre>class Generator&lt;T&gt; {}</pre><p>As the type parameter, we can pass any type with no restrictions; thus, it is an unbounded type, as shown below:</p><pre>Generator&lt;Integer&gt; intTypeGeneric = new Generator&lt;Integer&gt;(10);<br>Generator&lt;Double&gt; doubleTypeGeneric = new Generator&lt;Double&gt;(14.0);<br>Generator&lt;String&gt; stringTypeGeneric = new Generator&lt;String&gt;(&quot;Generic&quot;);</pre><h4>The syntax for Bounded Type</h4><pre>class Generator&lt;T extend X &gt; {}</pre><p>X can be either a class or an interface. If X is a class, the type parameter allows us to pass either the X type or its child classes. If X is an interface, then as a type parameter, we can pass either the type of X or its implementation classes.</p><pre>class Generator&lt;T extends Number&gt; {<br><br>}<br><br> Generator&lt;Integer&gt; intTypeGeneric = new Generator&lt;Integer&gt;();<br> Generator&lt;Double&gt; doubleTypeGeneric = new Generator&lt;Double&gt;();<br> Generator&lt;String&gt; stringTypeGeneric = new Generator&lt;String&gt;(); // Compile-Time Error - Type parameter &#39;java.lang.String&#39; is not within its bound; should extend &#39;java.lang.Number&#39;<br><br></pre><pre>class Generator&lt;T extends Runnable&gt; {<br><br>}<br><br>  Generator&lt;Runnable&gt; runnableGenerator = new Generator&lt;Runnable&gt;();<br>  Generator&lt;Thread&gt; threadGenerator = new Generator&lt;Thread&gt;();<br>  Generator&lt;Integer&gt; stringTypeGeneric = new Generator&lt;Integer&gt;(); //Compile-Time Error- Type parameter &#39;java.lang.Integer&#39; is not within its bound; should implement &#39;java.lang.Runnable&#39;</pre><p>We can define a bound type even in combination.</p><pre>class Generator&lt;T extends Number &amp; Runnable&gt; {}</pre><p>We can use anything that should be a child class of Number as the type parameter and implements the Runnable interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4rsTZoNQ3s5m3S58USpEQ.png" /></figure><blockquote><strong>1. </strong>We can only use the extends keyword to define a bound type; we cannot use the implements or super keywords, but we can replace the implements keyword with the extends keyword.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcQTTJo_zlpg-GCUQY-Mjw.png" /></figure><blockquote><strong>2. </strong>We can use any valid Java identifier as type parameter T, however it is more common to use T.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hmLc2amC5cBymHp_FjPmQ.png" /></figure><p>3. Based on our requirement, we can declare any number of type parameters, and all these type parameters should be separated by (,).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMGxv7KS9tsp7ElE2D8nRA.png" /></figure><h3>Generic method and wildcard character (?)</h3><ol><li>We can invoke this method by sending an ArrayList of String types to it. We can only add String as an object type to the list; if we try to add any other type, we will get a compile-time error.</li></ol><pre>void addItem(ArrayList&lt;String&gt; list){<br>    <br>    list.add(&quot;Google&quot;); //✔ <br>    list.add(&quot;Yahoo&quot;);  //✔ <br>    list.add(null);     //✔ <br>    list.add(100);      // ☓ <br><br>}</pre><p>2. We can call this method by passing ArrayList any unknown type or any type. But within the method, we can’t add anything to the list except null because we don’t know the type exactly. null is allowed because it is valid for any type.</p><pre>void addItem(ArrayList&lt;?&gt; list){<br><br>    list.add(&quot;Google&quot;); //☓ <br>    list.add(&quot;Yahoo&quot;);  //☓ <br>    list.add(null);     //✔<br>    list.add(100);      //☓ <br><br>}</pre><blockquote><strong>Note </strong>— This type of method are best suitable for read-only operation.</blockquote><p>3. X can be a class or an interface. If X is a class, we invoke this method with an ArrayList of either X or its child class. If X is an interface, we can invoke it by giving an ArrayList of either the X type or its implementation classes.</p><pre>void addItem(ArrayList&lt;? extends x&gt; list){<br>}<br></pre><p>However, because we don’t know the exact type, we can’t add anything to the list except null within the method. This method is also suitable for read-only tasks.</p><p>4. X can be a class or an interface. If X is a class, we can invoke this method by supplying an ArrayList of X or its superclasses. If X is an interface, we can call this method by supplying an ArrayList of either the X type or the superclass of the X implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*zXlQzoABrA7xT8y5VFTipg.png" /></figure><p>But within a method, we can add X types of objects and null to the list.</p><pre>1. ArrayList&lt;String&gt; list1 = new ArrayList&lt;String&gt;();//✔ <br>2. ArrayList&lt;?&gt; list2 = new ArrayList&lt;String&gt;();//✔ <br>3. ArrayList&lt;?&gt; list3 = new ArrayList&lt;Integer&gt;();//✔ <br>4. ArrayList&lt;? extends Number&gt; list4 = new ArrayList&lt;Integer&gt;();//✔ <br>5. ArrayList&lt;? extends Number&gt; list5 = new ArrayList&lt;String&gt;();//☓ <br>6. ArrayList&lt;? super String&gt; list6= new ArrayList&lt;Object&gt;();//✔ <br>7. ArrayList&lt;?&gt; list7= new ArrayList&lt;?&gt;(); //☓ <br>8. ArrayList&lt;?&gt; list8= new ArrayList&lt;? extends Number&gt;();  //☓ </pre><p>Type parameters can be declared at either the class or method level. At the class level, type parameters are declared.</p><pre>class Generator&lt;T&gt; {<br>// We can use &#39;T&#39; within this class based on our requirement<br>}</pre><p>By declaring the type parameter at the method level, we can declare the type parameter just before returning the type.</p><pre>public &lt;T&gt; void myMethod(T object){<br>// We can use &#39;T&#39; anywhere within this class based on our requirement<br>}</pre><p>We can define a bound type even at the method level-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0N6LpGpw9LaamdlblYmq-w.png" /></figure><h3>Communication with non-generic code</h3><p>If we send the generic object to the non-generic area, it begins to behave like a non-generic, similarly non-generic to the generic object, and then resumes its generic behavior. That is, in a location where items are present depending on their well-defined behavior.</p><pre>import java.util.ArrayList;<br><br>public class GenericExample {<br><br>    public static void main(String[] args) {<br><br>        ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();<br>        /*<br>         * Generic Area<br>         */<br>        list.add(&quot;ibm&quot;);<br>        list.add(&quot;intel&quot;);<br>        list.add(&quot;samsung&quot;);<br>        //list.add(10);<br>        System.out.println(list);<br>        addItem(list);<br>        //list.add(10);<br>        System.out.println(list);<br>    }<br><br>    public static void addItem(ArrayList list) {<br>        /*<br>         * Non-Generic Area<br>         */<br>        list.add(10);<br>        list.add(20.5);<br>        list.add(true);<br><br>    }<br>}<br><br>/***<br>Output<br>  [ibm, intel, samsung]<br>  [ibm, intel, samsung, 10, 20.5, true]<br>***/<br></pre><p>The primary goal of generics is to offer type safety and eliminate type casting. At compilation time, type safety and type casting are both relevant. As a result, the generic concept is only applicable during compilation, as the final step of generic syntax is omitted, and so generic syntax is not available for the JVM. As a result, the following declaration is equivalent:</p><pre>ArrayList list = new ArrayList&lt;String&gt;();<br>ArrayList list = new ArrayList&lt;Integer&gt;();<br>ArrayList list = new ArrayList&lt;Double&gt;();<br>ArrayList list = new ArrayList();</pre><pre>ArrayList list = new ArrayList&lt;String&gt;();<br>list.add(&quot;ibm&quot;);<br>list.add(10);<br>list.add(true);</pre><p>The following declaration is equal -</p><pre>ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();<br>ArrayList list = new ArrayList();</pre><p>for the above codeArrayList we can add only String type object.</p><pre>public class GenericExample {<br><br>    public static void addItem(ArrayList list) {<br>        <br>    }<br><br><br>    public static void addItem(ArrayList&lt;Integer&gt; list) {<br>      <br>    }<br>}</pre><blockquote>Compile-Time Error- &#39;addItem(ArrayList)&#39; clashes with &#39;addItem(ArrayList&lt;Integer&gt;)&#39;; both methods have same erasure</blockquote><p>The compiler follows the following step for generic case in-</p><ol><li>The compiler compiles code normally by considering generic syntax</li><li>Remove generic syntax</li><li>Compiler compiles code once again resultant code</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=582f2f90d209" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build Regular Expression in Java]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/how-to-build-regular-expression-in-java-16e3c3cc9f43?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/16e3c3cc9f43</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scjp]]></category>
            <category><![CDATA[ocjp]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Mon, 29 May 2023 04:31:55 GMT</pubDate>
            <atom:updated>2023-05-29T04:31:55.910Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, I’ll explain in detail how to build a regular expression in Java, as well as provide some sample regular expressions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Z7LN43zyv3uWiEaL0TFcag.png" /></figure><h3>Introduction</h3><p>If we want to represent a group of strings according to a particular pattern, then we should go for a regular expression.</p><p>For example, we can write a regular expression to represent all valid email addresses, or we can write a regular expression to validate valid phone numbers, and so on.</p><p>The most important application area where we can use regular expressions-</p><ol><li>To develop a validation framework like the Hibernate Validator.</li><li>To develop a pattern matching tool or application like Ctrl + F or grap cmd in Linux.</li><li>To develop digital circuits</li><li>To develop translators like assemblers, compilers,s, and interpreters, etc.</li><li>To develop communication protocol TCP/IP, UDP, etc.</li></ol><p>To work with regular expressions in Java, we can utilize the<strong> java.util.regex</strong> package, which includes the following classes:</p><ol><li><strong>Pattern—</strong> This class is a compilation of regular expressions that can be used to define various types of patterns (define a pattern to be used in a search).</li><li><strong>Matcher—</strong> This object is used to perform match operations for an input string in Java (Used to search for the pattern).</li><li><strong>PatternSyntaxException</strong> — This class is used to Indicates syntax error in a regular expression pattern.</li></ol><p>Here I’m adding a sample code snippet of a regular expression: —</p><pre>import java.util.regex.*;<br><br>public class RegularExpression {<br><br>    public static void main(String[] args) {<br>        int count = 0;<br>        Pattern pattern = Pattern.compile(&quot;ab&quot;);<br>        Matcher matcher = pattern.matcher(&quot;abcbcbcababacb&quot;);<br>        while (matcher.find()) {<br>            ++count;<br>            System.out.println(matcher.group()+ &quot;...... found at: &quot;+matcher.start());<br>        }<br><br>        System.out.println(&quot;The Total number of occurrence is &quot; + count);<br><br>    }<br>}<br><br>/****<br>  Output-<br>  ab...... found at: 0<br>  ab...... found at: 7<br>  ab...... found at: 9<br>  The Total number of occurrence is 3<br>****/<br></pre><h3><strong>Pattern: —</strong></h3><p>An object is a compiled version of a regular expression, that is, a Java equivalent of a pattern. We can create a pattern object by using the compile() method of the Pattern class. The signature of the compile() method of the Pattern class is as follows:</p><p><strong>Flags — </strong>Flags in the compile() method change how the search is performed. Here are a few of them</p><ol><li><strong>CASE_INSENSITIVE</strong> — The case of letters will be ignored when performing a search</li><li><strong>UNICODE_CASE</strong>— Use it together with the <strong>CASE_INSENSITIVE</strong> flag to also ignore the case of letters outside of the English alphabet</li><li><strong>LITERAL</strong>— Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search.</li></ol><pre>public static Pattern compile(String regex)  </pre><p>Below is an example of the compile()method of the Pattern class:</p><pre>Pattern pattern = Pattern.compile(&quot;ab&quot;);</pre><h3><strong>Matcher: —</strong></h3><p>The matcher object can be used to check the specified pattern in the target string. Using the Pattern class’s matcher() method, we may generate an object for a matcher. The Pattern class’s matcher () method has the following signature:</p><pre>public Matcher matcher(CharSequence input)</pre><p>Here’s an example of the Pattern class’s matcher() method: —</p><pre>Matcher matcher = pattern.matcher(&quot;abcbcbcababacb&quot;);</pre><p>The Matcher class is present in the java.util.regex package. The following are some of the Matcher class’s most important methods:</p><ul><li><strong>boolean find() </strong>— It attempts to find the next match and returns true if it is available.</li><li><strong>int start()</strong> — return the start index of matched.</li><li><strong>int end()</strong> — return the end index of the matched.</li><li><strong>String group()</strong> — It returns a matched pattern.</li></ul><blockquote><strong>Note:-</strong> <strong>Pattern </strong>and <strong>Matcher </strong>classes are present in java.util.regex package and introduced in java1.4v.</blockquote><h3><strong>Character classes —</strong></h3><p>[abc] — Either ‘a’, or ‘b’ or ‘c’<br>[^abc] — Except ‘a’ and ‘b’ and ‘c’<br>[a-z] — Any Lowercase alphabet symbol from a to z<br>[A-Z] — Any Uppercase alphabet symbol from A to Z<br>[a-zA-Z] — Any alphabet symbol<br>[0–9] — Any Digit from 0–9<br>[a-zA-Z0–9] — Any alphanumeric symbol<br>[^a-zA-Z0–9] — Except alphanumeric symbol(special character only)</p><h3><strong>Predefine Character classes —</strong></h3><p>. — Any Character Except New Line<br>\d — Digit (0–9)<br>\D — Not a Digit (0–9)<br>\w — Word Character (a-z, A-Z, 0–9,_)<br>\W — Not a Word Character<br>\s — Whitespace (space, tab, newline)<br>\S — Not Whitespace(space, tab, newline)<br>\b — Word Boundary<br>\B — Not a Word Boundary<br>\uxxxx — Unicode charector specidied by the hexadecimal number xxxx</p><h3><strong>Quantifiers —</strong></h3><p>*— 0 or More<br>+ — 1 or More<br>? — 0 or One<br>{3} — Exact Number<br>{3,4}- Range of Number (Minimum, Mazimum)</p><blockquote>We can specify the number of occurrences to match using quantifiers.</blockquote><ul><li><strong>split() — </strong>To split the target string according to a specific pattern, we can use the Pattern class split(). The Pattern class’s split() method has the following signature:</li></ul><pre>public String[] split(CharSequence input)</pre><p>I’ve included a code snippet of the Pattern class’s split() method for your convenience:</p><pre>public class RegularExpression {<br><br>    public static void main(String[] args) {<br>        Pattern pattern = Pattern.compile(&quot;\\s&quot;);<br>        String[] splitString = pattern.split(&quot;Pattern class is present in java.util.regex&quot;);<br>        for (String text : splitString) {<br>            System.out.println(text);<br>        }<br><br>    }<br>}<br><br>/***<br>  Output -<br>    Pattern<br>    class<br>    is<br>    present<br>    in<br>    java.util.regex<br>***/<br></pre><p>Strings were divided in the above example depending on whitespace(\\s).</p><ul><li><strong>split() — </strong>The String class also contains the split() method. The string class split() method is used to split the target string according to a particular pattern.</li></ul><pre>public class RegularExpression {<br><br>    public static void main(String[] args) {<br>        String text = &quot;This is example of String class split() method&quot;;<br>        String[] strings = text.split(&quot;\\s&quot;);<br>        for (String s : strings) {<br>            System.out.println(s);<br>        }<br>    }<br>}<br><br>/***<br>Output<br>  This<br>  is<br>  example<br>  of<br>  String<br>  class<br>  split()<br>  method<br>***/<br></pre><p>Strings were divided in the above example depending on whitespace(\\s).</p><blockquote>Note: — The Pattern class split() method can take a target string as an argument, whereas the String class split() method can take a pattern as an argument.</blockquote><h3>StringTokenizer</h3><p>StringTokenizer is a class created specifically for tokenization tasks. The java.util package has a StringTokenizerclass.</p><pre>public class StringTokenizerDemo {<br><br>    public static void main(String[] args) {<br>     <br>        StringTokenizer tokenizer = new StringTokenizer(&quot;StringTokenizer class present in java.util package&quot;);<br>        while (tokenizer.hasMoreTokens()) {<br>            System.out.println(tokenizer.nextToken());<br><br>        }<br>    }<br>}<br><br>/***<br>  Output -<br>    StringTokenizer<br>    class<br>    present<br>    in<br>    java.util<br>    package<br>***/<br></pre><blockquote>Note : — The default regular expression for StringTokenizer is whitespace (\\s).</blockquote><p>We can also pass regular expressions as per the requirements below. I’m adding code snippets for your better understanding —</p><pre>StringTokenizer tokenizer = new StringTokenizer(&quot;05-21-2023&quot;,&quot;-&quot;);<br>while (tokenizer.hasMoreTokens()) {<br>    System.out.println(tokenizer.nextToken());<br>}<br>/***<br>  Output<br>    05<br>    21<br>    2023<br>***/</pre><p>I’ve included some regular expressions that are commonly used in programming:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8czrJhzYhANQ8oITS5ByCg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16e3c3cc9f43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the significance of enum in Java?]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/what-is-the-significance-of-enum-in-java-68dd044c299a?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/68dd044c299a</guid>
            <category><![CDATA[scjp]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ocjp]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Mon, 15 May 2023 11:34:29 GMT</pubDate>
            <atom:updated>2023-05-15T11:34:29.314Z</atom:updated>
            <content:encoded><![CDATA[<p>Here, using complete code samples and examples from real-world situations, I’ll explain the enum concept in more detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mxNzU1ZBkkk4nMTD" /><figcaption>Photo by <a href="https://unsplash.com/@jexo?utm_source=medium&amp;utm_medium=referral">Jexo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>If we want to represent a group of named constants, then we should go for enum.</p><pre>public enum Month {<br>    JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC<br>}</pre><p>The main objective of enum is to define our own data type (enumerated data type). I’m adding facts about enum —</p><ol><li>enum concept introduced in 1.5v</li><li>when compared with the old language Enum, Java Enum is more powerful.</li><li>every enum is internally implemented by the class concept.</li><li>Every enum constant is always public static final.</li><li>Every enum constant represents an object of type enum.</li></ol><pre>enum Color{<br>   RED, GREEN, BLUE  <br>}<br><br>class Color{<br>     public static final  Colour RED = new Colour();<br>     public static final  Colour GREEN = new Colour();<br>     public static final  Colour BLUE = new Colour();<br>}</pre><h3>Enum Declaration and Usages</h3><p>Because every enum constant is always public static final, we can access them directly by enum name.</p><pre>class EnumDemo {<br>    public static void main(String[] args) {<br>        Color color = Color.BLUE;<br>        System.out.println(color);<br>    }<br>}<br>/**<br>Output<br>  BLUE<br>**/<br></pre><p>It should be noted that the inside enum toString() method is internally implemented to return the constant’s name.</p><p>We can declare within or outside of the class, but not within the method. If we try to declare inside the method, we will get the compile-time error <strong><em>“enum type must not be local”.</em></strong></p><pre>// valid declaration - outside of the class<br>enum Wheel {<br>    TWO, THREE, FOUR,<br>}<br>class Vehicle {<br>}</pre><pre>//valid declaration - inside the class<br>class Vehicle {<br>    enum Wheel {<br>        TWO, THREE, FOUR,<br>    }<br>}</pre><pre>//invalid declartion - CE - &quot;Local enums are not supported at language level &#39;11&#39;&quot;<br>class Vehicle {<br>    public void getWheel(){<br>        enum Wheel {<br>            TWO, THREE, FOUR,<br>        }<br>    }<br>    <br>}</pre><h3>Modifiers</h3><p>If we declare an enum outside of the class, the applicable modifiers are: —</p><ol><li>public</li><li>&lt;default&gt;</li><li>strictfp</li></ol><p>If we declare an enum inside a class, then applicable modifiers are: —</p><ol><li>public</li><li>&lt;default&gt;</li><li>strictfp</li><li>private</li><li>protected</li><li>static</li></ol><h3>Enum with Switch()</h3><p>Until Java 1.4v, the only valid argument types for switch statements were byte, short, char, and int, but with Java 1.5v onwards, corresponding wrapper classes and enum types were permitted. The String type is supported beginning with Java 1.7v.</p><p>As a result, From Java 1.5v onwords, we can send an enum type as an argument to the switch statements.</p><pre>enum Month {<br>    JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC<br>}<br><br>class EnumDemo {<br>    public static void main(String[] args) {<br>        Month month = Month.MAY;<br>        switch (month) {<br>            case JAN:<br>            case MAR:<br>            case MAY:<br>            case JUL:<br>            case AUG:<br>            case OCT:<br>            case DEC:<br>                System.out.println(&quot;31 days in this month&quot;);<br>                break;<br>            case APR:<br>            case JUN:<br>            case SEP:<br>            case NOV:<br>                System.out.println(&quot;30 days in this month&quot;);<br>                break;<br>            case FEB:<br>                System.out.println(&quot;either 29 or 28 days in this month&quot;);<br>                break;<br>            /**<br>              case MONDAY:<br>                System.out.println(&quot;First day of week&quot;);<br>            **/<br>            //CE:-  unqualified enumeration constant name required<br>            default:<br>                System.out.println(&quot;Invalid month&quot;);<br>        }<br>    }<br><br>}<br><br>/***<br>Output <br>  31 days in this month<br>***/<br></pre><blockquote>Note — If we supply enum type as an argument to switch() statements, then each case label must be a legitimate enum constant; else, we will obtain the compile time error “<strong>unqualified enumeration constant name required.</strong>”</blockquote><h3>Enum with Inheritance</h3><p>I’m discussing enum facts with inheritance.</p><ol><li>Every enum is a direct child of a class in java.lang. Enum, and hence our own created enum, can’t extend any other enum (because Java won’t permit multiple inheritance).</li><li>Every enum is always explicitly final, thus we can’t create child enum for our enum.</li></ol><p>Because of the above, we can conclude that the inheritance concept is not applicable to enums explicitly. We can’t use the extends keyword for enum.</p><pre>//Case 1: - invalid <br>enum Month {<br>    JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC<br>}<br><br>enum Color extends Month{<br>    RED, GREEN, BLUE<br>}<br><br><br>//Case 2: - invalid<br>enum Month extends java.lang.Enum {<br>    JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC<br>}<br><br>//Case 3: - invalid (CE: enum type are not extendable/Cannot inherit from enum)<br>enum Color{<br>    RED, GREEN, BLUE<br>}<br><br>class EnumDemo extends Color {<br>   <br>}<br></pre><h3>java.lang.Enum</h3><p>Because every enum in Java is a direct child class of <strong>java.lang.Enum</strong>, this class serves as the root class for all enums. It is an abstract class that implements <strong>Serializable </strong>and <strong>Comparable </strong>interfaces and is a direct child class of the <strong>Object </strong>class.</p><h3>values()</h3><p>Every enum contains values() by default, which lists all of the values contained within the enum.</p><pre>Month[] months = Month.values();</pre><blockquote>Note: — The values() method not present in <strong>java.lang.Enum</strong> and <strong>Object </strong>class. <strong>enum</strong> keyword implicitly provide this method.</blockquote><h3>ordinal()</h3><p>The order of constants within an enum is significant, and we may describe this order by using ordinal values. The <strong>ordinal()</strong> method is used to determine the ordinal value of an enum constant.</p><pre>public final int ordinal()</pre><blockquote>Note: — ordinal values are 0 based like array indexes</blockquote><pre><br>enum Color {<br>    RED, GREEN, BLUE<br>}<br><br>class EnumDemo {<br><br>    public static void main(String[] args) {<br>        Color[] colors = Color.values();<br>        for (Color color: colors){<br>        System.out.println(color+&quot;.....&quot;+color.ordinal());<br>        }<br>    }<br><br>}<br><br>/****<br>Output -<br>  RED.....0<br>  GREEN.....1<br>  BLUE.....2<br>****/<br></pre><h3>Specialty of Java Enum</h3><p>In the old language enum, we could only accept a set of named constants, but in Java enum, we could also take methods, member variables, constructors, and so on. As a result, Java’s enum is more powerful than the old-language enum.</p><p>Even inside a Java enum, we can declare the main method and run the enum class directly.</p><pre>enum Month {<br>    JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC;<br><br>    public static void main(String[] args) {<br>        System.out.println(&quot;This is Month enum method....&quot;);<br>    }<br>}<br><br>/***<br>Output -<br>  This is Month enum method....<br>***/<br></pre><blockquote>Note: If we are taking any other members, such as method, variable, etc., in addition to constants, the list of constants should be in the first line and must end with <strong><em>;</em></strong></blockquote><p>I am going to use a combination of enums here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8eAQ7LHoTPIOmeMHJNOHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*aZuDOr5h39hiNvyC_pAoYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3jlFJuy7SQvbozgS0daBg.png" /></figure><blockquote>If we use an extra member like method and variable within enum, the mandatory first line must have at least one constant;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*blTXhOKnw317Kh9lqAnCRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*HnQti8GEjX246rXGz-XFgw.png" /></figure><p>In any case, an empty enum is a valid Java syntax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*hatHnuA-XWGIsa7Hg3Zckw.png" /></figure><h3>Enum with Constructor</h3><p>An enum can contain constructors. The enum constructor will be executed separately for every enum constant at the time of enum class loading.</p><pre><br>enum Color {<br>    RED, GREEN, BLUE;<br><br>    Color() {<br>        System.out.println(&quot;Color constructor ....&quot;);<br>    }<br>}<br><br>class EnumDemo {<br><br>    public static void main(String[] args) {<br>        Color favoriteColor = Color.RED;<br>        System.out.println(&quot;Hey, mine favorite color:  &quot; + favoriteColor);<br>    }<br><br>}<br><br>/***<br>Output -<br>  Color constructor ....<br>  Color constructor ....<br>  Color constructor ....<br>  Hey, mine favorite color:  RED<br>***/<br></pre><p>We can’t create an enum object directly, and hence we can’t invoke the enum constructor directly.</p><pre>Color color = new Color();<br><br>/****<br>Compile-Time Error - Enum types cannot be instantiated<br>****/<br></pre><p>Now it is time to move on to the complete example with all the concepts of enum that I have explained so far for the sake of convenience —</p><pre>enum Month {<br>    JAN(31), FEB, MAR(31), APR(30), MAY(31), JUN(30),<br>    JUL(31), AUG(31), SEP(30), OCT(31), NOV(30), DEC(31);<br><br>    int days;<br><br>    Month(int days) {<br>        this.days = days;<br>    }<br><br>    Month() {<br>        this.days = 28;<br>    }<br><br>    int getDays() {<br>        return days;<br>    }<br>}<br><br>class EnumDemo {<br><br>    public static void main(String[] args) {<br>        Month[] months = Month.values();<br>        for (Month month : months) {<br>            System.out.println(month + &quot;   &quot; + month.getDays());<br>        }<br>    }<br><br>}<br><br>/******<br>Output - <br>  JAN   31<br>  FEB   28<br>  MAR   31<br>  APR   30<br>  MAY   31<br>  JUN   30<br>  JUL   31<br>  AUG   31<br>  SEP   30<br>  OCT   31<br>  NOV   30<br>  DEC   31<br>******/<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68dd044c299a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create our own immutable class in Java]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/how-to-create-our-own-immutable-class-in-java-be7974540369?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/be7974540369</guid>
            <category><![CDATA[final]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ocjp]]></category>
            <category><![CDATA[scjp]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Mon, 08 May 2023 05:07:35 GMT</pubDate>
            <atom:updated>2023-05-08T05:07:35.745Z</atom:updated>
            <content:encoded><![CDATA[<p>This post will demonstrate how to create our own immutable class in Java. Later on, we’ll go over the final vs. immutable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*39t9lZNsHFnJ1W5B4sAXBg.png" /></figure><h3>Immutable</h3><p>We can’t modify an object once we’ve created it. Any modifications to the content will result in the creation of a new object. If the content remains unchanged, the existing object is reused; this behavior is nothing but immutable.</p><p>String and all wrapper classes (such as Integer, Byte, Boolean, Long, and so on) are the most commonly used immutable classes. So I’m using this class to demonstrate immutable concepts —</p><pre>public class ImmutableDemo {<br>    <br>    public static void main(String[] args) {<br>        String str = new String(&quot;Java immutable demo code&quot;);<br>        String upperCase = str.toUpperCase();<br>        String lowerCase = str.toLowerCase();<br>        System.out.println(&quot;Str: &quot; + str);<br>        System.out.println(&quot;upperCase: &quot; + upperCase);<br>        System.out.println(&quot;loweCase: &quot; + lowerCase);<br>    }<br>}<br><br>/** <br>  Output -<br>  Str: Java immutable demo code<br>  upperCase: JAVA IMMUTABLE DEMO CODE<br>  loweCase: java immutable demo code<br>**/</pre><p>Here I’m adding internal representation that occurs during runs above the code —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*Qe8vKrD-SjU6Pz01bLFM1A.jpeg" /><figcaption>Internal representation of above code</figcaption></figure><p>Now is the time to develop our own immutable class, so here’s a code snippet to help you understand: —</p><pre>final public class ImmutableDemo {<br>    private int i;<br><br>    ImmutableDemo(int i) {<br>        this.i = i;<br>    }<br><br>    public ImmutableDemo modify(int i) {<br>        if (this.i == i)<br>            return this;<br>        else<br>            return new ImmutableDemo(i);<br>    }<br>}<br><br>public class Demo{<br>    public static void main(String[] args) {<br>        ImmutableDemo immutableDemo1 = new ImmutableDemo(10);<br>        ImmutableDemo immutableDemo2 = immutableDemo1.modify(100);<br>        ImmutableDemo immutableDemo3 = immutableDemo1.modify(10);<br><br>        System.out.println(immutableDemo1 == immutableDemo2);<br>        System.out.println(immutableDemo1 == immutableDemo3);<br>        <br>    }<br>}<br><br>/**<br>  Output<br>  false<br>  true<br>**/<br></pre><h3>final vs immutability</h3><p>Immutability is applicable to objects but not variables, whereas final is applicable to variables but not objects.</p><p>Even if we declare the reference variable as final, we will not achieve immutability. We can make any changes to the associated objects. However, we cannot make reassignments on that variable; thus, final and immutable are two different concepts.</p><p>Below, I added the code snippet for declaring the reference variable as final and its behaviors —</p><pre>final StringBuffer stringBuffer = new StringBuffer(&quot;Demo String &quot;);<br>System.out.println(stringBuffer);<br>stringBuffer.append(&quot;Example&quot;);<br>System.out.println(stringBuffer);<br>stringBuffer = new StringBuffer(&quot;&quot;);  //Compile Time Error - Cannot assign a value to final variable &#39;stringBuffer&#39;<br><br>/**<br>  Output<br>  Demo String<br>  Demo String Example<br>**/<br></pre><blockquote>In the above code example, stringBuffer is a final type of reference variable. Initially, it holds “Demo String” content, and after that, using the append() method, we can easily modify content. If we try to reassign to that variable, then we will get a compile-time error saying “Cannot assign a value to the final variable ‘stringBuffer’”. Hence, immutable and final are both different concepts.</blockquote><p>Below, I have added recommended ways in which we can use final and immutable concepts: —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*xcJu-mczRh6zkOzLeRxemg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be7974540369" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serialization and Deserialization in Java Part: 5 (serialVersionUID)]]></title>
            <link>https://medium.com/@tararamgoyal4_92353/serialization-and-deserialization-in-java-part-5-serialversionuid-854daa8eade0?source=rss-30b35ab11904------2</link>
            <guid isPermaLink="false">https://medium.com/p/854daa8eade0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[scjp]]></category>
            <category><![CDATA[ocjp]]></category>
            <category><![CDATA[serialversionuid]]></category>
            <dc:creator><![CDATA[TARA RAM GOYAL]]></dc:creator>
            <pubDate>Wed, 03 May 2023 04:01:33 GMT</pubDate>
            <atom:updated>2023-05-03T04:01:33.936Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I’ll explain about externalization and serialVersionUID and its importance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*-Jvkk3PLVBsTlvHED2G9tQ.jpeg" /></figure><h3>Externalization</h3><p>Everything is handled by the JVM in serialization, and the programmer has no control. It is always feasible to save a entire object to a file in serialization, but it is not possible to save a portion of an object to a file. This may result in a performance issue. To address this issue, we should consider externalisation. The fundamental advantage of externalisation over serialization is that the programmer handles everything and the JVM has no control. Depending on our needs, we can persist either the entire objec or a portion of it, which enhances system efficiency.</p><p>To allow any Java object to be externalized, the corresponding class must implement the <strong><em>Externalizable </em></strong>interface. Externalizable is a child interface of the <strong><em>Serializable </em></strong>interface and defines two methods, writeExternal() and readExternal().</p><p>An externalizable interface has the following methods:</p><pre>void writeExternal(ObjectOutput out) throws IOException;</pre><p>This method will be executed automatically during serialization. Within this method, we must write code to save the required variable(s) to the file.</p><pre>void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;</pre><p>The method is executed automatically during deserialization. Within this method, we must write code to read the required variable(s) from the file and assign them to the current object.</p><p>However, during deserialization, JVM will create a separate object by calling the public no-argument constructor on that object. The readExternal() method will then be called by the JVM.</p><p>Therefore, a public no-argument constructor must be present in every Externalizable implemented class; otherwise, we will receive an <strong><em>InvalidClassException </em></strong>runtime exception.</p><p>For more clarity I’m adding code snippet for you -</p><pre>public class ExternalizableDemo implements Externalizable {<br><br>    String name;<br>    int age;<br>    float salary;<br><br>    public ExternalizableDemo() {<br>        System.out.println(&quot;no-arg constructor calling ...&quot;);<br>    }<br><br>    public ExternalizableDemo(String name, int age, float salary) {<br>        this.name = name;<br>        this.age = age;<br>        this.salary = salary;<br>    }<br><br>    @Override<br>    public void writeExternal(ObjectOutput out) throws IOException {<br>        out.writeObject(name);<br>        out.writeObject(age);<br>    }<br><br>    @Override<br>    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<br>        name = (String) in.readObject();<br>        age = (Integer) in.readObject();<br>    }<br><br>    public static void main(String[] args) throws IOException, ClassNotFoundException {<br>        ExternalizableDemo demo = new ExternalizableDemo(&quot;Anky&quot;, 25, 45200.25f);<br><br><br>        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(&quot;info.txt&quot;));<br>        objectOutputStream.writeObject(demo);<br><br><br>        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(&quot;info.txt&quot;));<br><br>        ExternalizableDemo externalizableDemo = (ExternalizableDemo) objectInputStream.readObject();<br><br>        System.out.println(&quot;name: &quot; + externalizableDemo.name + &quot;\nage: &quot; + externalizableDemo.age + &quot;\nsalary: &quot; + externalizableDemo.salary);<br><br><br>    }<br>}<br><br>/**<br>Output<br>  no-arg constructor calling ...<br>  name: Anky<br>  age: 25<br>  salary: 0.0<br>**/<br></pre><p>In the above example, I simply want the name and age to persist, not the salary. I can achieve this by using the Externalizable interface’s writeExternal() and readExternal() methods. Certain variables will return their default values during deserialization if we choose not to persist them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*YJqyorCwAcjEP0bHbNc8tQ.jpeg" /><figcaption>Internal representation of Externalizable</figcaption></figure><p>Note — <strong>transient</strong> modifier will be crucial in serialization, but they won’t be relevant at all in externalisation. <strong>transient</strong> are obviously not necessary for externalisation.</p><p>Have a quick look at Serialization vs Externalization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*_03IOHJxLlqNtsC6zJzvLw.png" /><figcaption>Serialization vs Externalization</figcaption></figure><h3>serialVersionUID</h3><p>In serialization, both sender and receiver need not be the same person, need not use the same machine, and need not be at the same location. The sender and receiver may be different, or they may use different machines and be at different locations.</p><p>In serialization, both sender and receiver should have the same class file at the beginning, which just states that the object is travelling from sender to receiver.</p><p>At the time of serialization, for every object sent on the sender side, the JVM will save a unique identifier. The JVM is responsible for generating this unique identifier based on the <strong>.class</strong> file. At the time of deserialization, the receiver-side JVM will compare the unique identifier associated with the object with the local <strong>.class</strong> unique identifier. If both are matched, then only deserialization will be performed; otherwise, we will get a runtime exception saying <strong>InvalidClassException. </strong>This unique identifier is nothing but <strong>serialVersionUID</strong>.</p><p>Issues with depending upon the default serialVersionUID generated by the JVM are as follows:</p><ol><li>Both sender and receiver should use the same JVM with respect to vendor, platform, and version; otherwise, the receiver will be unable to de-serialise.</li><li>Both sender and receiver should use the same .class file version; after serialization, if there are any changes in the .class file at the receiver’s side, the receiver will also be unable to de-serialise.</li><li>To generate serialVersionUID internally, the JVM may use a complex algorithm, which may create performance issues.</li><li>We can solve the above issues by configuring our own <strong>serialVersionUID</strong>. We can configure our own <strong>serialVersionUID </strong>as follows:</li></ol><pre>private static final long serialVersionUID = 1L;</pre><p>I have an object of the Employee class that I want to serialise. Below is my Employee class object: —</p><pre>public class Employee implements Serializable {<br><br>    <br>    int ssn;<br>    String name;<br>    int age;<br>    float salary;<br><br>    public Employee() {<br>    }<br><br>    public Employee(int ssn, String name, int age, float salary) {<br>        this.ssn = ssn;<br>        this.name = name;<br>        this.age = age;<br>        this.salary = salary;<br>    }<br>}</pre><p>Here, I’m serializing an object from the Employee class with the above class object at the sender end; the following is my code:</p><pre>public class Sender {<br><br>    public static void main(String[] args) throws IOException {<br>        Employee employee = new Employee(1,&quot;Anky&quot;, 25, 45200.25f);<br>        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(&quot;emp.txt&quot;));<br>        objectOutputStream.writeObject(employee);<br>    }<br>}</pre><p>The Employee class is used for deserialization on the receiver side in the example below.</p><pre>public class Employee implements Serializable {<br><br>    String name;<br>    int age;<br>    float salary;<br><br>    public Employee() {<br>    }<br><br>    public Employee(String name, int age, float salary) {<br>        this.name = name;<br>        this.age = age;<br>        this.salary = salary;<br>    }<br>}</pre><p>Here, I’m using the above class at the receiver end to deserialize an object of the Employee class, and the following is my code:</p><pre>public class Receiver {<br><br>    public static void main(String[] args) throws IOException, ClassNotFoundException {<br>        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(&quot;emp.txt&quot;));<br><br>        Employee employee = (Employee) objectInputStream.readObject();<br><br>        System.out.println(&quot;name: &quot; + employee.name + &quot;\nage: &quot; + employee.age + &quot;\nsalary: &quot; + employee.salary);<br><br>    }<br>}</pre><p>On the sender side, I’m using an object of the Employee class with ssn, name, age, and salary. But at the receiver side, I have an object of Employee class with name, age, and salary; at the receiver end, the ssn member variable is not parent, hence both sides are using different .class files, and JVM generates two different unique identification numbers (serialVersionUID), and these two are not matched at the time of deserialization, hence the below error at the receiver end experianced below error —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAJLTS2UM1Tn7wqcxDHLlw.png" /></figure><p>To resolve the above issue, both ends must define a custom serialVersionUID as shown below:</p><pre>public class Employee implements Serializable {<br><br>    private static final long serialVersionUID = 1L;    <br>    int ssn;<br>    String name;<br>    int age;<br>    float salary;<br><br>    public Employee() {<br>    }<br><br>    public Employee(int ssn, String name, int age, float salary) {<br>        this.ssn = ssn;<br>        this.name = name;<br>        this.age = age;<br>        this.salary = salary;<br>    }<br>}</pre><p>In this case, serializing an employee object at the sender side</p><pre>public class Sender {<br><br>    public static void main(String[] args) throws IOException {<br>        Employee employee = new Employee(1,&quot;Anky&quot;, 25, 45200.25f);<br>        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(&quot;emp.txt&quot;));<br>        objectOutputStream.writeObject(employee);<br>    }<br>}</pre><p>The object that Employee will use for deserialization is shown below (without the SSN member variable).</p><pre>public class Employee implements Serializable {<br><br>    private static final long serialVersionUID = 1L;<br>    String name;<br>    int age;<br>    float salary;<br><br>    public Employee() {<br>    }<br><br>    public Employee(String name, int age, float salary) {<br>        this.name = name;<br>        this.age = age;<br>        this.salary = salary;<br>    }<br>}</pre><p>The deserializing object of the Employee class is used here.</p><pre>public class Receiver {<br><br>    public static void main(String[] args) throws IOException, ClassNotFoundException {<br>        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(&quot;emp.txt&quot;));<br><br>        Employee employee = (Employee) objectInputStream.readObject();<br><br>        System.out.println(&quot;name: &quot; + employee.name + &quot;\nage: &quot; + employee.age + &quot;\nsalary: &quot; + employee.salary);<br><br>    }<br>}</pre><p>In the above, the sender side uses an employee object with ssn, name, age, and salary, and the receiver side uses an employee object with a name, age, and salary. and both sides use different class files In this case, we do not experience any kind of issue during serialization and deserialization because both sides use serialVersionUID. Below is the output after deserializing an object:</p><p>name: Anky<br>age: 25<br>salary: 45200.25</p><p>Note: — IDE’s promote programmer to enter serialiVersionUID explicitly. Some IDE’s may generate serialVersionUID automatically.</p><p>We won’t experience any problems during deserialization if we use our own unique serialVersionUID and make any changes on the receiver side. In this scenario, maintaining the same JVM version, vendor, or platform will not be necessary for the sender and recipient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=854daa8eade0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>