<?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 Kruti Dave on Medium]]></title>
        <description><![CDATA[Stories by Kruti Dave on Medium]]></description>
        <link>https://medium.com/@er.janik26?source=rss-8ca4afd7e6dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1J4F0Uj8RjmUNRgs</url>
            <title>Stories by Kruti Dave on Medium</title>
            <link>https://medium.com/@er.janik26?source=rss-8ca4afd7e6dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:01:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@er.janik26/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[A Deep Dive into Object-Oriented Programming (OOP): Interview Questions and Explanations — 1]]></title>
            <link>https://blog.devgenius.io/a-deep-dive-into-object-oriented-programming-oop-interview-questions-and-explanations-1-60030e94c7fe?source=rss-8ca4afd7e6dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/60030e94c7fe</guid>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[java-oops-concept]]></category>
            <category><![CDATA[abstract-class-in-java]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <category><![CDATA[static-in-java]]></category>
            <dc:creator><![CDATA[Kruti Dave]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 05:41:56 GMT</pubDate>
            <atom:updated>2023-10-11T10:38:36.879Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Deep Dive into Object-Oriented Programming (OOP): Interview Questions and Explanations — 1</h3><p>In this post, we will explore a range of interview questions on OOP concepts and related topics. If you’d like a refresher on the basics, you can refer to our previous blog post [<a href="https://blog.devgenius.io/java-backend-interview-preparation-part-2-4a488f39d569">Java OOPs Concepts Illustrated: GitHub Demos for Developers</a>] where we introduced the fundamental OOP principles.</p><p>Let’s get started with some challenging OOP interview questions:</p><p><strong>What is the difference between an abstract class and an interface in OOP? When would you use one over the other?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*ieru5xNbL8y9Roq4tPmgtQ.png" /></figure><h4><strong>Can abstract class have constructor in Java? or </strong>why do abstract classes in Java have constructors?</h4><p>An abstract class can have constructors just like any other class, and these constructors can be used for various purposes, such as initializing instance variables or performing other setup tasks.<br>In below example, created constructor to initialize items list using constructor which will be used in calculateTotalPrice() and displayCart() method.</p><pre>package com.demo.kruti.oops.abstraction;<br><br>import com.demo.kruti.oops.models.Product;<br>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.stream.DoubleStream;<br><br>public abstract class ShoppingCart {<br>  protected List&lt;Product&gt; items; // Store items in the cart<br><br>  public ShoppingCart() {<br>    items = new ArrayList&lt;&gt;();<br>  }<br><br>  // Abstract method to add a product to the cart<br>  public abstract void addItem(Product product);<br><br>  // Abstract method to remove a product from the cart<br>  public abstract void removeItem(Product product);<br><br>  public double calculateTotalPrice() {<br>    return items.stream().flatMapToDouble(product -&gt; DoubleStream.of(product.getPrice())).sum();<br>  }<br><br>  // Abstract method to display the cart contents<br>  public void displayCart() {<br>    for (Product item : items) {<br>      System.out.println(item.getName() + &quot; - Rs&quot; + item.getPrice());<br>    }<br>  }<br>}</pre><p><strong>Mandatory for a class which is declared as abstract to have at least one abstract method? Explain.</strong></p><p>No, it is not compulsory for an abstract class in Java to have at least one abstract method. An abstract class can have zero or more abstract methods, but it can also have concrete methods (methods with implementations) just like any regular class. The presence of abstract methods is just one characteristic of an abstract class, but it’s not a strict requirement.</p><p><strong>Can we instantiate an abstract class which does not have any abstract method? What is a need of constructors in abstract class if not using for initialization?</strong></p><p>No. Abstract classes are not mean to be initiated. It will not allow to create even don&#39;t have any abstract method. Please check and try your self — [ <a href="https://github.com/djavaphp/java8_features/commit/35fa784a48fb8fd99207094ad3a015d11dc2b6fb">JI-LR : Can we instantiate a class which does not have even a single … · djavaphp/java8_features@35fa784 (github.com)</a> ]</p><p>we can’t create objects to abstract classes, but we can create objects to their sub classes. From sub class constructor, there will be an implicit call to super class constructor. That’s why abstract classes should have constructors. Even if you don’t write constructor for your abstract class, compiler will keep default constructor.</p><p><strong>Can we create final abstract class?</strong></p><p>The final and abstract modifiers are mutually exclusive, meaning you cannot use them together on the same class.</p><p>A final class cannot be subclassed, and it is considered the endpoint of the inheritance hierarchy. You use the final keyword to indicate that a class should not have any subclasses.</p><p>An abstract class, on the other hand, is meant to be subclassed. It is a class that can have abstract methods (methods without implementations) that must be implemented by its concrete subclasses.</p><p><strong>Is it possible to create synchronized abstract method?</strong></p><p>An abstract method cannot be declared as synchronized. But methods which override abstract methods can be declared as synchronized.</p><p><strong>Is it possible to declare abstract method as static or final?</strong></p><p>Abstract methods are meant to be overridden and implemented by subclasses.</p><p>Static methods, on the other hand, belong to the class itself and are not associated with instances.</p><p>Final methods cannot be overridden by subclasses; they are considered as sealed or unchangeable implementations in the inheritance.</p><p>So due to their behavioural change these modifiers are not compatible with the concept of abstract methods.</p><p><strong>What is the use of super keyword?</strong></p><p>The super keyword is used to refer to the superclass or parent class of the current class.</p><p><strong>What is the static keyword in Java, and how is it used?</strong></p><p>The static keyword can be used for field, method , block and nested class.</p><p>Static <strong>variable </strong>/ <strong>field </strong>is shared by all instances of a class. There is only one copy of a static field in a memory and that is associated with class.</p><p>Static methods are associated with class but not with any instace of the class. It can be called by using ClassName.methodName();</p><p>Static initialization blocks are executed once when the class is first loaded, before any instances are created, or static methods are called.<br>Tt is typically used for performing one-time initialization tasks for the class itself.</p><pre>package com.demo.kruti.oops.staticdemo;<br><br>//Outer class can be created as static:<br>public class StaticDemo {<br>  static {<br>    // Static initialization block<br>    System.out.println(&quot;Load Masters/DB connections etc.&quot;);<br>  }<br>  static int value;<br>  static void print(){<br>    System.out.println(&quot;VALUE :&quot;+value);<br>  }<br>  public static void main(String[] str){<br>    StaticDemo.print();<br>    StaticDemo.value = 100;<br>    StaticDemo.print();<br>    StaticDemo.NestedStaticDemo.print();<br>  }<br><br>  static class NestedStaticDemo {<br>    static{<br>      System.out.println(&quot;Initialized Nested Class&quot;);<br>    }<br>    static void print(){<br>      System.out.println(&quot;Print Nested called.&quot;);<br>    }<br>  }<br>}</pre><p><strong>Please refer to my previous post for the answers to the questions listed below, with the link provided at the top.</strong></p><p>What are the four pillars of Object-Oriented Programming (OOP), and why are they important in Java?<br>What is a class in Java, and how is it different from an object?<br>Explain the concepts of inheritance and polymorphism in Java. Provide examples.<br>What is encapsulation, and why is it considered a fundamental concept in OOP?<br>What are access modifiers in Java, and how do they control the visibility of class members?</p><p>I plan to address various questions related to Object-Oriented Programming (OOPS) concepts and core Java in upcoming blog posts. I’ll continually update this post with links to those articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60030e94c7fe" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/a-deep-dive-into-object-oriented-programming-oop-interview-questions-and-explanations-1-60030e94c7fe">A Deep Dive into Object-Oriented Programming (OOP): Interview Questions and Explanations — 1</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Backend Interview Preparation: Part 2]]></title>
            <link>https://blog.devgenius.io/java-backend-interview-preparation-part-2-4a488f39d569?source=rss-8ca4afd7e6dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a488f39d569</guid>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[abstract]]></category>
            <dc:creator><![CDATA[Kruti Dave]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 17:33:10 GMT</pubDate>
            <atom:updated>2023-10-06T11:41:42.913Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java OOPs Concepts Illustrated: GitHub Demos for Developers</h3><p>Before delving into the detailed discussion of Java concepts, I recommend checking out this link for a comprehensive list of topics you should be familiar with. It covers all the essential areas of Java knowledge.</p><p><a href="https://medium.com/@er.janik26/prepare-for-java-backend-interview-part-1-af805a1bb45b">From Novice to Pro: Your Journey through Core Java | Medium</a></p><p>We’ll be taking a closer look at each topic individually in this blog post and the upcoming ones.</p><p>In this post, I’ll be delving deeper into the topic of Object-Oriented Programming (OOP).</p><p>Certainly! Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of “<strong>objects</strong>.” It’s a way of structuring and designing software that models real-world entities, their properties, and their interactions. Java is a popular programming language that embraces OOP principles. Here are the key principles of OOP and how they apply to Java:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*0PiKOVy1HV8xnhMIrYNVrA.png" /></figure><p>Before delving into the intricacies of Object-Oriented Programming (OOP) concepts, let’s understand the fundamental of building blocks: Classes and Objects.</p><ul><li><strong>Class</strong>: In OOP, a class is a blueprint or template for creating objects. It defines the attributes (data members) and methods (functions) that the objects of the class will have.</li><li><strong>Object</strong>: An object is an instance of a class, created based on the class’s blueprint. Objects can interact with each other by invoking methods and accessing attributes.</li></ul><p>Now that we have a grasp of what classes and objects are, let’s dive deeper into the realm of Object-Oriented Programming (OOP) concepts.</p><ol><li><strong>Encapsulation</strong>:</li></ol><p>Encapsulation refers to the bundling of data (attributes/ properties) and the methods (functions) that operate on that data within a single unit, i.e., a class. It hides the internal details of how an object works and exposes only what’s necessary.</p><p>In Java, encapsulation is achieved using access modifiers and getter and setter methods:</p><p><strong>Access Modifiers</strong>: Java provides four types of access modifiers to control the visibility of fields and methods within a class:</p><p><strong><em>public</em></strong>: Accessible from anywhere.<br><strong><em>private</em></strong>: Accessible only within the same class.<br><strong><em>protected</em></strong>: Accessible within the same class, its subclasses (inheritance), and classes in the same package.<br><strong><em>default </em></strong>(package-private): Accessible only within the same package.</p><p><strong>Getter and Setter Methods</strong>: To provide controlled access to class fields, you create getter and setter methods within the class. These methods allow you to get and set the values of private fields while enforcing any necessary validation or logic.</p><pre>public class Product {<br>  //Added access-modifier so that another class need to set it using constructor or setter.<br>  private final String name;<br>  private final double price;<br>  private int quantity;<br><br>  // Constructor<br>  public Product(String name, double price, int quantity) {<br>    this.name = name;<br>    this.price = price;<br>    this.quantity = quantity;<br>  }<br><br>  // Getter method for name<br>  public String getName() {<br>    return name;<br>  }<br><br>  // Getter method for price<br>  public double getPrice() {<br>    return price;<br>  }<br><br>  // Getter method for quantity<br>  public int getQuantity() {<br>    return quantity;<br>  }<br><br>  // Setter method for quantity with validation<br>  // Based on my requirement I will create setter method, In this example I am only allowing to set qty.<br>  public void setQuantity(int quantity) {<br>    if (quantity &gt;= 0) {<br>      this.quantity = quantity;<br>    } else {<br>      System.out.println(&quot;Quantity cannot be negative.&quot;);<br>    }<br>  }<br><br>  // Method to calculate the total cost for a given quantity<br>  public double calculateTotalCost(int quantityToBuy) {<br>    if (quantityToBuy &gt;= 0 &amp;&amp; quantityToBuy &lt;= quantity) {<br>      return price * quantityToBuy;<br>    } else {<br>      System.out.println(&quot;Invalid quantity to buy.&quot;);<br>      return 0.0;<br>    }<br>  }<br><br>  public void displayProductInfo() {<br>    System.out.println(&quot;Product Name: &quot; + name);<br>    System.out.println(&quot;Price: &quot; + price);<br>    System.out.println(&quot;Quantity in stock: &quot; + quantity);<br>  }<br>}</pre><p>2. <strong>Inheritance</strong>:</p><p>Inheritance is a mechanism that allows a class (subclass or derived class) to inherit properties and behaviors from another class (superclass or base class). It promotes code reuse and the creation of a hierarchy of classes.</p><p>In Java, you can use the extends keyword to create subclasses.</p><p>I have created 2 childs of Product classed we used for Encapsulation example.</p><pre>package com.demo.kruti.oops.models;<br><br>// The Electronics class is another subclass of Product<br>public class Electronics extends Product {<br>  private final String brand;<br>  private final String model;<br><br>  public Electronics(String name, double price, int quantity, String brand, String model) {<br>    super(name, price, quantity); // Call the constructor of the superclass<br>    this.brand = brand;<br>    this.model = model;<br>  }<br><br>  // Not adding any Getter and setter methods as of now as I don&#39;t it now<br>  @Override<br>  public void displayProductInfo() {<br>    super.displayProductInfo(); // Call the superclass method<br>    System.out.println(&quot;Brand: &quot; + brand);<br>    System.out.println(&quot;Model: &quot; + model);<br>  }<br>}</pre><pre>package com.demo.kruti.oops.models;<br><br>//Book class is a subclass of Product<br>public class Book extends Product {<br>  private String author;<br>  private int pageCount;<br><br>  public Book(String name, double price, int quantity, String author, int pageCount) {<br>    super(name, price, quantity); // Call the constructor of the superclass<br>    this.author = author;<br>    this.pageCount = pageCount;<br>  }<br><br>  @Override<br>  public void displayProductInfo() {<br>    super.displayProductInfo(); // Call the superclass method<br>    System.out.println(&quot;Author: &quot; + author);<br>    System.out.println(&quot;Page Count: &quot; + pageCount);<br>  }<br>}</pre><p>Main Class to use above classes.</p><pre>package com.demo.kruti.oops;<br><br>import com.demo.kruti.oops.models.Book;<br>import com.demo.kruti.oops.models.Electronics;<br><br>public class InheritanceDemo {<br>  public static void main(String[] args) {<br>    Book book = new Book(&quot;Java Concepts&quot;, 300, 50, &quot;John Doe&quot;, 400);<br>    Electronics laptop = new Electronics(&quot;Laptop&quot;, 800.0, 10, &quot;DELL&quot;, &quot;LATITUDE&quot;);<br><br>    System.out.println(&quot;Books :&quot;);<br>    book.displayProductInfo();<br>    System.out.println(&quot;\n&quot;);<br>    System.out.println(&quot;Electronics :&quot;);<br>    laptop.displayProductInfo();<br>  }<br>}</pre><p>The ‘Product’ class serves as the primary or superclass, while ‘Electronics’ and ‘Books’ inherit shared attributes like name, price, and quantity from the ‘Product’ class. <br>Now, let’s take a look at the ‘displayProductInfo()’ method within these classes. We override this method in the child classes to access and display properties from the ‘Product’ class, along with additional information specific to each subclass.</p><p>3. <strong>Polymorphism</strong>:</p><p>Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables dynamic method binding, where the appropriate method implementation is determined at runtime.</p><p>In Java, polymorphism can be achieved through method overriding and interfaces.</p><p>one of the examples of method overriding already covered with Inheritance where we override displayProductInfo() of Product into Child classes. <br>Let&#39;s me give you more demo using interfaces.</p><p>PaymentMethod Interface :</p><pre>package com.demo.kruti.oops.polymorphism;<br><br>//Main interface <br>public interface PaymentMethod {<br>  void processPayment(double amount);<br>}</pre><pre>package com.demo.kruti.oops.polymorphism;<br><br>//implement interface and override processPayment() and logic to it.<br>public class CreditCardPayment implements PaymentMethod {<br>  private final String cardNumber;<br><br>  public CreditCardPayment(String cardNumber) {<br>    this.cardNumber = cardNumber;<br>  }<br><br>  @Override<br>  public void processPayment(double amount) {<br>    // we can validate card and processing of payment logic<br>    System.out.println(&quot;Paid Rs &quot; + amount);<br>  }<br>}</pre><pre>package com.demo.kruti.oops.polymorphism;<br><br>//implement interface and override processPayment() and logic to it.<br>public class GPayPayment implements PaymentMethod {<br>  private final String mobile;<br><br>  public GPayPayment(String mobile) {<br>    this.mobile = mobile;<br>  }<br><br>  @Override<br>  public void processPayment(double amount) {<br>    // Here I will implement Gpay logic based on mobile and verified with OTP etc<br>    System.out.println(<br>        &quot;Paid Rs&quot; + amount + &quot; using Gpay account associated with mobile no: &quot; + mobile);<br>  }<br>}</pre><pre>package com.demo.kruti.oops.polymorphism;<br><br>import com.demo.kruti.oops.models.Book;<br>import com.demo.kruti.oops.models.Electronics;<br>import com.demo.kruti.oops.models.Product;<br><br>public class PolymorphismDemo {<br>  public static void main(String[] args) {<br>    // Create different product types<br>    Product book =new Book(&quot;Java Concepts&quot;, 300, 50, &quot;John Doe&quot;, 400);<br>    Product laptop = new Electronics(&quot;Laptop&quot;, 800.0, 10, &quot;DELL&quot;, &quot;LATITUDE&quot;);<br><br>    // Calculate and display prices with polymorphism - <br>    // we can override this into Book and Electronics<br>    System.out.println(&quot;Book Price: $&quot; + book.calculatePrice());<br>    System.out.println(&quot;Laptop Price: $&quot; + laptop.calculatePrice());<br><br>    // Create different payment methods<br>    PaymentMethod creditCard = new CreditCardPayment(&quot;1234-5678-9012-3456&quot;);<br>    PaymentMethod gpay = new GPayPayment(&quot;80000002344&quot;);<br><br>    // Process payments with polymorphism<br>    creditCard.processPayment(book.calculatePrice());<br>    gpay.processPayment(laptop.calculatePrice());<br>  }<br>}</pre><p>In above example , I introduced a new interface called “PaymentMethod” and two additional classes, “GPayPayment” and “CreditCardPayment.” These classes implement the core interface and provide their own implementations for the “processPayment()” method.</p><p>4. <strong>Abstraction</strong>:</p><p>Abstraction is the process of simplifying complex reality by modeling classes based on the essential properties and behaviors. It helps manage complexity by hiding unnecessary details. <br>To give more details on abstraction, let me take an example of ShoppingCart of different type users from ecommerce.</p><pre>package com.demo.kruti.oops.abstraction;<br><br>import com.demo.kruti.oops.models.Product;<br>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.stream.DoubleStream;<br><br>public abstract class ShoppingCart {<br>  protected List&lt;Product&gt; items; // Store items in the cart<br><br>  public ShoppingCart() {<br>    items = new ArrayList&lt;&gt;();<br>  }<br><br>  // Abstract method to add a product to the cart<br>  public abstract void addItem(Product product);<br><br>  // Abstract method to remove a product from the cart<br>  public abstract void removeItem(Product product);<br><br>  // Abstract method to calculate the total price of items in the cart<br>  public double calculateTotalPrice() {<br>    return items.stream().flatMapToDouble(product -&gt; DoubleStream.of(product.getPrice())).sum();<br>  }<br><br>  // Abstract method to display the cart contents<br>  public void displayCart() {<br>    for (Product item : items) {<br>      System.out.println(item.getName() + &quot; - Rs&quot; + item.getPrice());<br>    }<br>  }<br><br>}<br><br>class MemberShoppingCart extends ShoppingCart {<br>  @Override<br>  public void addItem(Product product) {<br>    items.add(product);<br>    System.out.println(&quot;Added for member &quot; + product.getName());<br>  }<br><br>  @Override<br>  public void removeItem(Product product) {<br>    items.remove(product);<br>    System.out.println(&quot;Removed for member&quot; + product.getName());<br>  }<br><br>  @Override<br>  public double calculateTotalPrice() {<br>    return super.calculateTotalPrice();<br>  }<br><br>  @Override<br>  public void displayCart() {<br>    System.out.println(&quot;Cart contents for Member user:&quot;);<br>    super.displayCart();<br>  }<br>}<br><br>class GuestShoppingCart extends ShoppingCart {<br>  @Override<br>  public void addItem(Product product) {<br>    items.add(product);<br>    System.out.println(&quot;Added for Guest &quot; + product.getName());<br>  }<br><br>  @Override<br>  public void removeItem(Product product) {<br>    items.remove(product);<br>    System.out.println(&quot;Removed for Guest &quot; + product.getName());<br>  }<br><br>  @Override<br>  public double calculateTotalPrice() {<br>    return super.calculateTotalPrice();<br>  }<br><br>  @Override<br>  public void displayCart() {<br>    System.out.println(&quot;Cart contents for Guest user:&quot;);<br>    super.displayCart();<br>  }<br>}</pre><pre>package com.demo.kruti.oops.abstraction;<br><br>import com.demo.kruti.oops.models.Product;<br><br>public class AbstractionDemo {<br>  public static void main(String[] args) {<br>    // Create a shopping cart for a registered user<br>    ShoppingCart memberUserCart = new MemberShoppingCart();<br><br>    // Create a shopping cart for a guest user<br>    ShoppingCart guestUserCart = new GuestShoppingCart();<br><br>    // Add products to the carts<br>    Product product1 = new Product(&quot;Product A&quot;, 29.99, 1);<br>    Product product2 = new Product(&quot;Product B&quot;, 19.99, 1);<br><br>    memberUserCart.addItem(product1);<br>    memberUserCart.addItem(product2);<br><br>    guestUserCart.addItem(product1);<br><br>    // Display cart contents and calculate total prices<br>    memberUserCart.displayCart();<br>    double memberUserTotalPrice = memberUserCart.calculateTotalPrice();<br>    System.out.println(&quot;Total Price for Member User: Rs&quot; + memberUserTotalPrice);<br><br>    guestUserCart.displayCart();<br>    double guestUserTotalPrice = guestUserCart.calculateTotalPrice();<br>    System.out.println(&quot;Total Price for Guest User: Rs&quot; + guestUserTotalPrice);<br>  }<br>}</pre><p>This example demonstrates abstraction by focusing on the essential features of a shopping cart while hiding the internal details of how each cart type works. It allows for flexibility and extensibility when adding new types of shopping carts or modifying the behavior of existing ones.</p><p>I have included the code snippet for this section in the Git repository. Please check this link : (<a href="https://github.com/djavaphp/java8_features/tree/main/src/main/java/com/demo/kruti/oops">https://github.com/djavaphp/java8_features/tree/main/src/main/java/com/demo/kruti/oops</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a488f39d569" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/java-backend-interview-preparation-part-2-4a488f39d569">Java Backend Interview Preparation: Part 2</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prepare for Java Backend Interview Part — 1]]></title>
            <link>https://medium.com/@er.janik26/prepare-for-java-backend-interview-part-1-af805a1bb45b?source=rss-8ca4afd7e6dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/af805a1bb45b</guid>
            <category><![CDATA[core-java-tutorial]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[java-8-feature]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <dc:creator><![CDATA[Kruti Dave]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 14:16:01 GMT</pubDate>
            <atom:updated>2023-10-06T05:20:34.630Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Novice to Pro: Your Journey through Core Java</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQXNq2cj9G4VRWkFK6NqwA.png" /><figcaption>Prepring for Java Interview ? This can help you.</figcaption></figure><p>Preparing for a Java interview as a developer can be quite overwhelming. You might wonder where to begin, especially when it comes to core Java concepts. An important question that often arises is, “Which Java version should I focus on during my preparation?” In today’s programming landscape, many concepts have evolved, with a significant emphasis on using wrapper implementations rather than diving deep into the underlying mechanics.</p><p>Moreover, if you’re currently working on microservices and utilizing a specific framework, you might wonder whether it’s crucial to revisit the basics of Java. These and many more questions can leave you feeling uncertain about the best approach to take.</p><p>In this journey of Java interview preparation, it’s essential to address these concerns and find a clear path forward. Let’s explore these questions and guide you on the most effective way to prepare for your Java interview.</p><p><strong>Crucial Java Concepts Unaffected by Version Changes: A Developer’s Must-Know List</strong></p><p>When preparing for Java development, there are fundamental topics that transcend Java versions but are absolutely essential for developers to master. These foundational concepts are universal and provide a strong base for your Java programming skills. As a developer, it’s crucial to be well-versed in the following areas:</p><ol><li><strong>Object-Oriented Programming (OOP): </strong>Understanding the principles of OOP, such as encapsulation, inheritance, and polymorphism, is indispensable. OOP forms the core of Java’s design philosophy and is vital for writing efficient and maintainable code.</li><li><strong>Exceptions:</strong> Exception handling is a critical aspect of Java development. Knowing how to handle exceptions gracefully and efficiently can prevent runtime errors and enhance the robustness of your applications.</li><li><strong>Generics:</strong> Generics allow for type-safe and reusable code. Proficiency in generics enables you to create flexible and efficient data structures and algorithms.</li><li><strong>Memory Management:</strong> Although Java has automatic memory management (garbage collection), understanding memory allocation, object lifecycle, and potential memory leaks is crucial for optimizing application performance.</li><li><strong>Multi-Threading:</strong> Java’s support for multi-threading is one of its standout features. A solid grasp of multi-threading concepts ensures that your applications can efficiently leverage parallelism while avoiding concurrency issues.</li><li><strong>Collections:</strong> Java’s vast collection framework provides a wide array of data structures to choose from. Knowing when and how to use collections, including lists, sets, maps, and queues, is essential for effective data manipulation.</li></ol><p>These topics transcend Java version changes and remain vital for any Java developer, regardless of the specific version you are working with. A strong foundation in these areas will not only bolster your understanding of Java but also make you a more skilled and versatile developer.</p><p>Many companies have transitioned to Java 8, making it essential for developers to possess a comprehensive understanding of its features.</p><p>In <strong>Java 8</strong>, a range of important features and enhancements were introduced, each contributing to the language’s evolution. Below, you’ll find a succinct list of these pivotal additions in bullet point format:</p><ul><li>Lambda Expressions</li><li>Functional Interfaces</li><li>Default Methods</li><li>Method References</li><li>Streams API</li><li>New Date and Time API (java.time)</li><li>Interface Changes (static and default methods)</li><li>Optional class for handling null values</li><li>New Collectors for the Stream API</li></ul><p>These are the key features that are commonly employed in Java 8 and have significantly impacted the way developers write Java code.</p><p>In my upcoming blog post, I aim to comprehensively address both core Java concepts and those specific to Java 8. This post will be a valuable resource for developers preparing for interviews, equipping them with the knowledge they need to excel.</p><p>Feel free to add new topics into comment sections. Let&#39;s make this open discussion which will help developers to prepare for interviews.</p><p>I aim to maintain a structured approach in my blog posts, breaking down each topic into individual posts for better readability and ease of follow-through. This way, readers can focus on specific subjects and engage in more targeted practice. <br>Towards the conclusion of this topic, we will include questions specific to the discussed subject matter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af805a1bb45b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Spark Application]]></title>
            <link>https://medium.com/@er.janik26/create-spark-application-from-scrach-and-understands-sparksession-397194d45c6e?source=rss-8ca4afd7e6dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/397194d45c6e</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[sparksession]]></category>
            <category><![CDATA[spark-summit]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kruti Dave]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 14:36:49 GMT</pubDate>
            <atom:updated>2023-07-25T16:49:49.202Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore Spark sessions, their usage, and the process of creating a session. By the end, you will have a solid understanding of Spark sessions and how to effectively utilize them.</p><p><strong>What is Spark?</strong></p><p>Before delving into the concept of Spark, it is essential to understand the reasons behind its creation. One of the major challenges in any big data project is scalability. Traditionally, data was stored in relational databases (RDBMS), but as businesses and data volumes grew over the years, this approach proved inadequate for scaling purposes.</p><p>Various approaches were attempted to address the scaling issue, but each had its drawbacks. For instance, consider the case of MapReduce, which is built on Java. This limited the ability to use other programming languages. Additionally, MapReduce primarily supports batch processing and is not well-suited for streaming, machine learning, and other real-time applications.</p><p>Another drawback of MapReduce is the requirement to serialize data between the map and reduce phases. Inefficient serialization can lead to increased network traffic and slower processing times, posing further challenges.</p><p>To tackle these limitations and provide more efficient and versatile solutions, alternative frameworks and technologies were developed. These include Apache Spark, Apache Flink, Hive, and others.</p><p>In this article, we will explore Apache Spark and focus on the concept of Spark Session.</p><p>Apache Spark is an open-source distributed computing system specifically designed for processing and analyzing big data. It offers a powerful engine capable of handling large-scale data processing tasks, which can be executed both on local machines and in cloud environments.</p><p>One of the key advantages of Spark is its in-memory storage capability, which enables significantly faster processing times compared to traditional disk-based systems. Additionally, Spark provides a user-friendly interface, allowing developers to write applications using popular programming languages such as Python, Java, and Scala. Notably, Spark itself is implemented in Scala, a functional programming language.</p><p>Spark consists of four main modules, each catering to different data processing requirements. Spark Streaming is focused on real-time data processing, allowing for the handling of streaming data sources. Spark SQL, on the other hand, is designed for batch processing, providing a SQL-like interface for querying structured data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*_OmQeCgHP8R65UuL.JPG" /></figure><p>Apache Spark is versatile and can be deployed across various platforms. It supports integration with popular cluster managers like YARN, a Hadoop-based cluster manager, as well as Kubernetes, EC2, and even standalone setups.</p><p><strong>Spark Sessions</strong></p><p>SparkSession, often referred to as “spark,” serves as the primary interface for interacting with Apache Spark’s diverse range of functionalities. Introduced in Spark 2.x, it consolidates the functionality of SparkContext, SQLContext, StreamingContext, and HiveContext into a single entry point.</p><p>With the advent of SparkSession, developers no longer need to manage multiple contexts individually. It acts as a unified access point to leverage the capabilities of Spark, simplifying the development process.</p><p>In previous versions of Spark, SparkContext (sc) served as the entry point for working with Resilient Distributed Datasets (RDD). However, starting from Spark 2.0, SparkSession took over this role, providing a more comprehensive and streamlined approach to working with data in Spark.</p><p>By default, spark shell provides “spark” object which is an instance of SparkSession class from Spark 2.x onwards.</p><p>I have installed latest version of Apache spark.</p><blockquote>After installation of Spark on local or cloud use “pyspark” command which will start Spark .</blockquote><pre>Welcome to<br>      ____              __<br>     / __/__  ___ _____/ /__<br>    _\ \/ _ \/ _ `/ __/  &#39;_/<br>   /__ / .__/\_,_/_/ /_/\_\   version 3.4.1<br>      /_/<br><br>Using Python version 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023 05:45:37)<br>Spark context Web UI available at http://host.docker.internal:4040<br>Spark context available as &#39;sc&#39; (master = local[*], app id = local-1688556016950).<br>SparkSession available as &#39;spark&#39;.</pre><p>In above ‘sc’ is the instance of SparkContext, we can still use sc in or above spark 2.x versions.</p><p><strong>SparkSession : Create</strong></p><p>When working in a production environment, it is often necessary to create a custom instance of SparkSession tailored to specific requirements. Let’s explore how to create one.</p><p>To create a SparkSession, you will typically need to import the required libraries and instantiate a SparkSession object. Here’s an example using Python:</p><pre>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder.master(&#39;local[*]&#39;).appName(&#39;Test&#39;).getOrCreate()<br><br>print(&quot;spark instance is created&quot;)</pre><p>So, in above snippet , we import SparkSession from pyspark.sql module. We utilize the builder design pattern to create an instance of the SparkSession object.</p><p>Master [master(‘local[*]’)] can be local, yarn, Kubernetes etc.</p><p>Finally, we call getOrCreate to either retrieve an existing SparkSession or create a new one if none exists.</p><p>To achieve the described steps using command-line commands, you can follow the instructions below:</p><ol><li>Create the dev1\example1\src\main\python directory:</li></ol><pre>mkdir dev1\example1\src\main\python</pre><p>2. Create the bin, lib, and sql directories inside the python directory:</p><pre>mkdir dev1\example1\src\main\python\bin<br>mkdir dev1\example1\src\main\python\lib<br>mkdir dev1\example1\src\main\python\sql      </pre><p>3. Create a file and write the code using the fsutil command:</p><pre>fsutil file createnew dev1\example1\src\main\python\test.py 0</pre><p>This command creates an empty file called test.py inside the python directory. Copy above code snipat of creating SparkSession in basics.py file.</p><p>At the end of code add <strong>spark.stop(), </strong>after calling stop you can not create any spark related code in test.py file.</p><p><strong>Using spark-submit</strong></p><p>I am using spark 3.x, so I will be using the spark-submit command to submit Spark applications.</p><pre>E:\devl\example1\src\main\python\bin&gt;spark-submit basics.py<br>spark instance iscreated<br>23/07/05 19:39:34 INFO SparkContext: Successfully stopped SparkContext<br>23/07/05 19:39:35 INFO ShutdownHookManager: Shutdown hook called<br></pre><pre>spark-submit \<br>  --class &lt;main class&gt; \<br>  --master &lt;master URL&gt; \<br>  --deploy-mode &lt;deploy mode&gt; \<br>  --conf &lt;key&gt;=&lt;value&gt; \<br>  --jars &lt;comma-separated list of jars&gt; \<br>  --files &lt;comma-separated list of files&gt; \<br>  --packages &lt;comma-separated list of packages&gt; \<br>  --repositories &lt;comma-separated list of Maven repository URLs&gt; \<br>  &lt;application JAR&gt; [application arguments]</pre><p>Let’s go through the important options:</p><ul><li>--class: Specifies the main class of your Spark application.</li><li>--master: Specifies the URL of the cluster manager or the &quot;local&quot; keyword for running in local mode. it could be yarn or Kubernetes too.</li><li>--deploy-mode: Specifies the deploy mode, which can be &quot;client&quot; or &quot;cluster&quot;. cluster mode driver run on worker mode; you can see it on Spark UI for the logs. Above code runs drivers localy so we can see the logs in terminal. (“spark instance is created”) By default if we dont specify mode it runs on client-mode only.</li><li>--packages: Specifies Maven coordinates of packages to be included as dependencies.</li><li>&lt;application JAR&gt;: Specifies the path to the application JAR file.</li><li>--conf: to pass run time configurations, application configurations</li></ul><p>In summary, the Spark Session acts as the entry point for interacting with Spark’s functionalities, providing a unified interface. It simplifies application development by consolidating multiple contexts into one. spark-submit is a command-line tool used to submit Spark applications, allowing you to configure and launch your applications on Spark clusters. Together, they facilitate the efficient development and execution of Spark applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=397194d45c6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick start with HDFS CLI]]></title>
            <link>https://medium.com/@er.janik26/quick-start-with-hdfs-cli-45da2e474d61?source=rss-8ca4afd7e6dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/45da2e474d61</guid>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[hdfs-commands]]></category>
            <category><![CDATA[apache-hadoop]]></category>
            <category><![CDATA[hdfs]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Kruti Dave]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 17:16:27 GMT</pubDate>
            <atom:updated>2023-07-26T15:58:41.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*cMsvbuD7Aa8Kd9UZumL_xg.png" /></figure><h4>Install Hadoop and ready with the CMD.</h4><p>In this context, we will not delve into the installation process of Hadoop on specific operating systems such as Windows, Ubuntu, or macOS. The method and platform you choose for installing and utilizing Hadoop are entirely based on your preferences. You have the flexibility to opt for cloud-based solutions like GCP or utilize pre-configured Docker images to quickly deploy and begin using Hadoop.</p><p>I have installed it on my Windows 10 as I want to learn more about Hadoop, MapReduce, Hive, Spark etc.</p><h4><strong><em>Getting started with HDFS CLI</em></strong></h4><p>Hadoop provides a command line interface to interact with HDFS.</p><ol><li><strong>Help Commands:</strong></li></ol><p>List all HDFS commands:</p><p>hadoop fs or hdfs dfs</p><p>Allows users to interact with the file system. The hadoop fs command is used to perform various file and directory operations, such as creating, copying, moving, deleting, and listing files and directories in Hadoop.</p><pre>C:\Users&gt;hadoop fs<br>Usage: hadoop fs [generic options]<br>        [-appendToFile [-n] &lt;localsrc&gt; ... &lt;dst&gt;]<br>        [-cat [-ignoreCrc] &lt;src&gt; ...]<br>        [-checksum [-v] &lt;src&gt; ...]<br>        [-chgrp [-R] GROUP PATH...]<br>        [-chmod [-R] &lt;MODE[,MODE]... | OCTALMODE&gt; PATH...]<br>        [-chown [-R] [OWNER][:[GROUP]] PATH...]<br>        [-concat &lt;target path&gt; &lt;src path&gt; &lt;src path&gt; ...]<br>        [-copyFromLocal [-f] [-p] [-l] [-d] [-t &lt;thread count&gt;] [-q &lt;thread pool queue size&gt;] &lt;localsrc&gt; ... &lt;dst&gt;]<br>        [-copyToLocal [-f] [-p] [-crc] [-ignoreCrc] [-t &lt;thread count&gt;] [-q &lt;thread pool queue size&gt;] &lt;src&gt; ... &lt;localdst&gt;]<br>        [-count [-q] [-h] [-v] [-t [&lt;storage type&gt;]] [-u] [-x] [-e] [-s] &lt;path&gt; ...]<br>        [-cp [-f] [-p | -p[topax]] [-d] [-t &lt;thread count&gt;] [-q &lt;thread pool queue size&gt;] &lt;src&gt; ... &lt;dst&gt;]<br>        [-createSnapshot &lt;snapshotDir&gt; [&lt;snapshotName&gt;]]<br>        [-deleteSnapshot &lt;snapshotDir&gt; &lt;snapshotName&gt;]<br>        [-df [-h] [&lt;path&gt; ...]]<br>        [-du [-s] [-h] [-v] [-x] &lt;path&gt; ...]<br>        [-expunge [-immediate] [-fs &lt;path&gt;]]<br>        [-find &lt;path&gt; ... &lt;expression&gt; ...]<br>        [-get [-f] [-p] [-crc] [-ignoreCrc] [-t &lt;thread count&gt;] [-q &lt;thread pool queue size&gt;] &lt;src&gt; ... &lt;localdst&gt;]<br>        [-getfacl [-R] &lt;path&gt;]</pre><p>We can find the general usage for any command with hadoop fs -usage ls</p><p>In case we want a complete guide for any commands we can use hadoop fs -help ls</p><pre>C:\Users&gt;hadoop fs -help ls -e<br><br>    -C  Display the paths of files and directories only.<br>    -d  Directories are listed as plain files.<br>    -h  Formats the sizes of files in a human-readable fashion<br>        rather than a number of bytes.<br>    -q  Print ? instead of non-printable characters.<br>    -R  Recursively list the contents of directories.<br>    -t  Sort files by modification time (most recent first).<br>    -S  Sort files by size.<br>    -r  Reverse the order of the sort.<br>    -u  Use time of last access instead of modification for<br>        display and sorting.<br>    -e  Display the erasure coding policy of files and directories.</pre><p><strong>2. Create a Folder/Directory</strong></p><p>To work with folder creation, we will use mkdir along with hdfc command.</p><p>hadoop fs -mkdir demo/my_db</p><p>hadoop fs -mkdir -p demo/my_db/tmp1/tmp2</p><pre>C:\Users&gt;hadoop fs -help mkdir<br><br>-mkdir [-p] &lt;path&gt; ... :<br>  Create a directory in specified location.<br><br>  -p  Do not fail if the directory already exists</pre><p><strong>3. Remove a Folder/Directory</strong></p><p>For removing any file or directory we can use -rmdir or -rmcommands.</p><pre>C:\Users&gt;hadoop fs -help rmdir<br>-rmdir [--ignore-fail-on-non-empty] &lt;dir&gt; ... :<br>  Removes the directory entry specified by each directory argument, provided it is<br>  empty.<br><br>C:\Users&gt;hadoop fs -help rm<br>-rm [-f] [-r|-R] [-skipTrash] [-safely] &lt;src&gt; ... :<br>  Delete all files that match the specified file pattern. Equivalent to the Unix<br>  command &quot;rm &lt;src&gt;&quot;<br><br>  -f          If the file does not exist, do not display a diagnostic message or<br>              modify the exit status to reflect an error.<br>  -[rR]       Recursively deletes directories.<br>  -skipTrash  option bypasses trash, if enabled, and immediately deletes &lt;src&gt;.<br>  -safely     option requires safety confirmation, if enabled, requires<br>              confirmation before deleting large directory with more than<br>              &lt;hadoop.shell.delete.limit.num.files&gt; files. Delay is expected when<br>              walking over large directory recursively to count the number of<br>              files to be deleted before the confirmation.</pre><p>Remove all the files in a directory we can use : hadoop fs -rm -r demo/my_db<br>Remove specific file we can use : hadoop fs -rm test.txt</p><p>Please note we cannot remove directory using -rmdirif it is not empty that is the reason we used -rm</p><p><strong>4. get command</strong></p><p>This command is used for copy files from the HDFS to the local file system.</p><pre>C:\Users&gt;hadoop fs -help get<br>-get [-f] [-p] [-crc] [-ignoreCrc] [-t &lt;thread count&gt;] [-q &lt;thread pool queue size&gt;] &lt;src&gt; ... &lt;localdst&gt; :<br>  Copy files that match the file pattern &lt;src&gt; to the local name. &lt;src&gt; is kept.<br>  When copying multiple files, the destination must be a directory.<br>  Flags:<br><br>  -p                           Preserves timestamps, ownership and the mode.<br>  -f                           Overwrites the destination if it already exists.<br>  -crc                         write CRC checksums for the files downloaded.<br>  -ignoreCrc                   Skip CRC checks on the file(s) downloaded.<br>  -t &lt;thread count&gt;            Number of threads to be used, default is 1.<br>  -q &lt;thread pool queue size&gt;  Thread pool queue size to be used, default is<br>                               1024.</pre><p>It allows you to retrieve files from HDFS and save them on your local machine.</p><p>hadoop fs -get &lt;source&gt; &lt;destination&gt;</p><p><strong>4. put command</strong></p><p>This command is used in Hadoop to copy files from the local file system to the HDFS.</p><pre>C:\Users&gt;hadoop fs -help put<br>-put [-f] [-p] [-l] [-d] [-t &lt;thread count&gt;] [-q &lt;thread pool queue size&gt;] &lt;localsrc&gt; ... &lt;dst&gt; :<br>  Copy files from the local file system into fs. Copying fails if the file already<br>  exists, unless the -f flag is given.<br>  Flags:<br><br>  -p                           Preserves timestamps, ownership and the mode.<br>  -f                           Overwrites the destination if it already exists.<br>  -t &lt;thread count&gt;            Number of threads to be used, default is 1.<br>  -q &lt;thread pool queue size&gt;  Thread pool queue size to be used, default is<br>                               1024.<br>  -l                           Allow DataNode to lazily persist the file to disk.<br>                               Forces replication factor of 1. This flag will<br>                               result in reduced durability. Use with care.<br>  -d                           Skip creation of temporary file(&lt;dst&gt;._COPYING_).</pre><p>Following command will copy the source-file-name file from the local machine the destination directory in HDFS. If the destination directory doesn’t exist, Hadoop will take care of creating automatically.</p><p>hadoop fs -put &lt;source-file-name&gt; &lt;destination&gt;</p><p><strong>Few more commonly used commands are listed below</strong></p><ul><li>hadoop fs -copyFromLocal &lt;local-path&gt; &lt;hdfs-path&gt;: Copies a file from the local file system to the Hadoop file system. similar to -put command.</li><li>hadoop fs -copyToLocal &lt;hdfs-path&gt; &lt;local-path&gt;: Copies a file from the Hadoop file system to the local file system. similar to -get command.</li><li>hadoop fs -mv &lt;src-path&gt; &lt;dst-path&gt;: Moves a file or directory from the source path to the destination path.</li></ul><p>In this blog, I have focused on providing an overview of the fundamental commands in Hadoop that are essential for beginners. These commands will assist you in getting started with Hadoop. If you require further information or detailed explanations about the commands, you can utilize the -help command, which will provide you with more insights and guidance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45da2e474d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marshaling and Unmarshaling XML using JAXB]]></title>
            <link>https://blog.devgenius.io/marshaling-and-unmarshaling-xml-using-jaxb-59b57a991bda?source=rss-8ca4afd7e6dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/59b57a991bda</guid>
            <category><![CDATA[jaxb]]></category>
            <category><![CDATA[xml-parser]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kruti Dave]]></dc:creator>
            <pubDate>Sat, 23 Apr 2022 15:48:17 GMT</pubDate>
            <atom:updated>2023-11-27T18:06:55.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*PCF4ncL9JTjCHwagoe8ltQ.png" /><figcaption>Java Class to XML and XML to Java Class</figcaption></figure><p>Previous Article Link: <a href="https://medium.com/vedity/xml-parsing-using-jaxb-de5529b91fbe">XML Parsing using JAXB</a></p><p>In the preceding article, we delved into various XML parsers and comprehended the annotations of JAXB. If you missed it, you can find the previous article here: “XML Parsing using JAXB”.</p><p>In the current piece, our focus will shift towards mastering the conversion of XML into Java objects and the creation of XML from Java objects.</p><p><strong>1. Convert Java Object to XML (Marshaling)</strong></p><p>Marshaller is an interface which will be used to achieve the output. To demonstrate, we will create an example to convert Java Objects into XML. Create a Java Class and Use JAXB annotations</p><p>Use JAXB annotation in pojo class. I have already explained all the annotations used in person class in my previous article.</p><p><strong>Person.java</strong></p><pre>@<strong>XmlRootElement</strong>(name = &quot;person&quot;)<br>@<strong>XmlType</strong>(propOrder = { &quot;userName&quot;, &quot;userEmailId&quot;, &quot;userPhoneNo&quot;, &quot;userCode&quot;, &quot;skills&quot;, &quot;goals&quot; })<br>@<strong>XmlAccessorOrder</strong>(XmlAccessOrder.ALPHABETICAL)<br>@ToString<br>public class <strong>Person </strong>implements Serializable {</pre><pre>private static final long serialVersionUID = 1L;<br> private Long id;<br> private String userName;<br> private String userEmailId;<br> private String userPhoneNo;<br> private String userCode;<br> private boolean isActive;</pre><pre>private List&lt;String&gt; skills;</pre><pre>private List&lt;String&gt; goals;</pre><pre>public Person() {<br>  super();<br> }</pre><pre>public Person(Long id, String userName, String userEmailId, String userPhoneNo, String userCode, boolean isActive) {<br>  super();<br>  this.id = id;<br>  this.userName = userName;<br>  this.userEmailId = userEmailId;<br>  this.userPhoneNo = userPhoneNo;<br>  this.userCode = userCode;<br>  this.isActive = isActive;<br> }</pre><pre>public Long getId() {<br>  return id;<br> }</pre><pre>@<strong>XmlAttribute</strong><br> public void setId(Long id) {<br>  this.id = id;<br> }</pre><pre>public String getUserName() {<br>  return userName;<br> }</pre><pre>@<strong>XmlElement</strong>(name = &quot;name&quot;)<br> public void setUserName(String userName) {<br>  this.userName = userName;<br> }</pre><pre>public String getUserEmailId() {<br>  return userEmailId;<br> }</pre><pre><a href="http://twitter.com/XmlElement">@XmlElement</a>(name = &quot;email&quot;)<br> public void setUserEmailId(String userEmailId) {<br>  this.userEmailId = userEmailId;<br> }</pre><pre>public String getUserPhoneNo() {<br>  return userPhoneNo;<br> }</pre><pre><a href="http://twitter.com/XmlElement">@XmlElement</a>(name = &quot;phone&quot;)<br> public void setUserPhoneNo(String userPhoneNo) {<br>  this.userPhoneNo = userPhoneNo;<br> }</pre><pre>public String getUserCode() {<br>  return userCode;<br> }</pre><pre>public void setUserCode(String userCode) {<br>  this.userCode = userCode;<br> }</pre><pre>public boolean isActive() {<br>  return isActive;<br> }</pre><pre>@<strong>XmlTransient</strong><br> public void setActive(boolean isActive) {<br>  this.isActive = isActive;<br> }</pre><pre>public List&lt;String&gt; getSkills() {<br>  return skills;<br> }</pre><pre>@<strong>XmlList</strong><br> public void setSkills(List&lt;String&gt; skills) {<br>  this.skills = skills;<br> }</pre><pre>public List&lt;String&gt; getGoals() {<br>  return goals;<br> }</pre><pre>@<strong>XmlElementWrapper</strong>(name = &quot;goals&quot;)<br>@<strong>XmlElement</strong>(name = &quot;goal&quot;)<br> public void setGoals(List&lt;String&gt; goals) {<br>  this.goals = goals;<br> }<br>}</pre><p>Marshaller — Convert Object to XML in Java.</p><p>JAXBContext class used in the below class is the entry point to the JAXB API. It provides information to implement the different operations such as: unmarshal, marshal and validate.</p><p>Marshaller interface provides the basic marshalling methods to convert Java Objects to XML.</p><p><strong>XMLUtils.java</strong></p><pre>public class <strong>XMLUtils </strong>{<br> <br> public static void main(String args[]) {<br>  Person person = new Person(1l, &quot;Sample USer&quot;, &quot;<a href="/service/mailto:sampleUser@gmail.com">sampleUser@gmail.com</a>&quot;, &quot;8777777777&quot;, &quot;SUC102&quot;, true);<br>  person.setGoals(Arrays.asList(&quot;Goal-1&quot;, &quot;Goal-2&quot;, &quot;Goal-3&quot;));<br>  person.setSkills(Arrays.asList(&quot;Skill-1&quot;, &quot;Skill-2&quot;, &quot;Skill-3&quot;));<br>  objectToXML(person);<br> }<br> <br> private static void <strong>objectToXML</strong>(Person person) {<br>  try {<br>   JAXBContext jaxbContext = <br>      JAXBContext.newInstance(Person.class);<br>   Marshaller marshaller = <br>      jaxbContext.createMarshaller();<br>   marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,<br>      Boolean.TRUE);<br>   marshaller.marshal(person, <br>      new File(&quot;D://person.xml&quot;));<br>  } catch (JAXBException e) {<br>   e.printStackTrace();<br>  }<br> }<br>}</pre><p><strong>Output</strong> will be stored in <strong>person.xml</strong> file at given location.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;<strong>person</strong> id=&quot;1&quot;&gt;<br>    &lt;<strong>name</strong>&gt;Read User&lt;/name&gt;<br>    &lt;<strong>email</strong>&gt;<a href="/service/mailto:readUser@gmail.com">readUser@gmail.com</a>&lt;/email&gt;<br>    &lt;<strong>phone</strong>&gt;98888888&lt;/phone&gt;<br>    &lt;<strong>userCode</strong>&gt;SUC102&lt;/userCode&gt;<br>    &lt;<strong>skills</strong>&gt;RSkill-1 RSkill-2 RSkill-3&lt;/skills&gt;<br>    &lt;<strong>goals</strong>&gt;<br>        &lt;goal&gt;RGoal-1&lt;/goal&gt;<br>        &lt;goal&gt;RGoal-2&lt;/goal&gt;<br>        &lt;goal&gt;RGoal-3&lt;/goal&gt;<br>    &lt;/<strong>goals</strong>&gt;<br>&lt;/<strong>person</strong>&gt;</pre><p><strong>2. Convert XML to Object in Java (Unmarshaller)</strong></p><p>Unmarshaller interface provides methods to convert XML to Java Objects. It reads the specified file and converts into Java class.</p><p><strong>XMLUtils.java</strong></p><pre>package com.example.utils;</pre><pre>import java.io.File;<br>import java.util.Arrays;</pre><pre>import javax.xml.bind.JAXBContext;<br>import javax.xml.bind.JAXBException;<br>import javax.xml.bind.Marshaller;<br>import javax.xml.bind.Unmarshaller;</pre><pre>import com.example.dto.Person;</pre><pre>public class <strong>XMLUtils </strong>{<br> <br> public static void main(String args[]) {<br> <br>  xmlToObject();<br> }<br> <br> private static void <strong>xmlToObject</strong>() {<br>  File xmlFile = new File(&quot;D://person.xml&quot;);<br>      <br>     JAXBContext jaxbContext;<br>     try<br>     {<br>       jaxbContext = JAXBContext.newInstance(Person.class);<br>       Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();<br>       Person person = (Person) unmarshaller.unmarshal(xmlFile);        <br>       System.out.println(person);<br>     }<br>     catch (JAXBException e) <br>     {<br>       e.printStackTrace();<br>     }<br> }<br>}</pre><p>Output From above code will display person information:</p><pre>Person(id=1, userName=Read User, <a href="/service/mailto:userEmailId=readUser@gmail.com">userEmailId=readUser@gmail.com</a>, userPhoneNo=98888888, userCode=SUC102, skills=[RSkill-1, RSkill-2, RSkill-3], goals=[RGoal-1, RGoal-2, RGoal-3])</pre><p>I trust that both of my articles on JAXB will assist you in commencing your journey with XML in Java.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59b57a991bda" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/marshaling-and-unmarshaling-xml-using-jaxb-59b57a991bda">Marshaling and Unmarshaling XML using JAXB</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XML Parsing using JAXB]]></title>
            <link>https://blog.devgenius.io/xml-parsing-using-jaxb-de5529b91fbe?source=rss-8ca4afd7e6dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/de5529b91fbe</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jaxb]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[parse]]></category>
            <category><![CDATA[xml]]></category>
            <dc:creator><![CDATA[Kruti Dave]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 11:43:53 GMT</pubDate>
            <atom:updated>2023-11-01T09:11:10.920Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will learn about XML parsing , different types of Parsers and annotations of JAXB which helps to convert XML to Java object and create XML from JAVA Object.</p><p><strong>What is XML?</strong></p><p><em>XML, eXtensible Markup Language</em> is a markup language which defines a set of rules for encoding documents in a format that is readable.</p><p><strong>What is XML Parser?</strong></p><p>The XML parser is a software library or a package that provides an interface for the applications to work with XML documents. It checks for correct format of the XML document and also validates the XML documents.</p><p>There are several parsers for reading xml file in JAVA such as <strong>DOM</strong> Parser, <strong>SAX</strong> Parser, <strong>JAXB</strong> etc.</p><p>Let me give brief idea of each.</p><p><strong>DOM Parser:</strong></p><p>It creates a tree structure of objects available into the XML document and loads in into memory. It works on entire XML document. This API is very simple to use, it also supports Read and Write both operations. But also have some drawbacks, as it stores the entire document into memory if document size is big it will occupy more memory.</p><p><strong>SAX Parser</strong>:</p><p>It is also known as the Simple API for XML<strong>. </strong>It can be consider as an event based parser as it does not store anything into memory and it start parsing at the beginning of the document in a sequence manner. Since SAX is more memory-efficient than DOM as it is based on events and works on callback mechanism.</p><p><strong>JAXB:</strong></p><p>JAXB — Java Architecture for XML Binding — is used to convert objects from/to XML.</p><p>JAXB offers a fast and suitable way to marshal (write) Java objects into XML and unmarshal (read) XML into Java objects. It supports Java annotations to map XML elements to Java attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*aystDZg7ITl2jIpANbFoLg.jpeg" /></figure><p><strong>JAXB Annotations:</strong></p><p>Let me give you a brief idea about JAXB annotations and usage of each.</p><ul><li><strong>@XmlRootElement</strong></li></ul><p>It defines the XML root element. When a top-level class (Root Class) is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document.</p><p>This is a must-have an annotation for the Object to be used in JAXB. It defines the root element for the XML content.</p><pre><a href="http://twitter.com/XmlRootElement">@XmlRootElement</a>(name = &quot;person&quot;)<br>public class Person implements Serializable {//other codes}</pre><pre>Output: person.xml</pre><pre>&lt;person id=&quot;1&quot;&gt;<br>  &lt;name&gt;Sample USer&lt;/name&gt;<br>  &lt;email&gt;<a href="/service/mailto:sampleUser@gmail.com">sampleUser@gmail.com</a>&lt;/email&gt;<br>  &lt;phone&gt;8777777777&lt;/phone&gt;<br>&lt;/person&gt;</pre><ul><li><strong>@XmlAccessorType</strong></li></ul><p>This defines the fields or properties of your Java classes that the JAXB engine uses for including into generated XML. It accepts <em>XmlAccessType</em> values.</p><p><em>XmlAccessType</em> .PUBLIC_MEMBER :</p><p>It means every public getter or setter and every public property defined in Java class will be automatically bound to XML, Annotated by XmlTransient will be excluded. It is also a default value for @XmlAccessorType.</p><p><em>XmlAccessType</em> .FIELD:</p><p>It means fields which are non static and non transient will be automatically bound to XML; Annotated by XmlTransient will be excluded.</p><p><em>XmlAccessType</em> .NONE:</p><p>It means any fields which are not annotated with JAXB annotations is not bound to XML.</p><p><em>XmlAccessType</em> .PROPERTY:</p><p>It means every getter and setter pair will be automatically bound to XML, Annotated by XmlTransient will be excluded.</p><pre>@XmlAccessorType(XmlAccessType.<strong><em>FIELD</em></strong>)<br><strong>public</strong> <strong>class</strong> Person <strong>implements</strong> Serializable {}</pre><ul><li><strong>@XmlAccessorOrder</strong></li></ul><p>Usage of this annotation of JAXB is to provide the order of fields and properties in a class. We can have predefined values ALPHABETICAL or UNDEFINED.</p><pre>@XmlAccessorOrder(XmlAccessOrder.<strong><em>ALPHABETICAL</em></strong>)<br><strong>public</strong> <strong>class</strong> Person <strong>implements</strong> Serializable {}</pre><ul><li><strong>@XmlType</strong></li></ul><p>It maps the class to the XML schema type. We can use it for ordering the elements in the XML.</p><pre>@XmlRootElement(name = &quot;person&quot;)<br>@XmlType(propOrder = {&quot;userName&quot;,<br>&quot;userEmailId&quot;,<br>&quot;userPhoneNo&quot;,<br>&quot;userCode&quot;<br>})<br><strong>public</strong> <strong>class</strong> Person <strong>implements</strong> Serializable {<br>//other code<br>}</pre><ul><li><strong>@XmlElement</strong></li></ul><p>It define the actual XML element name that will be used while parsing.</p><pre>@XmlElement(name = &quot;name&quot;)<br><strong>public</strong> <strong>void</strong> setUserName(String userName) {<br>  <strong>this</strong>.userName = userName;<br>}<br>@XmlElement(name = &quot;email&quot;)<br><strong>public</strong> <strong>void</strong> setUserEmailId(String userEmailId) {<br> <strong>this</strong>.userEmailId = userEmailId;<br>}<br>@XmlElement(name = &quot;phone&quot;)<br><strong>public</strong> <strong>void</strong> setUserPhoneNo(String userPhoneNo) {<br>  <strong>this</strong>.userPhoneNo = userPhoneNo;<br>}</pre><pre>Output: person.xml</pre><pre>&lt;person id=<em>&quot;1&quot;</em>&gt;<br>  &lt;name&gt;Sample USer&lt;/name&gt;<br>  &lt;email&gt;sampleUser@gmail.com&lt;/email&gt;<br>  &lt;phone&gt;8777777777&lt;/phone&gt;<br>&lt;/person&gt;</pre><p>userName, userEmailId, userPhoneNo changed to name, email, phone after applying @XmlElement annotation on each property.</p><ul><li><strong>@XmlAttribute</strong></li></ul><p>It defines the id field which is mapped as an attribute instead of an element of an XML.</p><pre>@XmlAttribute<br><strong>public</strong> <strong>void</strong> setId(Long id) {<br> <strong>this</strong>.id = id;<br>}</pre><pre>Output: person.xml</pre><pre>&lt;person <strong>id=<em>&quot;1&quot;</em>&gt;<br></strong>&lt;/person&gt;</pre><ul><li><strong>@XmlTransient</strong></li></ul><p>This annotation defines on any fields than that we don’t want to be included in XML.</p><pre>@XmlTransient<br><strong>public</strong> <strong>void</strong> setActive(<strong>boolean</strong> isActive) {<br> <strong>this</strong>.isActive = isActive;<br>}</pre><ul><li><strong>@XmlValue</strong></li></ul><p>This annotation can be used with a JavaBeans property and non static, non transient field. At most one field or property can be annotated with the @XmlValue annotation.</p><ul><li><strong>@XmlList</strong></li></ul><p>This annotation is used to map a property to a list simple type. It allows multiple values to be represented with whitespace separated in a single xml element.</p><pre>@XmlList<br><strong>private</strong> List&lt;String&gt; skills;</pre><pre>Output: person.xml</pre><pre>&lt;person id=<em>&quot;1&quot;</em>&gt;<br>  &lt;name&gt;Sample USer&lt;/name&gt;<br>  &lt;email&gt;sampleUser@gmail.com&lt;/email&gt;<br>  &lt;phone&gt;8777777777&lt;/phone&gt;<br>  &lt;userCode&gt;SUC102&lt;/userCode&gt;<br>  &lt;skills&gt;Skill-1 Skill-2 Skill-3&lt;/skills&gt;<br>&lt;/person&gt;</pre><ul><li><strong>@XmlElementWrapper</strong></li></ul><p>This annotation is also used with collections. It generates a wrapper element around XML representation and inside that element it wills wrapper the collection elements. This must be used only with collections fields.</p><pre>@XmlElementWrapper(name=&quot;goals&quot;)<br>@XmlElement(name=&quot;goal&quot;)<br><strong>private</strong> List&lt;String&gt; goals;</pre><pre>Output: person.xml</pre><pre>&lt;person id=<em>&quot;1&quot;</em>&gt;<br> &lt;name&gt;Sample USer&lt;/name&gt;<br> &lt;email&gt;sampleUser@gmail.com&lt;/email&gt;<br> &lt;phone&gt;8777777777&lt;/phone&gt;<br> &lt;userCode&gt;SUC102&lt;/userCode&gt;<br> &lt;skills&gt;Skill-1 Skill-2 Skill-3&lt;/skills&gt;<br> &lt;goals&gt;<br>  &lt;goal&gt;Goal-1&lt;/goal&gt;<br>  &lt;goal&gt;Goal-2&lt;/goal&gt;<br>  &lt;goal&gt;Goal-3&lt;/goal&gt;<br> &lt;/goals&gt;<br>&lt;/person&gt;</pre><p>I will cover JAXB annotation example by doing marshaling and unmarshaling in another Article.</p><p>Next Article : <a href="https://medium.com/vedity/marshaling-and-unmarshaling-xml-using-jaxb-59b57a991bda">Marshaling and Unmarshaling XML using JAXB</a></p><p>Reference: <a href="https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/package-summary.html">JAXB Annotations</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de5529b91fbe" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/xml-parsing-using-jaxb-de5529b91fbe">XML Parsing using JAXB</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Data JPA Part -1]]></title>
            <link>https://medium.com/@er.janik26/spring-data-jpa-part-1-fed8f2885c8c?source=rss-8ca4afd7e6dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fed8f2885c8c</guid>
            <category><![CDATA[crudrepository]]></category>
            <category><![CDATA[entity]]></category>
            <category><![CDATA[custom-queries]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Kruti Dave]]></dc:creator>
            <pubDate>Tue, 12 Apr 2022 07:46:57 GMT</pubDate>
            <atom:updated>2022-04-12T10:34:30.256Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Introduction to Spring Data JPA with an Example</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*8Txsp146R0zHW42q.png" /><figcaption><em>Introduction to Spring Data JPA with an Example</em></figcaption></figure><p>Before getting into Spring Data JPA, let’s understand the different modules for Spring. Spring has developed many modules or frameworks for each platform, like for web development.</p><p><strong>Spring Core</strong> modules have features such as IoC and Dependency Injection</p><p><strong>Spring MVC </strong>follows Model-View-Controller design pattern. It divides the roles and responsibility into different modules. Model is responsible for managing data of the application and View is responsible for showing the data of application in a readable manner. Mainly JSP is used to create view pages. It also supports other view technologies. Controller is used to write a business logic of the application.</p><p><strong>Spring Data</strong> has given support to ORM, JDBC, JMS etc. module provides relation mapping with database which includes <a href="https://docs.spring.io/spring-framework/docs/3.0.0.M4/reference/html/ch13s05.html">JPA</a>, <a href="https://docs.spring.io/spring-framework/docs/3.0.0.M4/reference/html/ch13s03.html">Hibernate</a>, <a href="https://docs.spring.io/spring-framework/docs/3.0.0.M4/reference/html/ch13s06.html">iBatis</a> and some others.</p><p><strong>Spring AOP</strong> means Aspect Oriented Programming which allows programmer to define interceptors and pointcuts on functionality which is not part of actual implementation but can consider as a add on to the application.</p><p>Spring also provides <strong>Test</strong> Modules to test spring components. It provides mocking of objects which makes testing easier.</p><p>This was a quick overview of Different Spring frameworks. So now coming back to our topic of Spring Data using JPA (Java Persistence API)</p><p>The JPA Provider implements the Java Persistence API. Spring Data JPA has certain classes which make it easier to create Repository of each entity (how object will be represented in relational database) used in the application. This library gives generic classes and methods which programmers don’t have to write on their own. Therefore, time is saved on writing the same code.</p><p>Let’s Start with an example to understand implementation.</p><p>We will use Spring Data JPA and MySQL and REST Endpoints in spring boot application.</p><p><strong>Spring Data JPA Setup into Spring Boot Project</strong></p><p>1. Create project using spring.io initializer ( <a href="https://start.spring.io/">Spring Initializr</a>) With option selection of MySql and Spring Data Jpa or can use STS with inbuild support of Spring framework.</p><p>By using URL, no need to add maven dependency, it will create automatically.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a>&quot; xmlns:xsi=&quot;<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>&quot;<br> xsi:schemaLocation=&quot;<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a> <a href="https://maven.apache.org/xsd/maven-4.0.0.xsd">https://maven.apache.org/xsd/maven-4.0.0.xsd</a>&quot;&gt;<br> &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br> &lt;parent&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>  &lt;version&gt;2.6.4&lt;/version&gt;<br>  &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;<br> &lt;/parent&gt;<br> &lt;groupId&gt;com.example&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-data-jpa&lt;/artifactId&gt;<br> &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br> &lt;name&gt;spring-data-jpa&lt;/name&gt;<br> &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;<br> &lt;properties&gt;<br>  &lt;java.version&gt;1.8&lt;/java.version&gt;<br> &lt;/properties&gt;<br> &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;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>   &lt;optional&gt;true&lt;/optional&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;mysql&lt;/groupId&gt;<br>   &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br> &lt;/dependencies&gt;<br> &lt;build&gt;<br>  &lt;plugins&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>   &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br> &lt;/build&gt;<br>&lt;/project&gt;</pre><p>2. Open project in Eclipse or STS and update application.properties or application.yml file.</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/user-mgmt<br>spring.datasource.username=root<br>spring.datasource.password=root<br>spring.datasource.driver-class-name=com.mysql.jdbc.Driver<br>spring.jpa.database-platform = org.hibernate.dialect.MySQL55Dialect<br>spring.jpa.generate-ddl=true<br>spring.jpa.hibernate.ddl-auto = create<br>spring.jpa.show-sql=true</pre><p>3. Create an Entity</p><p>After configuring database into the application, Lets create User entity. So, if someone is new to ORM, Entities are nothing but a Java class which will map to the tables in the relational database. So suppose I create User entity then it will map to database with user table.</p><p><strong>User Entity:</strong></p><p>Here I have also used lombok library for the entities. (Lombok is a java Library which helps in removing traditional code. Used @Data below entity class will Generates getters for all fields. It also comes with many other annotations.)</p><p>@Entity denotes a class match to a table in the relational database. userName, userEmailId etc will be column name in user Table.</p><p>@Id denotes as a is the primary key of the table.</p><p>@GeneratedValue is for auto generation of the primary key.</p><pre><a href="http://twitter.com/Data">@Data</a><br><a href="http://twitter.com/Entity">@Entity</a><br><a href="http://twitter.com/Table">@Table</a>(name = &quot;user&quot;)<br>public class User extends Auditable&lt;String&gt; {</pre><pre><a href="http://twitter.com/Id">@Id</a><br> <a href="http://twitter.com/GeneratedValue">@GeneratedValue</a>(strategy = GenerationType.IDENTITY)<br> private Long id;<br> private String userName;<br> private String userEmailId;<br> private String userPhoneNo;<br> private String userCode;<br> private boolean isActive;<br>}</pre><p>4. Create UserRepository</p><p>Spring Data JPA has different interfaces such as CrudRepository, JpaRepository, PagingAndSorting etc.</p><p>Crud Repository provides CRUD operations to database without writing any query. Basic Crud methods <em>save(), findAll(), findById(), delete()</em></p><p>JpaRepository is a combination of CrudRepository and PagingAndSorting.</p><p>So, in my example below I have used JpaRepository to implement pagination or sorting if needed.</p><pre>package com.example.repository;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import com.example.model.User;</pre><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>}</pre><p>5. Call methods from Service class or you can also use CommandLineRunner to test repository methods.</p><pre>package com.example;</pre><pre>import org.springframework.boot.CommandLineRunner;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.context.annotation.Bean;</pre><pre>import com.example.model.User;<br>import com.example.repository.UserRepository;</pre><pre><a href="http://twitter.com/SpringBootApplicatio">@SpringBootApplicatio</a>n<br>public class SpringDataJpaApplication {</pre><pre>public static void main(String[] args) {<br>  SpringApplication.run(SpringDataJpaApplication.class, args);<br> }</pre><pre><a href="http://twitter.com/Bean">@Bean</a> <br>    public CommandLineRunner example(UserRepository userRepository) {<br>        return (args) -&gt; {<br>            //New User<br>            User user = new User(&quot;ABCUSER&quot;, &quot;<a href="/service/mailto:abc@gmail.com">abc@gmail.com</a>&quot;,&quot;6767676767&quot;,&quot;ER001&quot;);            <br>            //1. Save New User to DB<br>            userRepository.save(user);            <br>            //2. Find User by user Code<br>            User findUser = userRepository.findByUserCode(&quot;ER001&quot;);<br>            //3. Print User Details<br>            System.out.println(&quot;User Name : &quot;+ findUser.toString());<br>        };<br>    }<br>}</pre><p>Point 3 will Print user information on console as below</p><pre>User Name: User(id=1, userName=ABCUSER,<a href="/service/mailto:userEmailId=abc@gmail.com">userEmailId=abc@gmail.com</a>, userPhoneNo=6767676767, userCode=ER001, isActive=true)</pre><p>So, here I have created one custom method as <em>findByUserCode(String userCode) </em>in UserRepository. Likewise, we can also customize our queries to fulfil requirements.</p><p>Also, if you have noticed I have not created any method such as <em>save(User user)</em>, <em>delete(), findAll()</em> in UserRepository. As it implements from JpaRepository.</p><p>We can also demonstrate the same with Http Methods by creating Rest Endpoints in Spring Boot Application. I will try to cover it in some other blog.</p><p>Source: <a href="https://docs.spring.io/spring-framework/docs/3.0.0.M4/reference/html/ch01s02.html">1.2 Modules (spring.io)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fed8f2885c8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Form Validations in Angular: A Comprehensive Guide]]></title>
            <link>https://blog.devgenius.io/form-validations-in-angular-fdf9cf2315c8?source=rss-8ca4afd7e6dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdf9cf2315c8</guid>
            <category><![CDATA[custom-validation]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[email-validation]]></category>
            <category><![CDATA[phone-validation]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <dc:creator><![CDATA[Kruti Dave]]></dc:creator>
            <pubDate>Fri, 11 Mar 2022 10:49:36 GMT</pubDate>
            <atom:updated>2025-01-07T17:52:40.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*UK8dCxnzjmUHtSapNF1xoQ.jpeg" /></figure><h3>Enhancing Form Validation in Angular: Combining Custom Rules with Fundamental Checks</h3><p>When working with forms, there are often fundamental validations that need to be in place, such as mandatory field validation, maximum and minimum length checks, and even restrictions on spaces within textboxes. In an Angular application, custom validations can be seamlessly integrated, enhancing form control.</p><p>For instance, consider a scenario where the requirement is to prevent the inclusion of spaces in a master code field. Traditionally, one might think of using conditional statements or the trim function to accomplish this. However, upon closer inspection, an elegant solution emerges using a custom validator within a FormControl, all within the realm of Angular&#39;s reactive forms framework. This capability is available from Angular 6 and onwards.</p><p>In my recent experience, I encountered a need to disallow spaces within a master code field. Rather than resorting to conventional methods like conditional checks or trimming functions, I delved into the world of FormGroup and FormControl. By creating a custom validator tailored to eliminate spaces from input fields, I was able to achieve this requirement in a more efficient and structured manner. Let’s explore this concept by crafting a new custom validator that ensures input fields remain free of spaces.</p><p>Let&#39;s check it by creating new custom validator which will not contain space on input field.</p><p>We will need an Angular application;</p><p>1. create new angular demo application if you already have then skip it.</p><pre>ng new demo-custom-validator</pre><p>2. If created a new application you need to install packages.</p><pre>npm i or npm install</pre><p>3. Since we are creating Forms module we need to add/ import it into app.module.ts file.</p><p>Route to src/app/app.module.ts</p><pre>import { BrowserModule } from &#39;@angular/platform-browser&#39;;</pre><pre>import { NgModule } from &#39;@angular/core&#39;;</pre><pre>import { AppRoutingModule } from &#39;./app-routing.module&#39;;</pre><pre>import { AppComponent } from &#39;./app.component&#39;;</pre><pre>import { ReactiveFormsModule } from &#39;@angular/forms&#39;;</pre><pre>@NgModule({</pre><pre>declarations: [</pre><pre>AppComponent</pre><pre>],</pre><pre>imports: [</pre><pre>BrowserModule,</pre><pre>AppRoutingModule,</pre><pre><strong>ReactiveFormsModule</strong></pre><pre>],</pre><pre>providers: [],</pre><pre>bootstrap: [AppComponent]</pre><pre>})</pre><pre>export class AppModule { }</pre><p>4. Html File with FormGroup as userForm</p><pre>&lt;div class=&quot;header row&quot;&gt;</pre><pre>&lt;span class=&quot;col-4&quot;&gt; User Management&lt;/span&gt;</pre><pre>&lt;span class=&quot;col-2 text-right&quot;&gt;</pre><pre>&lt;/span&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;mt-15&quot;&gt;</pre><pre><strong>&lt;form [formGroup]=&quot;userForm&quot;&gt;</strong></pre><pre>&lt;div class=&quot;row col mt-15&quot;&gt;</pre><pre>&lt;div class=&quot;form-group pr-20&quot;&gt;</pre><pre>&lt;label class=&quot;form-label&quot;&gt;User Name&lt;/label&gt;</pre><pre>&lt;input class=&quot;form-control material-form-input-box text-field&quot; formControlName=&quot;userName&quot;</pre><pre>placeholder=&quot;Enter User Name&quot; type=&quot;text&quot; /&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group pr-10&quot;&gt;</pre><pre>&lt;label class=&quot;form-label&quot;&gt;User Email ID&lt;/label&gt;</pre><pre>&lt;input class=&quot;form-control&quot; formControlName=&quot;emailId&quot;</pre><pre>placeholder=&quot;Enter Email&quot; type=&quot;text&quot; /&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group &quot;&gt;</pre><pre>&lt;label class=&quot;form-label&quot;&gt;User Phone Number&lt;/label&gt;</pre><pre>&lt;input class=&quot;form-control&quot; formControlName=&quot;phoneNo&quot;</pre><pre>placeholder=&quot;Enter Phone Number&quot; type=&quot;text&quot; /&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group &quot;&gt;</pre><pre>&lt;label class=&quot;form-label&quot;&gt;User Code&lt;/label&gt;</pre><pre>&lt;input class=&quot;form-control&quot; formControlName=&quot;userCode&quot;</pre><pre>placeholder=&quot;Enter User Code&quot; type=&quot;text&quot; /&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group top-margin&quot;&gt;</pre><pre>&lt;button type=&quot;button&quot; class=&quot;btn btn-primary text-uppercase&quot; (click)=&quot;submit()&quot;</pre><pre><strong>[disabled]=&quot;!userForm.valid&quot;</strong>&gt;SUBMIT&lt;/button&gt;</pre><pre>&lt;button type=&quot;button&quot; class=&quot;btn-cancel&quot; (click)=&quot;cancel()&quot;&gt;CANCEL&lt;/button&gt;</pre><pre>&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;/form&gt;<br>&lt;/div&gt;</pre><p>5. Custom validator file :</p><p>Here , by checking index of ‘ ‘ (space) validation a value and returning boolean value.</p><pre>import { AbstractControl, ValidationErrors } from &#39;@angular/forms&#39;;</pre><pre>export class <strong>SpaceValidator </strong>{</pre><pre>static validateSpace(control: AbstractControl): <strong>ValidationErrors </strong>| null {</pre><pre>if ((control.value as string).indexOf(&#39; &#39;) &gt;= 0) {</pre><pre>return { validateSpace: true }</pre><pre>}<br>return null;<br>}<br>}</pre><p>6. TS File</p><p>Here created userForm and created FormControls. Few validations added for each fields for some references.</p><p>So, SpaceValidator used in userCode where I dont want user to add any spaces.</p><p>Also added some validations on Email and Phone controls by applying patterns for each along with required validation.</p><p>Check below code file for the reference :</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;</pre><pre>import { FormControl, FormGroup, Validators } from &#39;@angular/forms&#39;;</pre><pre>import { SpaceValidator } from &#39;../space.validator&#39;;</pre><pre>@Component({</pre><pre>selector: &#39;app-user&#39;,</pre><pre>templateUrl: &#39;./user.component.html&#39;,</pre><pre>styleUrls: [&#39;./user.component.scss&#39;]</pre><pre>})</pre><pre>export class UserComponent implements OnInit {</pre><pre>constructor() { }</pre><pre>ngOnInit(): void {</pre><pre>}</pre><pre>userForm = new FormGroup({</pre><pre>userName: new FormControl(&quot;&quot;,<strong> [Validators.required]</strong>),</pre><pre>emailId: new FormControl(&quot;&quot;, [Validators.required,</pre><pre><strong>Validators.pattern(&quot;^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$&quot;)]</strong>), <em>//Email Pattern</em></pre><pre>phoneNo: new FormControl(&quot;&quot;, <strong>[Validators.required,</strong></pre><pre><strong>Validators.pattern(&quot;^((\\+91-?)|0)?[0-9]{10}$&quot;)]</strong>), <em>// can also provide pattern</em></pre><pre>userCode: new FormControl(&quot;&quot;,<strong> [Validators.required,</strong></pre><pre><strong>SpaceValidator.validateSpace]</strong>), <em>//custom validator created.</em></pre><pre>});</pre><pre>submit() {<br>console.log(this.userForm.value);<br>}</pre><pre>cancel() {<br>this.userForm.reset();<br>}<br>}</pre><p>7. run application :</p><pre> ng serve </pre><p>if you want to run on specific port :</p><pre> ng serve — port 4202</pre><p>8. Screenshots attached</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*kWH6d31KKQ-9yhgfMDAxDQ.png" /></figure><p>In the context of the first attachment, the unsuccessful validations result in the deactivation of the SUBMIT button. Conversely, the second image demonstrates successful validations, leading to the activation of the SUBMIT button.</p><p>However, the next step involves enhancing user interaction by providing real-time visual cues in the event of validation failures. A prime example is when an incorrect email address is provided. In such cases, the implementation of visual indicators, such as a red border or error messages denoting invalid input, becomes crucial. This particular aspect hasn’t been addressed in the current setup and warrants attention.</p><p>I trust you’re enjoying the content of the blog. Feel free to continue reading and stay connected for more insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdf9cf2315c8" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/form-validations-in-angular-fdf9cf2315c8">Form Validations in Angular: A Comprehensive Guide</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>