Wednesday, June 30, 2021

Angular ngSwitch Directive With Examples

In the post Angular ngIf Directive With Examples we saw how to use ngIf directive but you may have a scenario where you need to render different elements based on different conditions. In such scenario you can use Angular ngSwitch directive rather than using ngIf several times.

Angular ngSwitch directive

The [ngSwitch] directive on a container specifies an expression to match against. The expressions to match are provided by ngSwitchCase directives on views within the container.

Syntax of Angular ngSwitch

<container-element [ngSwitch]="switch_expression">
  <some-element *ngSwitchCase="match_expression_1">...</some-element>
  <some-element *ngSwitchCase="match_expression_2">...</some-element>
  ...
  <some-element *ngSwitchDefault>...</some-element>
</container-element>
  1. Every view that matches is rendered.
  2. If there are no matches, a view with the ngSwitchDefault directive is rendered.
  3. ngSwitchDefault element is optional. If you don't use it, nothing will be rendered when there is no matching value.
  4. Note that asterisk (*) precedes the ngSwitchCase which means it is a structural directive and used to add or remove DOM element.
  5. If the value of the match_expression matches the value of the switch_expression, the corresponding element is added to the DOM. If the expression doesn’t match, then the element is excluded from the DOM.
  6. The element that the ngSwitch directive is applied to is always included in the HTML document, ngSwitch is specified within square brackets.

Tuesday, June 29, 2021

Angular ngFor Directive With Examples

Angular ngFor directive is the looping directive in Angular that iterates over each item in the collection and renders the element (or section of elements) for each item.

Here is an example where ngFor is contained in an <li> element.

<li *ngFor="let item of items>
  ..
  ..
</li>

Note that ngFor is the shorthand form which is internally expanded into a long form that uses the ngForOf selector on an <ng-template> element.

<ng-template ngFor let-item [ngForOf]="items">
  <li>...</li>
</ng-template>

Note that asterisk (*) precedes the ngFor which means it is a structural directive and used to add or remove DOM element.

Monday, June 28, 2021

Java LinkedBlockingDeque With Examples

LinkedBlockingDeque in Java is an implementation of the BlockingDeque interface and it was added in Java 6.

LinkedBlockingDeque is an optionally bounded deque and it stores its elements as linked nodes. Since it is optionally bounded so it has constructor which takes initial capacity as parameter. In case capacity is not specified it is equal to Integer.MAX_VALUE.

Java LinkedBlockingDeque constructors

LinkedBlockingDeque in Java has three constructors-

  • LinkedBlockingDeque()- Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE.
  • LinkedBlockingDeque(Collection<? extends E> c)- Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection, added in traversal order of the collection's iterator.
  • LinkedBlockingDeque(int capacity)- Creates a LinkedBlockingDeque with the given (fixed) capacity.

Here note that Linked nodes are dynamically created upon each insertion unless this would bring the deque above capacity. In case initial capacity is defined then the blocking method like put(E e) will wait if necessary for space to become available.

Since elements are stored as linked nodes so most of the operations like add(), addFirst(), put(), putFirst() run in constant time (ignoring time spent blocking). Exceptions include remove(object o), removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk operations, all of which run in linear time.

LinkedBlockingDeque Java Example code

Let's create a produce consumer bounded buffer using LinkedBlockingDeque which is an implmentation of BlockingDeque.

Values will be inserted in the LinkedBlockingDeque using put() method, which will block if the space is full.

Values will be retrieved from the LinkedBlockingDeque using take() method, which retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Here in the Produce class some delay is induced using sleep() method. You can see that in Consumer class, where it is taking elements out of the deque, no excpetion will be thrown but it will block. If you are using eclipse you can see that delay in the console when it is printing.

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class LinkedBlockingDQDemo {
  public static void main(String[] args) {
    SharedClass buffer = new SharedClass();
    // Starting two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new Producer(buffer));
    executor.execute(new Consumer(buffer));
    executor.shutdown();
  }
}
/**
 * 
 */
class Producer implements Runnable{
  SharedClass buffer;
  Producer(SharedClass buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 10; i++){
      buffer.put(i);
      if(i == 4){
        try {
          // introducing some delay using sleep
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}
/**
 * 
 */
class Consumer implements Runnable{
  SharedClass buffer;
  Consumer(SharedClass buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 10; i++){
      buffer.get();;
    }
  }    
}

//Shared class used by threads
class SharedClass{
  int i;
  // Bounded LinkedBlockingDeque of size 10
  BlockingDeque<Integer> linkedBlockingDeque = new LinkedBlockingDeque<Integer>(10);
    
  public void get(){
    try {
      // take method to get from blockingdeque
      System.out.println("Consumer recd - " + linkedBlockingDeque.take());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  public void put(int i){
    this.i = i;
    try {
      // putting in blocking deque
      linkedBlockingDeque.put(i);
      System.out.println("Putting - " + i);
    }
    catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Output

Putting - 0
Putting - 1
Putting - 2
Putting - 3
Putting - 4
Consumer recd - 0
Consumer recd - 1
Consumer recd - 2
Consumer recd - 3
Consumer recd - 4
Putting - 5
Consumer recd - 5
Putting - 6
Consumer recd - 6
Putting - 7
Consumer recd - 7
Putting - 8
Consumer recd - 8
Putting - 9
Consumer recd - 9

That's all for this topic Java LinkedBlockingDeque With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java BlockingDeque With Examples
  2. Java BlockingQueue With Examples
  3. Java LinkedBlockingQueue With Examples
  4. Java Phaser With Examples
  5. Java Concurrency Interview Questions And Answers

You may also like-

  1. Race Condition in Java Multi-Threading
  2. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  3. Java ThreadLocal Class With Examples
  4. Functional Interfaces in Java
  5. Java Stream API Tutorial
  6. Heap Memory Allocation in Java
  7. static Keyword in Java With Examples
  8. Data Access in Spring Framework

Sunday, June 27, 2021

How to Iterate a HashMap of ArrayLists of String in Java

This Java program shows how to iterate a HashMap that contains arraylists of String.

In the Java program to iterate a HashMap containing ArrayLists there is a method getMap() where 3 lists are created and stored in the HashMap.

First you need to iterate the HashMap, though there are several ways to iterate over a HashMap, but here I have used the for-each loop for iterating the created HashMap. Each Map.Entry object is a key-value pair where value is the ArrayList stored with the given key. That's the list retrieved using listEntry.getValue() method.

In the second for-each loop List that is retrieved using listEntry.getValue() is iterated and the elements that are in the list are displayed.

Java Program to Iterate HashMap of ArrayLists

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapLoop {

  public static void main(String[] args) {
    MapLoop mapLoop = new MapLoop();
    Map<String, List<String>> cityMap = mapLoop.getMap();
    int i = 0;
    // iterating over a map
    for(Map.Entry<String, List<String>> listEntry : cityMap.entrySet()){
      System.out.println("Iterating list number - " + ++i);
      // iterating over a list
      for(String cityName : listEntry.getValue()){
        System.out.println("City - " + cityName);
      }
    }
  }
    
  /**
   * A method to create a list and store it in a Map
   * @return
  */
  private Map<String, List<String>> getMap(){
    Map<String, List<String>> cityMap = new HashMap<String, List<String>>();
    // First List
    List<String> temp = new ArrayList<String>();  
    temp.add("Delhi");
    temp.add("Mumbai");
    // Putting first list in the map
    cityMap.put("1", temp);
    // Second List
    temp = new ArrayList<String>();  
    temp.add("Hyderabad");
    temp.add("Bangalore");
    // Putting second list in the map
    cityMap.put("2", temp);
    // Third List
    temp = new ArrayList<String>();
    temp.add("Kolkata");
    temp.add("Chennai");
    // Putting third list in the map
    cityMap.put("3", temp);
    return cityMap;
  }
}
Output
Iterating list number - 1
City - Delhi
City - Mumbai
Iterating list number - 2
City - Hyderabad
City - Bangalore
Iterating list number - 3
City - Kolkata
City - Chennai

That's all for this topic How to iterate a Hash map of arraylists of String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How HashMap Internally Works in Java
  2. How to Loop Through a Map in Java
  3. How to Loop or Iterate an Arraylist in Java
  4. How to Sort ArrayList of Custom Objects in Java
  5. Count Number of Times Each Character Appears in a String Java Program

You may also like-

  1. Method Overloading in Java
  2. Dependency Injection in Spring Framework
  3. Race Condition in Java Multi-Threading
  4. Java ReentrantLock With Examples
  5. CopyOnWriteArrayList in Java With Examples
  6. Java Exception Handling Interview Questions And Answers
  7. Java Collections Interview Questions And Answers
  8. Producer-Consumer Java Program Using wait notify

Saturday, June 26, 2021

Difference Between Abstract Class And Interface in Java

Difference between abstract class and interface in Java is one of the most popular java interview questions and many times it is a kind of "breaking the ice" question when the interview just starts. But that way Abstract class Vs Interface becomes a very important question as it is often said "first impression is the last impression" so let's try to see the differences between abstract class and interface in Java in this post.

First of all it is very important to know what an abstract class is and what an interface is. So please go through these two posts abstract class in Java and interface in Java to familiarize yourself with abstract class and interface.

There are also some similarities between abstract class and interface in Java like both can't be instantiated, both have abstract methods where extending/implementing class has to provide the implementation for such methods.

Abstract class Vs Interface in Java

Abstract Class Interface
Methods Abstract class can have both abstract methods (method with no body) and non-abstract methods (methods with implementation). Interface can have abstract methods only.
Note: From Java 8 interfaces can have default methods and static methods and private methods Java 9 onward. So on this account both abstract classes and interfaces in Java are becoming quite similar as both can have methods with implementation.
Access Modifiers Abstract class methods can have public, protected, private and default modifier apart from abstract methods. In interface methods are by default public abstract only. From Java 9 private methods can also be added to a Java interface.
Variables Abstract class fields can be non-static or non-final. In interface all the fields are by default public, static, final.
Implementation Abstract class may have some methods with implementation and some methods as abstract. In interface all the methods are by default abstract, where only method signature is provided. Note: From Java 8 interfaces can have default methods where default implementation can be provided with in the interface and static methods that can be accessed using the Interface name. Apart from that interfaces can have private methods too Java 9 onward.
Constructor Abstract classes have a constructor, it may be user supplied or default in case no constructor is written by a user. Interfaces can't have a constructor.
Multiple Inheritance Abstract class can extend at most one class and implement one or more interfaces. Interface can only extend one or more interfaces.
Extends/Implements Abstract class are extended by the sub-classes. Sub-classes need to provide implementation for all the abstract methods of the extended abstract class or be declared as abstract itself. Interface is implemented by a class and the implementing class needs to provide implementation for all the abstract methods declared in an interface. If a class does not implement all the abstract methods of an interface then that class must be declared as abstract.
Easy to evolve Abstract class was considered easy to evolve as abstract classes could add new methods and provide default implementation to those methods. Interface was not considered easy to evolve as, in the case of adding new method to an interface, all the implementing classes had to be changed to provide implementation for the new method. With Java 8 even interfaces can have default methods so that issue has been addressed.

Which one should you use, abstract classes or interfaces?

As we know abstract classes have to be extended where as interfaces need to be implemented by a class. That itself suggests when to use what, in case you need to extend some functionality further you need to go with abstract class. When you need to start from generalized structure and move towards more specialized structure by extending the generalized class and providing specialized implementations, abstract class is a better choice.

In case of interfaces it is expected that unrelated classes would implement that interface and each class is free to provide their own implementation. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.

That's all for this topic Difference Between Abstract Class And Interface in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Interface in Java With Examples
  2. Marker Interface in Java
  3. Interface Static Methods in Java 8
  4. Interface Default Methods in Java 8
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. What are JVM, JRE and JDK in Java
  2. static Keyword in Java With Examples
  3. super Keyword in Java With Examples
  4. this Keyword in Java With Example
  5. Reflection in Java - Getting Class Information
  6. Autowiring using XML configuration in Spring
  7. How HashMap Works Internally in Java
  8. Count Number of Words in a String Java Program

Thursday, June 24, 2021

Producer-Consumer Java Program Using ArrayBlockingQueue

This Java program solves the Producer-Consumer problem using threads and ArrayBlockingQueue which is an implementation of the BlockingQueue interface.

Initial capacity of the ArrayBlockingQueue will be kept one so that producer and consumer both get a chance alternatively.

Values will be inserted in the ArrayBlockingQueue using put() method, which will block if the space is full.

Values will be retrieved from the ArrayBlockingQueue using take() method, which retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

In the program there is a class Buffer which is shared by both threads. In comparison to produce-consumer using wait notify this version using blocking queue is much simpler as you don't need to write the logic for making the thread wait or notifying the waiting thread.

Producer-Consumer program in Java Using ArrayBlockingQueue

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ArrayBQDemo {
  public static void main(String[] args) {
    Buffer buffer = new Buffer();
    // Starting two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new ProdTask(buffer));
    executor.execute(new ConTask(buffer));
    executor.shutdown();
  }
}

class ProdTask implements Runnable{
  Buffer buffer;
  ProdTask(Buffer buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      buffer.put(i);
    }
  }
}

class ConTask implements Runnable{
  Buffer buffer;
  ConTask(Buffer buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      buffer.get();;
    }
  }    
}

//Shared class used by threads
class Buffer{
  int i;
  // Bouded ArrayBlockingQueue of size 1
  BlockingQueue<Integer> arrayBlockingQ = new ArrayBlockingQueue<Integer>(1);
  public void get(){
    try {
      // take method to get from blockingqueue
      System.out.println("Consumer recd - " + arrayBlockingQ.take());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  public void put(int i){
    this.i = i;
    try {
      // putting in blocking queue
      arrayBlockingQ.put(i);
      System.out.println("Putting - " + i);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Putting - 0
Consumer recd - 0
Putting - 1
Consumer recd - 1
Putting - 2
Consumer recd - 2
Putting - 3
Consumer recd - 3
Putting - 4
Consumer recd - 4

That's all for this topic Producer-Consumer Java Program Using ArrayBlockingQueue. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Print Odd-Even Numbers Using Threads And Semaphore Java Program
  2. Java ArrayBlockingQueue With Examples
  3. How to Run Threads in Sequence in Java
  4. Setting And Getting Thread Name And Thread ID in Java
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. Convert int to String in Java
  3. Connection Pooling Using Apache DBCP in Java
  4. How to Create PDF From XML Using Apache FOP
  5. Race Condition in Java Multi-Threading
  6. Abstraction in Java
  7. Interface Default Methods in Java
  8. Bean Scopes in Spring With Examples

Wednesday, June 23, 2021

Java String Interview Questions And Answers

In this post some of the Java String Interview Questions are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is String in Java?

    In Java String class represents character strings which means; Strings in Java are objects and all strings are instances of the String class. Internally in String class Strings are stored as character array.

    Read more about String in Java here.

  2. In how many ways String object can be created?

    Since strings are objects so strings can of course be created using new operator. String class has more than 10 constructors to create Strings which ranges from taking nothing as parameter to taking char array, StringBuffer, StringBuilder, another String as argument.
    Another and more preferred way to create Strings is to assign String literal directly to a String reference as you will do for any primitive type. For every string literal Java will automatically constructs a String object.

    As example- String str = “abc”; 
    

    Read more about String in Java here.

  3. If String can be created using String str = “test” then String is a primitive data type.Yes/No?

    No. For every string literal Java automatically constructs a String object.


  4. What is String pool? Where is it created in memory?

    When String literals are created they are stored in a String pool and that is a common pool; which means if there are two strings literals having the same content then those string will share the space in the pool.
    When String object is created by assigning a string literal, pool will be checked to verify if there is any existing object with the same content if there is then that existing reference is used, no new object is created in that case. If no object is found with the same content then this new literal will be added in the pool.
    String pool is stored in the heap.

    Read more about String Pool in Java here.

  5. What is immutable object? Is String object immutable?

    An immutable object is an object that would not be able to change its state after creation. Thus immutable object can only be in one state and that state can not be changed after creation of the object.
    Yes String object is immutable. Once you create a String object the content of that string cannot be modified.


  6. Why is String class immutable?

    Since Java maintains a string pool where String references are shared thus changing content of any of the String will also affect the other strings sharing the same references that’s one reason why string is immutable.

    Read more about String immutability here.

  7. Why is String class final in Java?

    Since String is immutable, whenever you perform any operation on string which alters its content a new string object is created containing the modified string. Which means all the methods of the String class that modify the content in any way return a new String object with the modified content.
    Now, What if you can override the method of the String class so that it modifies and return the original string reference itself? In that case all the other strings having the same data in the string pool will also get affected as the reference is shared for the String literals having the same content.
    To avoid these kind of scenarios String class is declared as final and it can’t be overridden.


  8. Which operator is overloaded for String?

    ‘+’ operator is overloaded in Java for String. It is used for concatenating two strings.


  9. How many objects will be created if two Strings are created this way?

    String s1 = “test”; 
    String s2 =  “test”;
    

    Since s1 and s2 are string literals and having the same content object reference will be shared by them in the string pool. Therefore only one object is created.


  10. How many objects will be created if two Strings are created this way?

    String s1 = “test”;
    String s2 =  new String(“test”);
    

    In this case string literal goes to string pool and s2 is another object created using new. So, in this case two objects are created even if content is same.


  11. How many objects will be created if two Strings are created this way?

    String s1 = new String(“test”);
    String s2 =  new String(“test”);
    

    Two separate objects are created.
    If you check it using the following code

    if(s1 == s2){
      System.out.println("s1 and s2 are same");
    }else{
      System.out.println("s1 and s2 are not same");
    }
    
    s1 and s2 are not same will be displayed.


  12. How many object will be created if Strings are created this way?

    String s1 = “test”;
    String s2 =  new String(“test”);
    String s3 = new String(“test”).intern();
    

    s1 will go to string pool, for s2 new object is created. S3, though created using new will still search in the string pool for any reference having the same content as intern() method is used. So two objects will be created.


  13. What is intern() method in String?

    Using intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.
    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    Read more about intern() method in Java here.

  14. Is String thread safe in Java?

    Yes string is thread safe in Java as String is immutable.

    Read more about String and thread safety in Java here.

  15. What is StringBuffer in Java?

    StringBuffer class is the companion class of String. StringBuffer is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuffer length and content of the sequence can be changed through certain method calls.
    Since StringBuffer is mutable a new String object is not created every time string is modified, which in turn results in less memory consumptions and not having lots of intermediate String object for garbage collection.

    Read more about StringBuffer in Java here.

  16. What is StringBuilder in Java?

    StringBuilder class (Added in Java 5),just like StringBuffer, is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuilder length and content of the sequence can be changed through certain method calls.

    Read more about StringBuilder in Java here.

  17. Differences among String, StringBuffer and StringBuilder in Java?

    String is immutable where as both StringBuffer and StringBuilder are mutable.
    String and StringBuffer are thread safe where as StringBuilder is not thread safe.

    Read more about String Vs StringBuffer Vs StringBuilder in Java here.

  18. Is StringBuffer class also immutable in Java?

    No, StringBuffer is not immutable.

    Read more about StringBuffer in Java here.

  19. Is StringBuffer class also final in Java?

    Yes, StringBuffer class is final in Java.


  20. Is StringBuffer class thread safe?

    Yes StringBuffer class is thread safe. Methods in StringBuffer class are synchronized.


  21. Is StringBuilder class thread safe?

    No StringBuilder class is not thread safe. That makes it faster than StringBuffer.


  22. Is StringBuilder class also final in Java?

    Yes StringBuilder class is final in Java.

    Read more about StringBuilder in Java here.

  23. How to compare two strings in Java?

    equals() method can be used for comparing two strings in Java. If you want to ignore case then you can use equalsIgnoreCase(String anotherString) method.
    There are also compareTo() and compareToIgnoreCase() methods for comparing two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
    You can also use matches() method where you can pass a regular expression for matching strings.

    Read more about String comparison in Java here.

  24. What will happen if “==” operator is used to compare two strings in Java?

    “==” operator will compare the references of the strings not the content.

    String str1 = "abc";
    String str4 = new String("abc");
    
    Comparing these two strings using “==” operator
     if(str1 == str4)
    
    will return false as the references are different.


  25. How to get characters and substrings by index with in a String?

    You can get the character at a particular index within a string by invoking the charAt() accessor method.

    String str = "Example String";
    char resChar = str.charAt(3);
    
    Will give char ‘m’. If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions -
    • String substring(int beginIndex, int endIndex) - Returns a new string that is a substring of this string.
    • String substring(int beginIndex) - Returns a new string that is a substring of this string.

    Read more about String charAt() and subString() methods in Java here.
  26. How can you find characters or substrings within a string?

    To find characters or substrings with in a string indexOf() and lastIndexOf() methods can be used.
    You can also use contains() method
    public boolean contains(CharSequence s) - Returns true if and only if this string contains the specified sequence of char values. Otherwise it returns false.

    Read more about charAt() and subString() methods in Java here.
  27. How can you split a string in Java?

    String provides a split method in order to split the string into one or more substring based on the given  regular expression.
    As example If you have a string where one (or more) spaces are used and you want to split it around those spaces.

    String str1 = "split example    program";
    String[] strArray = str1.split("\\s+");
    

    Read more about Splitting a String using split() method in Java here.
  28. How can you join strings in Java?

    With Java 8 join() method has been added in the String class which makes it very easy to join the multiple strings.
    join method has two overloaded versions -

    • public static String join(CharSequence delimiter, CharSequence... elements) - Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
    • public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) – Here elements is an Iterable that will have its elements joined together and delimiter is a sequence of characters that is used to separate each of the elements in the resulting String.

    Read more about String join() method in Java 8 here.
  29. Can we use String in switch case statement?

    Yes from Java 7 string can be used in switch case statement.


Related Topics

  1. Java OOP Interview Questions And Answers
  2. Core Java Basics Interview Questions And Answers
  3. Java Exception Handling Interview Questions And Answers
  4. Java Multithreading Interview Questions And Answers
  5. Java Collections Interview Questions And Answers
  6. Java Concurrency Interview Questions And Answers
  7. Java Lambda Expressions Interview Questions And Answers
  8. Java Stream API Interview Questions And Answers

Tuesday, June 22, 2021

How LinkedList Class Works Internally in Java

In Java Collections framework there are two general purpose implementations of the List interface-

Out of these two ArrayList internally uses an array of Object which can be dynamically re-sized.

In this post I'll talk about LinkedList internal implementation in Java Collections framework.

Note- Code of LinkedList class used here for reference is from Java 10.


Internal implementation of LinkedList class in Java

LinkedList class in Java implements List and Deque interfaces and LinkedList implements it using doubly linkedlist.

In the implementation of the LinkedList class in Java there is a private class Node which provides the structure for a node in a doubly linked list. It has item variable for holding the value and two reference to Node class itself for connecting to next and previous nodes.

The Node class from Linked List implementation

private static class Node<E> {
  E item;
  Node<E> next;
  Node<E> prev;
  Node(Node<E> prev, E element, Node<E> next) {
    this.item = element;
    this.next = next;
    this.prev = prev;
  }
}

Graphical representation of Java LinkedList with nodes

Here is a graphical representation of a linked list to help you better visualize how actually a node will look like and how it connects with other nodes through next and prev references.
Since reference is stored for both next and previous nodes that is why it is a doubly linked list implementation.

LinkedList internal implementation in Java

Though there are many methods with in the LinkedList class but here I'll try to explain the internal working of the LinkedList, how references are created and shuffled using these 3 methods-

  • private void linkFirst(E e)
  • void linkLast(E e)
  • public void add(int index, E element)

Java LinkedList internal implementation - linkFirst() method

linkFirst() method is used to add an element at the beginning of the list and it is implemented as follows in the LinkedList class

/**
 * Links e as first element.
 */
private void linkFirst(E e) {
  final Node<E> f = first;
  final Node<E> newNode = new Node<>(null, e, f);
  first = newNode;
  if (f == null)
      last = newNode;
  else
      f.prev = newNode;
  size++;
  modCount++;
}

Here one more important thing to mention is first and last Node class references which always refer to the first and last element of the linked list.

/**
 * Pointer to first node.
 * Invariant: (first == null && last == null) ||
 *            (first.prev == null && first.item != null)
 */
transient Node<E> first;
/**
 * Pointer to last node.
 * Invariant: (first == null && last == null) ||
 *            (last.next == null && last.item != null)
 */
transient Node<E> last;

With this info it is easy to see that in the linkFirst method, when the very first element is inserted into the list first and last both refer to this new node.

In case linked list already contains elements and a new element is inserted at the beginning of the list. Then f will hold the reference to the node which was the first element before this insertion. first will be assigned the reference to the newly created node (first = newNode;). The element which was the first element before this insertion is at second position now so its prev element should store reference of the first node, that's what is happening here f.prev = newNode;

And in the call to the constructor of the node class f is sent as a parameter. If you see in the Node class constructor there is a line this.next = next; that's how the newly created node is storing the reference to the second node.

Java LinkedList internal implementation - linkLast() method

linkLast() method is used to insert element as the last element of the list. In that case the node which is currently the last node of the linked list will become the second last node. So the newly created node's prev should store the reference to this second last node and the next of the second last node should store the reference to the node which is the last node now.

/**
 * Links e as last element.
 */
void linkLast(E e) {
  final Node<E> l = last;
  final Node<E> newNode = new Node<>(l, e, null);
  last = newNode;
  if (l == null)
      first = newNode;
  else
      l.next = newNode;
  size++;
  modCount++;
}

Here it is first checking if it is the very first element which is inserted in that case both first and last references point to it. If elements are already there in the linked list then the node which is currently the last node of the linked list will become the second last node now.

See the call to the constructor of the Node class (this.prev = prev;). So the newly created node's prev should store the reference to this second last node and the next of the second last node should store the reference to the node which is the last node now (l.next = newNode;).

Java LinkedList internal implementation - add(int index, E element) method

add(int index, E element) is used to Insert the specified element at the specified position in this list.

public void add(int index, E element) {
  checkPositionIndex(index);

  if (index == size)
    linkLast(element);
  else
    linkBefore(element, node(index));
}

Here it calls linkBefore method

void linkBefore(E e, Node<E> succ) {
  // assert succ != null;
  final Node<E> pred = succ.prev;
  final Node<E> newNode = new Node<>(pred, e, succ);
  succ.prev = newNode;
  if (pred == null)
    first = newNode;
  else
    pred.next = newNode;
  size++;
  modCount++;
}

And node(index) parameter with in the linkBefore() method is call to the following method to get the existing Node at the given index-

/**
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int index) {
 // assert isElementIndex(index);

  if (index < (size >> 1)) {
    Node<E> x = first;
    for (int i = 0; i < index; i++)
      x = x.next;
    return x;
  } else {
    Node<E> x = last;
    for (int i = size - 1; i > index; i--)
      x = x.prev;
    return x;
  }
}

I am leaving it to you readers to figure out how linkBefore() method is working. It should be easy based on the explanation already provided for linkFirst() and linkLast() method.

That's all for this topic How LinkedList Class Works Internally in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashMap Works Internally in Java
  2. How HashSet Works Internally in Java
  3. Difference Between ArrayList And LinkedList in Java
  4. ListIterator in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How to Convert Array to ArrayList in Java
  2. Difference between HashMap and ConcurrentHashMap in Java
  3. static import in Java
  4. finally Block in Java Exception Handling
  5. Interface Static Methods in Java
  6. Method reference in Java 8
  7. Java Program to Find First Non-Repeated Character in a Given String
  8. Synchronization in Java - Synchronized Method And Block

Monday, June 21, 2021

How to Create Immutable Class in Java

In this tutorial we will learn how to create an immutable class in Java.

Immutable class, as the name suggests, is a class whose object can’t be modified in anyway once created. Once an object of the immutable class is created and initialized the content of any field of that object can’t be changed in anyway and remains same throughout the life of the object. If there are methods that modify the content in some way then a new object is created with the modified content and returned, original object does not change.

As example String in Java is an immutable class though there are methods with in String class like substring or replace which modify the created String object. You can see in the code of the String class that for all these type of methods a new string is created with the modified data and returned. Other examples of immutable classes in Java are all the wrapper classes for primitive types like Integer, Long etc. BigDecimal and BigInteger are also immutable classes.

How to create an immutable class in Java

There are certain steps that are to be followed for creating an immutable class in Java–

  1. Methods of the class should not be overridden by the subclasses. You can ensure that by making your class final.

  2. Make all fields final and private. Marking fields as final ensures that their value is not changed. If the field is of primitive type, then it’s value can’t be changed as it is final. If field is holding a reference to another object, then declaring that field as final means its reference can’t be changed.
    Having access modifier as private for the fields ensure that fields are not accessed outside the class.

  3. Initialize all the fields in a constructor.

  4. Don’t provide setter methods or any method that can change the state of the object. Only provide methods that can access the value (like getters).

  5. In case any of the fields of the class holds reference to a mutable object any change to those objects should also not be allowed, for that–
    • Make sure that there are no methods with in the class that can change those mutable objects (change any of the field content).
    • Don’t share reference of the mutable object, if any of the methods of your class return the reference of the mutable object then its content can be changed.
    • If reference must be returned create copies of your internal mutable objects and return those copies rather than the original object. The copy you are creating of the internal mutable object must be a deep copy not a shallow copy.

In case you are wondering why such elaborate procedure for the fields holding references when fields are already final and references can’t be changed. Remember that even if reference cannot be changed you can still change the content of the fields with in a mutable object which goes against what you want to achieve by making your class immutable.

Creating Immutable class Java example

In the example we'll create an immutable class that holds another class object too along with fields of other types. There are two classes, Address class is the mutable class whose object is there in the immutable class ImmutableEmployee.

Address.java

public class Address {
 private String addressLine1;
 private String addressLine2;
 private String city;
 public String getAddressLine1() {
  return addressLine1;
 }
 public void setAddressLine1(String addressLine1) {
  this.addressLine1 = addressLine1;
 }
 public String getAddressLine2() {
  return addressLine2;
 }
 public void setAddressLine2(String addressLine2) {
  this.addressLine2 = addressLine2;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String toString() {
  return "AddressLine1 " + addressLine1 + " AddressLine2 " + addressLine2 + " City " + city;
 }
}

ImmutableEmployee

public class ImmutableEmployee {
 private final String name;
 private final int age;
 private final Address empAddress;
 ImmutableEmployee(String name, int age, String add1, String add2, String city){
  this.name = name;
  this.age = age;
  // don't pass reference around create a new object with in constructor
  empAddress = new Address();
  empAddress.setAddressLine1(add1);
  empAddress.setAddressLine2(add2);
  empAddress.setCity(city);
 }
 
 public String getName() {
  return name;
 }
 public int getAge() {
  return age;
 }
 
 public Address getEmpAddress() {
  // creating copy of the mutable object for returning
  Address adr = new Address();
  adr.setAddressLine1(empAddress.getAddressLine1());
  adr.setAddressLine2(empAddress.getAddressLine2());
  adr.setCity(empAddress.getCity());
  return adr;
  /*return empAddress;*/
 }
 
 public String toString() {
  return "Name " + name + " Age " + age + " Address " + empAddress;
 }

 public static void main(String[] args) {
  ImmutableEmployee ie = new ImmutableEmployee("Jack", 32, "34, Hunter's Glen", "Pine Street", "Brooklyn");
  System.out.println("Employee information " + ie);
  Address adr = ie.getEmpAddress();
  adr.setCity("London");
  System.out.println("Employee information " + ie);
 }
}

Output

Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City Brooklyn
Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City Brooklyn

Here notice that in the line Address adr = ie.getEmpAddress(); I get the address object and change the city in the object but that change is not reflected in the Employee object because getEmpAddress() method creates and returns a new Address object.

You can change that method to return the original Address object, in that case your getEmpAddress() method will look like this–

 public Address getEmpAddress() {
  /*Address adr = new Address();
  adr.setAddressLine1(empAddress.getAddressLine1());
  adr.setAddressLine2(empAddress.getAddressLine2());
  adr.setCity(empAddress.getCity());
  return adr;*/
  return empAddress;
 }

Now if you execute the code and see the output-

Output

Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City Brooklyn
Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City London

You can see that Employee information is changed, you are now able to change the content of the Employee class object which should not be happening as it’s an immutable class. That’s why the point as mentioned above “If reference must be returned create copies of your internal mutable objects and return those copies rather than the original object.” is important.

If your class has any mutable object or using any of the modifiable collections like ArrayList, HashSet, HashMap same steps are to be followed.

Advantages of using immutable class

  1. One of the advantage of an immutable class is it is thread safe and its object can be shared among many threads without any fear of content of the original object getting changed. Refer String and thread safety to have more clarity on this point.

  2. Another advantage is you can cache immutable class objects as you know content won’t change once the object is created so no fear of dirty read. This ability to cache and reuse reduces overhead.

  3. If you ever wondered why do you see mostly String as a key for HashMap, yes, it is mostly because of String being immutable. So, if you are somehow required to use your own custom object as key and want to make sure that the object is not changed by any means (like any other thread) making that class immutable will be an option.

Disadvantages of using immutable class

  1. If the second point in the advantages of using immutable class has impressed you to make as many immutable classes in your Java application as possible just take a pause and think of the disadvantage too. Any get method where you are supposed to return the immutable class object or any field that holds a reference to a mutable object you do need to create a new object every time, copy the content from the original object and then return it. Which results in creation of many new objects and performing deep copies which again is expensive.

That's all for this topic How to Create Immutable Class in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. How to Create Deadlock in Java
  2. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  3. Remove Duplicate Elements From an Array in Java
  4. Is String Thread Safe in Java
  5. String Comparison in Java equals(), compareTo(), startsWith() Methods

You may also like-

  1. Java ReentrantLock With Examples
  2. Difference Between HashMap And ConcurrentHashMap in Java
  3. Invoking Getters And Setters Using Reflection in Java
  4. Java Stream API Tutorial
  5. Serialization Proxy Pattern in Java
  6. Nested class and Inner class in Java
  7. Ternary Operator in Java With Examples
  8. Type Casting in Java

Sunday, June 20, 2021

Java Program to Get All DB Schemas

In this post we’ll see a Java program to list all the schemas in a DB. Database used here is MySQL.

List all DB schemas using Java

To get all the database schemas in Java you can use the getCatalogs() method provided by the DatabaseMetaData interface in the JDBC API.

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBMetaData {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");
      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306", 
                        "root", "admin");
      // Getting DatabaseMetaData object
      DatabaseMetaData dbMetaData = connection.getMetaData();
    
      // getting Database Schema Names
      ResultSet rs = connection.getMetaData().getCatalogs();
      while (rs.next()) {
        System.out.println("Schema Name - " + rs.getString("TABLE_CAT"));
      }
      
   } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }finally{
      if(connection != null){
       //closing connection 
       try {
         connection.close();
       } catch (SQLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
      } // if condition
    }// finally
  }
}

Two points to note here are-

  • In the DB URL you are providing for connection, you don’t have to provide any specific schema. So your URL would be like this– jdbc:mysql://localhost:3306
  • getCatalogs() method returns a resultset which has only one column “TABLE_CAT” so you can use that column to get value or column index as 1 to get the value. i.e. rs.getString("TABLE_CAT") or rs.getString(1). By iterating through that result set you can get the list of all DB schemas.

That's all for this topic Java Program to Get All DB Schemas. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Get All The Tables in a DB Schema
  2. Connection Pooling Using Apache DBCP in Java
  3. Connection Pooling Using C3P0 in Java
  4. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  5. CallableStatement Interface in Java-JDBC

You may also like-

  1. Remove Duplicate Elements From an Array in Java
  2. Convert float to String in Java
  3. Configuring DataSource in Spring Framework
  4. Spring JdbcTemplate Insert, Update And Delete Example
  5. Garbage Collection in Java
  6. Java Stream API Tutorial
  7. ConcurrentHashMap in Java With Examples
  8. Synchronization in Java - Synchronized Method And Block

Saturday, June 19, 2021

Java Program to Get All The Tables in a DB Schema

In this post we’ll see a Java program to get all the tables in a schema in a DB. Database used here is MySQL.

For listing DB schema tables in Java you can use getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) method provided by the DatabaseMetaData interface in the JDBC API. You can provide null as value for all the parameters, that way you don’t narrow the search and all the tables are returned. If you want to narrow your search to get specific tables then you can provide values for these parameters.

Listing DB schema tables Java example

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBMetaData {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");

      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/world", 
                          "root", "admin");
      // Getting DatabaseMetaData object
      DatabaseMetaData dbMetaData = connection.getMetaData();
     
      ResultSet rs = dbMetaData.getTables(null, null, null, null);       
      
      while (rs.next()){
        System.out.println(""Table name - " " + rs.getString(3));
      }    
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } // if condition
    }// finally
  }
}

Points to note here are-

  • Here connection is made to the “world” schema in the MySQL DB ( jdbc:mysql://localhost:3306/world) so program will list all the table names in the world schema.
  • Returned resultset has table description rows where each row has following columns -
Table Descrition Columns
Column NameTypeDescription
TABLE_CAT String table catalog (may be null)
TABLE_SCHEM String table schema (may be null)
TABLE_NAME String table name
TABLE_TYPE String table type. Typical types are "TABLE", "VIEW" etc.
REMARKS String explanatory comment on the table (may be null)
TYPE_CAT String the types catalog (may be null)
TYPE_SCHEM String the types schema (may be null)
TYPE_NAME String type name (may be null)
SELF_REFERENCING_COL_NAME String name of the designated "identifier" column of a typed table (may be null)
REF_GENERATION String specifies how values in SELF_REFERENCING_COL_NAME are created.

That’s why column index is 3 while getting result from ResultSet in the Java code as TABLE_NAME is at number 3.

That's all for this topic Java Program to Get All The Tables in a DB Schema. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Connection Pooling Using C3P0 in Java
  2. Connection Pooling Using Apache DBCP in Java
  3. Java Program to Get All DB Schemas
  4. DataSource in Java-JDBC
  5. CallableStatement Interface in Java-JDBC

You may also like-

  1. Count Total Number of Times Each Character Appears in a String - Java Program
  2. Add Double Quotes to a String Java Program
  3. How to Run a Shell Script From Java Program
  4. Difference Between Two Dates in Java
  5. Interface Default Methods in Java
  6. Try-With-Resources in Java With Examples
  7. Java ThreadLocal Class With Examples
  8. Method Reference in Java

Friday, June 18, 2021

Format Date in Java Using SimpleDateFormat

If you want to create your own customized formats to format a date in Java, you can do that using the SimpleDateFormat class.

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determine the format of the date and time.

For example-
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

Here the specified pattern is "MM/dd/yyyy" so the date will be formatted in that pattern.

Formatting date using SimpleDateFormat Java examples

In the example code several String patterns are used to create SimpleDateFormat object which are then used to format date. Comment along with the pattern shows how date is displayed using that pattern.

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatDate {

 public static void main(String[] args) {
  FormatDate fd = new FormatDate();
  
  // For date in format Wed, Jun 8, '16
  fd.getFormattedDate("EEE, MMM d, ''yy");

  // For date in format Wednesday, June 08, 2016
  fd.getFormattedDate("EEEE, MMMM dd, yyyy");

  // For date in format 05/08/2016
  fd.getFormattedDate("MM/dd/yyyy");

  // For date in format 08/05/2016
  fd.getFormattedDate("dd/MM/yyyy");

  // For date in format 2016-05-08 AD at 09:42:54 IST
  // with era designator (AD in this case) and 
  // timezone info (IST in this case)
  fd.getFormattedDate("yyyy-MM-dd G 'at' hh:mm:ss z");

  //For date in format 08/May/2016 AD 21:47:28:889 PM
  //with AM/PM marker, time in 24 Hr fmt, miliseconds
  // also included
  fd.getFormattedDate("dd/MMMMM/yyyy GGG HH:mm:ss:SSS a");

  // Only time like 21:52:14:096 PM
  // in 24 hr format, with mili seconds and AM/PM marker
  fd.getFormattedDate("HH:mm:ss:SSS a");

 }
 
 public void getFormattedDate(String pattern){
  Date today;
  String result;
  SimpleDateFormat formatter;
  // Creating the date format using the given pattern
  formatter = new SimpleDateFormat(pattern);
  // Getting the date instance
  today = new Date();
  // formatting the date
  result = formatter.format(today);
  System.out.println("Pattern: " + pattern + 
    " Formatted Date - " + result);
 }

}

Output

Pattern: EEE, MMM d, ''yy Formatted Date - Sun, May 8, '16
Pattern: EEEE, MMMM dd, yyyy Formatted Date - Sunday, May 08, 2016
Pattern: MM/dd/yyyy Formatted Date - 05/08/2016
Pattern: dd/MM/yyyy Formatted Date - 08/05/2016
Pattern: yyyy-MM-dd G 'at' hh:mm:ss z Formatted Date - 2016-05-08 AD at 10:13:46 IST
Pattern: dd/MMMMM/yyyy GGG HH:mm:ss:SSS a Formatted Date - 08/May/2016 AD 22:13:46:090 PM
Pattern: HH:mm:ss:SSS a Formatted Date - 22:13:46:092 PM

Symbols used for creating date patterns in Java

Symbol Meaning Presentation Example
G era designator Text AD
y year Number 2009
M month in year Text & Number July & 07
d day in month Number 10
h hour in am/pm (1-12) Number 12
H hour in day (0-23) Number 0
m minute in hour Number 30
s second in minute Number 55
S millisecond Number 978
E day in week Text Tuesday
D day in year Number 189
F day of week in month Number 2 (2nd Wed in July)
w week in year Number 27
W week in month Number 2
a am/pm marker Text PM
k hour in day (1-24) Number 24
K hour in am/pm (0-11) Number 0
z time zone Text Pacific Standard Time
' escape for text Delimiter (none)
' single quote Literal '

Date Format Pattern Syntax

The number of symbol letters you specify also determines the format.

As exp. symbol for which the presentation style is text if length is 1-3 then abbreviated form is used if length is >= 4 then full form is used. In the above code it can be seen when 'EEE' is given it shows SUN as the day of the week, when 'EEEE' is given then Sunday is displayed.

Same way for month for which presentation style is text/number if length is 1-2 then number form is used when length is 3 (or more) then text form is used.

Source: https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html

That's all for this topic Format Date in Java Using SimpleDateFormat. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Convert Date And Time Between Different Time-Zones in Java
  2. How to Display Time in AM-PM Format in Java
  3. Difference Between Two Dates in Java
  4. How to Find Last Modified Date of a File in Java
  5. How to Convert String to Date in Java

You may also like-

  1. How to Read File From The Last Line in Java
  2. How to Sort ArrayList of Custom Objects in Java
  3. How to Untar a File in Java
  4. Split a String Java Program
  5. Marker interface in Java
  6. Difference Between Checked And Unchecked Exceptions in Java
  7. Java ThreadLocal Class With Examples
  8. CopyOnWriteArrayList in Java With Examples

Thursday, June 17, 2021

Spring p-namespace For Shorter XML Configuration in Spring

While using Spring XML configuration for wiring beans you would have used <property> element several times for providing property values and/or providing reference for beans. If you are looking for any shorter alternative to nested <property> element you can use p-namespace in Spring.

The p-namespace enables you to use the bean element’s attributes, instead of nested <property/> elements.

As example–

If you have a XML configuration for bean employee with property officeAddress of type Address which refers to another bean address like this–

<bean id="employee" class="org.netjs.model.Employee">
    <property name="officeAddress" ref="address"/>
</bean>
You can use p-namespace in Spring to shorten it like this–
<bean id="employee" class="org.netjs.model.Employee" p:officeAddress-ref="address">
    <!-- <property name="officeAddress" ref="address"/> -->
</bean>

You can see here that instead of using nested <property> element you can use bean element’s attribute itself.

In this way of using p-namespace for injection of bean reference p:officeAddress-ref="address", p: denotes the use of p-namespace, officeAddress is the property name with in the employee class where value is injected, -ref indicates injection of bean reference.

Using p-namespace with literals

Same way p-namespace can be used for injecting literal values.

As example

If you have a XML configuration for bean employee which has a property empName then you can provide a literal value to empName property like this-

<bean id="employee" class="org.netjs.model.Employee">
    <property name="empName" value="Ram"/>
</bean>

Using p-namespace you can shorten it like this–

<bean id="employee" class="org.netjs.model.Employee" p:empName="Ram">
    <!-- <property name="empName" value="Ram"/> -->
</bean>

Spring p-namespace example

As we have already seen there are two classes Address and Employee where Address class bean is referred in Employee.

Address class

public class Address {
 private String number; 
 private String street; 
 private String city; 
 private String state; 
 private String pinCode; 
 public String getNumber() {
  return number;
 }
 public void setNumber(String number) {
  this.number = number;
 }
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 public String getPinCode() {
  return pinCode;
 }
 
 public void setPinCode(String pinCode) {
  this.pinCode = pinCode;
 }
}

Employee class

public class Employee {
 private int empId;
 private String empName;
 private int age;
 private Address officeAddress;
 
 public Address getOfficeAddress() {
  return officeAddress;
 }
 public void setOfficeAddress(Address officeAddress) {
  this.officeAddress = officeAddress;
 }
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd">
   
  <bean id="address" class="org.netjs.model.Address" p:number="101" p:street="M I Road" 
    p:city="Jaipur" p:state="Rajasthan" p:pinCode="302001"> 
  </bean>
  <bean id="employee" class="org.netjs.model.Employee" p:empId="1001" p:age="25" 
    p:empName="Ram" p:officeAddress-ref="address">
    <!-- <property name="empName" value="Ram"/> -->
  </bean>   
</beans>

Here notice the inclusion of xmlns:p="http://www.springframework.org/schema/p in XML configuration for p-namespace.

Test Class

You can run this code using the following code-
public class App {
 public static void main(String[] args) {
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
    ("appcontext.xml");
  Employee emp = (Employee)context.getBean("employee");  
  Address addr = emp.getOfficeAddress();
  System.out.println("Name " + emp.getEmpName());
  System.out.println("Age " + emp.getAge());
  System.out.println("city " + addr.getCity());
  context.close(); 
 }
}

Output

Name Ram
Age 25
city Jaipur

Points to remember

  1. The p-namespace is not as flexible as the standard XML format. For example, the format for declaring property references clashes with properties that end in Ref, whereas the standard XML format does not. If you want to reference bean named address and you also have the property named as address-ref then it will result in a clash if you use p-namespace.
  2. You can’t use p-namespace while wiring a collection.

That's all for this topic Spring p-namespace For Shorter XML Configuration in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Using c-namespace in Spring
  2. Spring Profiles With Examples
  3. registerShutdownHook() Method in Spring Framework
  4. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  5. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

You may also like-

  1. Wiring Collections in Spring
  2. How to Read Properties File in Spring Framework
  3. Difference Between component-scan And annotation-config in Spring
  4. Configuring DataSource in Spring Framework
  5. How to Sort ArrayList of Custom Objects in Java
  6. How HashMap Works Internally in Java
  7. Callable and Future in Java With Examples
  8. Is String Thread Safe in Java