Tuesday, August 31, 2021

PostgreSQL - Create Database

In this tutorial you'll learn how to create database in PostgreSQL using both-
  1. SQL shell (command line)
  2. pgAdmin4 (Graphical interface)

Creating DB using SQL shell

Command that you can use to create a new DB is-

CREATE DATABASE dbname;
  1. Open SQL shell, provide the user name and password to connect to server.
  2. Type command CREATE DATABASE testdb; to create a database named testdb.

Monday, August 30, 2021

How to Loop or Iterate an Arraylist in Java

There are many ways to loop or iterate an ArrayList in Java. We can use the simple for loop, for-each loop (advanced for loop) available from Java 5 onwards, iterator or ListIterator (though not a preferred way if we are just sequentially looping through the elements of a list) and from Java 8 using Java 8 forEach statement that works with stream.

So the options available to loop through an ArrayList in Java are-

  • for loop
  • for-each loop
  • iterator
  • ListIterator
  • Java 8 forEach loop

Sunday, August 29, 2021

HashSet in Java With Examples

HashSet in Java is the implementation of the Set interface and it is an unordered collection meaning insertion order is not maintained in a HashSet.

Following are the important points about the HashSet in Java.
  1. HashSet is part of Java Collections framework. HashSet class extends AbstractSet and implements Set, Cloneable and Serializable interfaces.
  2. HashSet is an unordered collection. A hash is calculated using the element that is added to the HashSet and that decides where the element will be stored.
  3. HashSet only stores unique elements, meaning duplicates are nor allowed.
  4. HashSet permits one null element to be added.
  5. HashSet implementation is not synchronized hence not thread safe. If HashSet is to be used in a multi-threaded environment where it is accessed and modified concurrently then it must be synchronized externally. That can be done by wrapping the set with in Collections.synchronizedSet method.
  6. The iterators returned by HashSet's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException.

Saturday, August 28, 2021

@Required Annotation in Spring Framework

In your Spring bean you may have some fields for which you want to ensure that those fields have been populated. Spring framework has a @Required annotation to ensure that.

@Required annotation in Spring

The @Required annotation applies to bean property setter methods. This annotation simply indicates that the bean property annotated with the @Required annotation must be configured to be dependency-injected with a value, through an explicit property value in a bean definition or through autowiring.

If the property annotated with @Required annotation is not set, BeanInitializationException exception will be thrown.

For Spring @Required annotation to work you also need to register RequiredAnnotationBeanPostProcessor that enforces required JavaBean properties to have been configured. Rather than directly registering RequiredAnnotationBeanPostProcessor preferred way is to include the <context:annotation-config/> tag in an XML-based Spring configuration. By using this tag following post-processors are implicitly registered AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor and RequiredAnnotationBeanPostProcessor.

You can also use <context:component-scan> if you are configuring your beans to be automatically discovered in Spring.

Thursday, August 19, 2021

Spring Batch Processing With List of Objects in batchUpdate() Method

In the post Spring Batch Processing Using JDBCTemplate batchUpdate() Method we have already seen how you can use batchUpdate() method with BatchPreparedStatementSetter interface for processing similar queries as batch. In this post we’ll see another option for batch processing in Spring where list of objects is passed.


Spring Batch processing with a List of objects

For batch processing with Spring both the JdbcTemplate and the NamedParameterJdbcTemplate provides an alternate way to use batchUpdate() method. Instead of implementing a special batch interface BatchPreparedStatementSetter, you provide all parameter values in the call as a list. Spring framework loops over these values and uses an internal prepared statement setter.

If you are using NamedParameterJdbcTemplate then you provide an array of SqlParameterSource, one entry for each member of the batch. To create this array you can use SqlParameterSourceUtils.createBatch method.

If you are using JdbcTemplate then you need to provide an Object array.

Let’s see example of batch processing in Spring with both JdbcTemplate and NamedParameterJdbcTemplate to make it clearer. Project structure used is same as used in this post Spring Batch Processing Using JDBCTemplate batchUpdate() Method, so please refer it for setting the project structure.

Wednesday, August 18, 2021

@Import Annotation in Spring JavaConfig

If you are using JavaConfig in Spring to configure the bean definitions then, in order to modularize your configurations you can use @Import annotation in Spring.

@Import annotation in Spring JavaConfig allows for loading @Bean definitions from another configuration class so you can group your configuration by modules or functionality which makes your code easy to maintain.

@Import annotation is similar to <import/> element which is used to divide the large Spring XML configuration file into smaller XMLs and then import those resources.

How does Spring @Import annotation work

Let’s say you have two configuration classes ConfigA and ConfigB then you can import ConfigA into ConfigB as shown below.

@Configuration
public class ConfigA {
 @Bean
 public A a() {
  return new A();
 }
}

@Configuration
@Import(ConfigA.class)
public class ConfigB {
 @Bean
 public B b() {
  return new B();
 }
}

Tuesday, August 17, 2021

Marker Interface in Java

Marker interface in Java is an interface that has no method declarations or fields in it. It is used as a tag to let the compiler know it needs to add some special behavior to the class implementing marker interface. That is why marker interface is also known as tag interface in Java.

Some of the examples of marker interface in Java are-

  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.RandomAccess

Monday, August 16, 2021

How to Get The Inserted ID (Generated ID) in JDBC

In this tutorial we’ll see how to get the ID of the newly inserted record in the DB using JDBC. Getting the ID of the inserted record is useful in the scenario when you are using auto-generated ID in the table (Auto_increment, Sequence, Serial) and you want to insert records in the table having Primary Key – Foreign key relationship.

For example suppose there are two tables-

  1. user_master with fields as id (PK), name
  2. accounts with fields as id (PK), acct_number and user_id (FK referencing id of user_master)
get generated id jdbc java

You want to insert user record and then using that generated id of the user you want to make an entry in accounts where the same id is passed for the user_id column. In this scenario after inserting the user record you will want to get hold of the generated user id.

Sunday, August 15, 2021

HashSet Vs LinkedHashSet Vs TreeSet in Java

Though HashSet, LinkedHashSet and TreeSet all are implementation of the Set interface and share some traits like storing only the unique elements, not being thread-safe but there are certain differences too related to performance, how elements are ordered etc. So it is very important to know these differences among HashSet, LinkedHashSet and TreeSet in Java as it will help you to make an informed choice which Set implementation to use to meet the requirement.

HashSet Vs LinkedHashSet Vs TreeSet in Java

  1. First and most important difference is related to the ordering of the elements.
    HashSet is unordered, it will store elements on the basis of the calculated hash that's it.
    LinkedHashSet maintains the insertion ordering of the elements.
    TreeSet keeps the element in sorted order. The sorting orders TreeSet follows by default is the natural ordering of the elements.

  2. Another difference is related to allowing null value.
    HashSet as well as LinkedHashSet allow null value to be stored. Mind you only one null value is allowed in both HashSet and LinkedHashSet.
    TreeSet does not allow null value, trying to add null to a TreeSet will result in a null pointer exception.

  3. For HashSet and LinkedHashSet comparison of the elements is done using equals() method. Note that set allows only unique elements, and that uniqueness is maintained by using the equals() method to compare elements.
    TreeSet does the comparison of the element using the compareTo (or compare) method, depending on whether sorting is done using Comparable or Comparator.
  4. Performance wise HashSet is at the top as it has no added baggage of insertion ordering or sorting. If hashing is done correctly HashSet offers constant time performance O(1) for the basic operations (add, remove, contains and size). As I mentioned this performance is assuming that the hash function disperses the elements properly among the buckets. If HashCode is not proper the performance may degrade and in worst case it will be O(n).
    For LinkedHashSet performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list.
    TreeSet has to sort elements with every insertion so that way performance is slow, but TreeSet provides guaranteed log(n) time cost for the basic operations (add, remove and contains) irrespective of the number of elements stored.

That's all for this topic HashSet Vs LinkedHashSet Vs TreeSet in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashSet Works Internally in Java
  2. EnumSet in Java With Examples
  3. How to Sort Elements in Different Order in TreeSet
  4. Difference Between ArrayList And LinkedList in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Difference Between Comparable and Comparator in Java
  2. Java ReentrantLock With Examples
  3. Lambda expression examples in Java 8
  4. Spliterator in Java
  5. finalize method in Java
  6. super Keyword in Java With Examples
  7. Multi-Catch Statement in Java Exception Handling
  8. Why wait(), notify() and notifyAll() must be called inside a synchronized method or block?

Saturday, August 14, 2021

How to Sort a HashMap in Java

In this post we’ll see how to sort a HashMap in Java which is by design an unordered collection.

You can sort a HashMap on either the keys or the values. You can also use Java Stream API, Java 8 onward to sort a HashMap. So, let’s see example code to sort HashMap in Java on keys as well as values.


Sorting HashMap using keys

If you want to sort a HashMap on keys, just convert HashMap to TreeMap. TreeMap is sorted according to the natural ordering of its keys so just construct a TreeMap by passing your HashMap. Constructor used is this one-

TreeMap(Map<? extends K,? extends V> m)- Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys.

If you want to sort HashMap in different order than the natural ordering then you need to pass a comparator. In that case you can use the following constructor.

TreeMap(Comparator<? super K> comparator)- Constructs a new, empty tree map, ordered according to the given comparator.

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class HashMapSorting {

  public static void main(String[] args) {
    Map<String, String> langMap = new HashMap<String, String>();
    langMap.put("ENG", "English");
    langMap.put("NLD", "Dutch");
    langMap.put("ZHO", "Chinese");
    langMap.put("BEN", "Bengali");
    langMap.put("ZUL", "Zulu");
    System.out.println("-- Original Map --");
    for(Map.Entry<String, String> lang : langMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + 
                    " Value- " + lang.getValue());
    }
    TreeMap<String, String> sortedLangMap = new TreeMap<String, String>(langMap);
    System.out.println("-- Sorted by keys Map--");
    for(Map.Entry<String, String> lang : sortedLangMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + 
            " Value- " + lang.getValue());
    }
  }
}

Output

-- Original Map --
Key- ZHO Value- Chinese
Key- ZUL Value- Zulu
Key- NLD Value- Dutch
Key- BEN Value- Bengali
Key- ENG Value- English
-- Sorted by keys Map--
Key- BEN Value- Bengali
Key- ENG Value- English
Key- NLD Value- Dutch
Key- ZHO Value- Chinese
Key- ZUL Value- Zulu

Sorting HashMap using keys in descending order

If you want HashMap sorting done in descending order then you can pass a Comparator while constructing TreeMap.

public class HashMapSorting {

  public static void main(String[] args) {
    Map<String, String> langMap = new HashMap<String, String>();
    langMap.put("ENG", "English");
    langMap.put("NLD", "Dutch");
    langMap.put("ZHO", "Chinese");
    langMap.put("BEN", "Bengali");
    langMap.put("ZUL", "Zulu");
    System.out.println("-- Original Map --");
    for(Map.Entry<String, String> lang : langMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + 
                    " Value- " + lang.getValue());
    }
    // TreeMap with Comparator
    TreeMap<String, String> sortedLangMap = new TreeMap<String, String>(new Comparator<String>() {
      @Override
      public int compare(String str1, String str2) {
        return str2.compareTo(str1);
      }  
    });
    // Adding HashMap entries to TreeMap
    sortedLangMap.putAll(langMap);
    System.out.println("-- Keys of the Map sorted in descending order --");
    for(Map.Entry<String, String> lang : sortedLangMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + 
            " Value- " + lang.getValue());
    }
  }
}

Output

-- Original Map --
Key- ZHO Value- Chinese
Key- ZUL Value- Zulu
Key- NLD Value- Dutch
Key- BEN Value- Bengali
Key- ENG Value- English
-- keys of the Map sorted in descending order --
Key- ZUL Value- Zulu
Key- ZHO Value- Chinese
Key- NLD Value- Dutch
Key- ENG Value- English
Key- BEN Value- Bengali

Sorting HashMap using Values

If you have to sort HashMap in Java on values then you will have to convert your HashMap to List or Set having Map.Entry values and then sort that List or Set. Then you will have to add values back to a LinkedHashMap as insertion order is maintained in LinkedHashMap.

If you just want the values in sorted order not the (key, value) pair then you can convert the values view of the Map to TreeSet. That will give you values in sorted order as per the natural ordering.

public class HashMapSorting {

  public static void main(String[] args) {
    Map<String, String> langMap = new HashMap<String, String>();
    langMap.put("ENG", "English");
    langMap.put("NLD", "Dutch");
    langMap.put("ZHO", "Chinese");
    langMap.put("BEN", "Bengali");
    langMap.put("ZUL", "Zulu");
    System.out.println("-- Original Map --");
    for(Map.Entry<String, String> lang : langMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + 
                    " Value- " + lang.getValue());
    }
    TreeSet<String> valueSet = new TreeSet<>(langMap.values());
    System.out.println("-- Sorted HashMap Values --");
    for(String str : valueSet) {
      System.out.println(" Value- " + str);
    }
  }
}

Output

-- Original Map --
Key- ZHO Value- Chinese
Key- ZUL Value- Zulu
Key- NLD Value- Dutch
Key- BEN Value- Bengali
Key- ENG Value- English
-- Sorted HashMap Values --
 Value- Bengali
 Value- Chinese
 Value- Dutch
 Value- English
 Value- Zulu

If you want a sorted Map then as I said you need to convert HashMap to List or Set and then sort it. After that put values back in a LinkedHashMap. In this example Set is used.

import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeSet;

public class HashMapSorting {

  public static void main(String[] args) {
    Map<String, String> langMap = new HashMap<String, String>();
    langMap.put("ENG", "English");
    langMap.put("NLD", "Dutch");
    langMap.put("ZHO", "Chinese");
    langMap.put("BEN", "Bengali");
    langMap.put("ZUL", "Zulu");
    System.out.println("-- Original Map --");
    for(Map.Entry<String, String> lang : langMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + 
                    " Value- " + lang.getValue());
    }
    // Creating TreeSet with a comparator
    TreeSet<Map.Entry<String, String>> langSet = new TreeSet<Map.Entry<String, String>>(
      new Comparator<Map.Entry<String, String>>(){
        @Override
        public int compare(Entry<String, String> entry1,
            Entry<String, String> entry2) {
          return entry1.getValue().compareTo(entry2.getValue());
        }          
      });
    // Adding Map.entrySet to TreeSet
    langSet.addAll(langMap.entrySet());
    
    Map<String, String> newMap = new LinkedHashMap<String, String>();
    // Insert values in LinkedHashMap
    for(Map.Entry<String, String> entry : langSet) {
      newMap.put(entry.getKey(), entry.getValue());
    }
    System.out.println("-- Sorted Map(by Value) --");
    for(Map.Entry<String, String> lang : newMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + " Value- " + lang.getValue());
    }
  }
}

If you want to use List to sort a HashMap by values then you can use the following Java code.

public class HashMapSorting {

  public static void main(String[] args) {
    Map<String, String> langMap = new HashMap<String, String>();
    langMap.put("ENG", "English");
    langMap.put("NLD", "Dutch");
    langMap.put("ZHO", "Chinese");
    langMap.put("BEN", "Bengali");
    langMap.put("ZUL", "Zulu");
    System.out.println("-- Original Map --");
    for(Map.Entry<String, String> lang : langMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + 
                    " Value- " + lang.getValue());
    }
    // creating list
    List<Map.Entry<String, String>> newList = new ArrayList<Map.Entry<String, String>>(langMap.entrySet());
    // sorting list
    Collections.sort(newList, new Comparator<Map.Entry<String, String>>(){
      @Override
      public int compare(Entry<String, String> entry1,
            Entry<String, String> entry2) {
        return entry1.getValue().compareTo(entry2.getValue());
      }
        
    });
    
    Map<String, String> newMap = new LinkedHashMap<String, String>();
    // Insert values in LinkedHashMap
    for(Map.Entry<String, String> entry : newList) {
      newMap.put(entry.getKey(), entry.getValue());
    }
    System.out.println("-- Sorted Map(by Value) --");
    for(Map.Entry<String, String> lang : newMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + " Value- " + lang.getValue());
    }
  }
}

Output

-- Original Map --
Key- ZHO Value- Chinese
Key- ZUL Value- Zulu
Key- NLD Value- Dutch
Key- BEN Value- Bengali
Key- ENG Value- English
-- Sorted Map(by Value) --
Key- BEN Value- Bengali
Key- ZHO Value- Chinese
Key- NLD Value- Dutch
Key- ENG Value- English
Key- ZUL Value- Zulu

Sorting HashMap using Java stream

Using Stream API Java 8 onward you can sort a HashMap with very few lines. Java stream API has a sorted method that can be used to sort the elements in the stream, then you can collect it in a LinkedHashMap. Why LinkedHahsMap? To retain the order you get after applying the sorted method.

public class HashMapSorting {

  public static void main(String[] args) {
    Map langMap = new HashMap();
    langMap.put("ENG", "English");
    langMap.put("NLD", "Dutch");
    langMap.put("ZHO", "Chinese");
    langMap.put("BEN", "Bengali");
    langMap.put("ZUL", "Zulu");
    System.out.println("-- Original Map --");
    for(Map.Entry lang : langMap.entrySet()) {
      System.out.println("Key- " + lang.getKey() + 
                      " Value- " + lang.getValue());
    }
    Map newMap = langMap.entrySet().stream().sorted(Map.Entry.comparingByValue())
                                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k,v)->k,LinkedHashMap::new));
    System.out.println("-- Sorted Map --");
    newMap.entrySet().forEach((e)->{System.out.println("Key- " + e.getKey() + " Value- " + e.getValue());});
  }
}

Output

-- Original Map --
Key- ZHO Value- Chinese
Key- ZUL Value- Zulu
Key- NLD Value- Dutch
Key- BEN Value- Bengali
Key- ENG Value- English
-- Sorted Map --
Key- BEN Value- Bengali
Key- ZHO Value- Chinese
Key- NLD Value- Dutch
Key- ENG Value- English
Key- ZUL Value- Zulu

If you want to sort in reversed order then you can use reversed() method of the Comparator class to reverse the sorting order.

Map newMap= langMap.entrySet().stream().sorted(Map.Entry.comparingByValue().reversed())
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k,v)->k,LinkedHashMap::new));

If you want to sort on keys then you can use the following code-

Map newMap = langMap.entrySet().stream().sorted(Map.Entry.comparingByKey())
                     .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k,v)->k,LinkedHashMap::new));

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


Related Topics

  1. How to Sort HashSet in Java
  2. How LinkedList Class Works Internally in Java
  3. Difference Between HashMap And ConcurrentHashMap in Java
  4. How to Sort Elements in Different Order in TreeSet
  5. Fail-Fast Vs Fail-Safe Iterator in Java

You may also like-

  1. Java Multithreading Interview Questions And Answers
  2. Difference Between Encapsulation And Abstraction in Java
  3. strictfp in Java
  4. Try-With-Resources in Java With Examples
  5. String in Java Tutorial
  6. How to Display Time in AM-PM Format in Java
  7. Lazy Initializing Spring Beans
  8. Tips for improving MapReduce performance

Friday, August 13, 2021

How to Loop Through HashSet in Java

In this post we’ll see how you can iterate any Set implementation like HashSet in Java. To loop through a HashSet you have following options, you can choose based on your requirement or the Java version you are using.

  1. First option to iterate a HashSet in Java is to use a ForEach loop, if you are just iterating without doing any structural modification (adding or removing element) to the Set then this is the best option to iterate a HashSet.
  2. Using iterator() method which returns an iterator over the elements in the given Set. If you have to remove any element while iterating then use this option otherwise ConcurrentModificationException will be thrown.
  3. Java 8 onwards you also have an option to use forEach statement to iterate a HashSet in Java.

Iterating a HashSet – Java example

Let’s see a Java example code which illustrates all of the options mentioned above to loop through a HashSet.

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class IterateSetDemo {

  public static void main(String[] args) {
    // creating a HashSet
    Set<String> citySet = new HashSet<String>();
    // Adding elements
    citySet.add("London");        
    citySet.add("Tokyo");
    citySet.add("New Delhi");
    citySet.add("Beijing");
    citySet.add("Nairobi");
    
    System.out.println("-- Iterating HashSet - ForEach loop --");
    for(String city : citySet){
      System.out.println("city- " + city);
    }
    
    System.out.println("-- Iterating HashSet - using iterator --");
    Iterator<String> itr = citySet.iterator();
    while(itr.hasNext()){            
      System.out.println("city- " + itr.next());        
    }
    
    System.out.println("-- Iterating HashSet - using forEach statement-- ");
    citySet.forEach((city)->System.out.println("city- " + city));        
  }
}

Output

-- Iterating HashSet - ForEach loop --
city- Beijing
city- New Delhi
city- Nairobi
city- Tokyo
city- London
-- Iterating HashSet - using iterator --
city- Beijing
city- New Delhi
city- Nairobi
city- Tokyo
city- London
-- Iterating HashSet - using forEach statement-- 
city- Beijing
city- New Delhi
city- Nairobi
city- Tokyo
city- London

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


Related Topics

  1. How to Loop Through a Map in Java
  2. How to Sort HashSet in Java
  3. LinkedHashSet in Java With Examples
  4. How ArrayList Works Internally in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Java ReentrantLock With Examples
  2. How and Why to Synchronize ArrayList in Java
  3. CopyOnWriteArrayList in Java With Examples
  4. Executor And ExecutorService in Java With Examples
  5. Array in Java With Examples
  6. instanceof Operator in Java
  7. Comparing Enum to String in Java
  8. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example

Thursday, August 12, 2021

Nested Try Statements in Java Exception Handling

A try-catch-finally block can reside inside another try-catch-finally block that is known as nested try statement in Java.

When you have nested try statements in your code, in case an exception is thrown the inner most try-catch block gets the first chance to handle that exception, if that try-catch block can not handle the exception, the exception goes up the hierarchy (next try-catch block in the stack) and the next try statement's catch block handlers are inspected for a match. If no catch block, with in the hierarchy, handles the thrown exception then the Java run-time system will handle the exception.

Java nested try statement example

public class NestedTryDemo {
  public static void main(String[] args) {
    try{
      System.out.println("In Outer try block");
      try{
        System.out.println("In Inner try block");
        int a = 7 / 0;
      }catch (IllegalArgumentException e) {
        System.out.println("IllegalArgumentException caught");
      }finally{
        System.out.println("In Inner finally");
      }
    }catch (ArithmeticException e) {
      System.out.println("ArithmeticException caught");
    }finally {
      System.out.println("In Outer finally");
    }
  }
}

Output

In Outer try block
In Inner try block
In Inner finally
ArithmeticException caught
In Outer finally

In this example, one try catch finally sequence has been nested within another try catch finally sequence. The inner try block throws an ArithmeticException which it could not handle, as the inner catch block catches IllegalArgumentException. Hence, this exception moves up the hierarchy and handled in the outer try-catch-finally block.

Better way to use nested try statement

In the above example you have seen how exception propagates and can be handled by the inner or outer block based on which catch block can handle it. But the better way to design nested try statements in Java exception handling is to look for the code sections which are more likely to throw any specific exception and wrap those specific blocks in a try-catch block that can handle that exception and overall code can be wrapped in more general try-catch block.

Java nested try statement example

Let’s change the above code a little bit, now there is a method with an int as argument. That argument is used to divide 7 in the code. You also have a condition that passed argument should be less than or equal to 7 otherwise IllegalArgumentException must be thrown.

Also you need to check for divide by zero condition in which case you must handle ArithmeticException. Overall you may have a try-catch block which can handle any other exception.

To handle this scenario you may start a try block in which you can check if the passed value is less than or equal to 7 or not, if not throw IllegalArgumentException and then have a nested try-catch where you can handle ArithmeticException. After that you can have a catch block for the outer try statement to handle IllegalArgumentException.

So overall there are three try-catch blocks with in the code. One outer try-catch statement and two nested try statement with in it for handling specific exceptions.

public class NestedTryDemo {
  public static void main(String[] args) {
    NestedTryDemo nd = new NestedTryDemo();
    nd.process(8);
  }
 
  private void process(int num){
    try{
      try{
        if(num > 7){
          throw new IllegalArgumentException("Number should not 
                  be greater than 7");
        }
        try{
          System.out.println("In Inner try block");
          int a = 7 / num;
          System.out.println("value of a " + a);
        }catch (ArithmeticException e) {
          System.out.println("ArithmeticException caught - " + e.getMessage());
        }
      }catch(IllegalArgumentException e){
        System.out.println("IllegalArgumentException caught - " + e.getMessage());
      }

    }catch(Exception exp){
      System.out.println("Exception in the code " + exp.getMessage());
    }finally {
      System.out.println("In Outer finally");
    }
  }
}

Output

IllegalArgumentException caught - Number should not be greater than 7
In Outer finally

If you execute the same code by passing 0, then the output will be-

In Inner try block
ArithmeticException caught - / by zero
In Outer finally

If you execute the same code by passing 3, then the output will be

In Inner try block
value of a 2
In Outer finally

That's all for this topic Nested Try Statements in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. final Vs finally Vs finalize in Java
  2. Creating Custom Exception Class in Java
  3. Try-With-Resources in Java With Examples
  4. Difference Between StackOverflowError and OutOfMemoryError in Java
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. finalize() Method in Java
  2. Encapsulation in Java
  3. Marker Interface in Java
  4. Varargs (Variable-length Arguments) in Java
  5. Fail-Fast Vs Fail-Safe Iterator in Java
  6. How HashMap Works Internally in Java
  7. Can we Start The Same Thread Twice in Java
  8. Serialization and Deserialization in Java

Wednesday, August 11, 2021

How to Install PostgreSQL on Windows

In this tutorial we'll see how to download and install PostgreSQL database on Windows 10.

Downloading Postgre

You can download PostgreSQL installer from the URL given below-

https://www.postgresql.org/download/windows/
PostgreSQL Download

Click on Download the installer.

In the next page Select the version of PostgreSQL you want to download by clicking on download button. Select the location where you want to download the exe file.

PostgreSQL Installation Steps

1. Go to the location where you have downloaded the .exe file and double click to start the installation process. In the setup window click on next.

Monday, August 9, 2021

Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation

In your Spring Web MVC application if you are using @PathVariable annotation along with @RequestMapping annotation to retrieve the parameter from the request path, then you may come across one problem- If the passed parameter has a value with a dot in it (i.e. xxx.xx) then the portion after the last dot (.), including dot, gets truncated when the value is assigned to the variable annotated with @PathVariable annotation.

For example– If you have a handler method in your controller like below.

@RequestMapping(value = "/ip/{address}")
public void processIP(@PathVariable("address") String address) {
 ..
 ..
}

Then the URI /ip/345.67.56.45 will assign 345.67.56 to the variable address.
URI /ip/198.201.231 will assign 198.201 to the variable address.

So, you can see that the value starting from the last dot is always truncated while assigning to the variable annotated with @PathVariable annotation.

Saturday, August 7, 2021

Angular Disable Button Example

In this post we’ll see some examples of disabling a button in Angular. There is a disabled property of button that can be set to true or false in order to disable or enable a button.

So disabling a button is as simple as using the statement given below-

<button class="btn btn-primary" [disabled]="true">Submit</button>

Of course you’ll bind it with some property or use a condition to disable or enable a button dynamically so let’s see examples of doing that.


Disable a button if no input text Angular example

To ensure that button is disable when there is no text and it is enable only when some text is entered you can use two way Angular two way databinding.

Template

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <label for="name" class="col-form-label">Name:</label>
      <input class="form-control" placeholder="Enter name" id="name" [(ngModel)]="userName">        
    </div>
  </div>
  <div class="row mt-3">
    <div class="col-md-12">
      <button class="btn btn-primary" [disabled]="userName === ''">Submit</button>
    </div>
  </div>
</div>

As you can see userName is bound to the property in the Typescript file using two way binding. Then using Angular property binding button’s disabled property is bound to a condition that checks if userName is empty.

[disabled]="userName === ''"

Thursday, August 5, 2021

Angular @ViewChildren Decorator With Examples

@ViewChildren decorator in Angular is used to get reference list of elements or directives from the view DOM in a Component class. Using @ViewChildren decorator you can configure a view query, that is done by passing a selector with @ViewChildren. For example

@ViewChildren('uname') userName: QueryList<UserComponent>

Here 'uname' is the passed selector. ViewChildren looks for all the elements or the directives matching the selector in the view DOM and return them as an instance of QueryList which is another class in Angular used to store unmodifiable list of items.

If a child element is added, removed, or moved, the query list will be updated, and the changes function of the QueryList will emit a new value.

Once you have access to DOM elements in the parent Component you can do DOM manipulation.


View queries and ngAfterViewInit callback

View queries are set before the ngAfterViewInit callback is called. That means ngAfterViewInit callback is the best place to manipulate the element or directive by using the reference variable.

@ViewChildren Metadata Properties

You can pass the following three metadata properties with @ViewChildren decorator.

  • selector- The directive type or the name used for querying.
  • read- Used to read a different token from the queried elements. It is an optional property.
  • emitDistinctChangesOnly- When used the changes method of the QueryList will emit new values only if the QueryList result has changed. Note that this config option is deprecated, right now it is true by default and will be permanently set to true .

Syntax of ViewChildren-

@ViewChildren(selector, { read?: any;})

Wednesday, August 4, 2021

Running Dos/Windows Commands From Java Program

If you want to run DOS or Windows commands from a Java program it can be done using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).

Java RunTime class

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

In RunTime class there is a exec() method that executes the specified string command in a separate process. Using this exec() method dos or windows commands can be executed from Java.

Runtime.getRunTime().exec to run dos/windows commands in Java example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RunningCommand {
  public static void main(String[] args) {
    Process p;
    try {
      p = Runtime.getRuntime().exec("cmd /c dir");

      p.waitFor(); 
      BufferedReader reader=new BufferedReader(new InputStreamReader(
                  p.getInputStream())); 
      String line; 
      while((line = reader.readLine()) != null) { 
        System.out.println(line);
      } 
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Volume in drive C is OS
Volume Serial Number is AEC2-FEE9

 Directory of C:\workspace\abc

10/19/2016  12:39 PM    <DIR>          .
10/19/2016  12:39 PM    <DIR>          ..
10/24/2016  03:22 PM               592 .classpath
10/19/2016  12:39 PM               379 .project
10/19/2016  12:39 PM    <DIR>          .settings
10/21/2016  03:16 PM    <DIR>          bin
10/19/2016  12:39 PM    <DIR>          src
               2 File(s)            971 bytes
               5 Dir(s)  40,032,706,560 bytes free

Here it can be seen that directory listing is displayed for the directory which happens to be the workspace directory from where I executed the Java program.

Runtime.getRuntime().exec method is used to run the command.

  • public static Runtime getRuntime() - Returns the runtime object associated with the current Java application.
  • public Process exec(String command) throws IOException - Executes the specified string command in a separate process.

cmd /c which is used with the command has the following explanantion -

  • cmd- Starts a new command shell
  • /c- Executes the given command and terminates

Execution of the command returns instance of class Process. Using the getInputStream() method of Process class output of the executed command can be printed by reading the stream.

Running command Using ProcessBuilder

You can also use ProcessBuilder class to run dos or windows command from Java. If you have to run the same command as used above using ProcessBuilder, which is a much clearer way to do that, you can create a list with the command and the required arguments and then pass it to ProcessBuilder instance as command.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class RunningCommand {
  public static void main(String[] args) {
    Process p;
    try {
      List<String> cmdList = new ArrayList<String>();
      cmdList.add("cmd");
      cmdList.add("/c");
      cmdList.add("dir");
      ProcessBuilder pb = new ProcessBuilder();
      pb.command(cmdList);
      p = pb.start();
    
      p.waitFor(); 
      BufferedReader reader=new BufferedReader(new InputStreamReader(
                p.getInputStream())); 
      String line; 
      while((line = reader.readLine()) != null) { 
        System.out.println(line);
      } 
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

That's all for this topic Running Dos/Windows Commands From Java Program. 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 Compile Java Program at Runtime
  2. How to Run javap Programmatically From Java Program
  3. How to Run a Shell Script From Java Program
  4. How to Run Threads in Sequence in Java
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program

You may also like -

  1. Difference Between Two Dates in Java
  2. Initializer block in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. TreeMap in Java With Examples
  5. Java Exchanger With Examples
  6. ConcurrentSkipListMap in Java With Examples
  7. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  8. Functional Interfaces in Java

Tuesday, August 3, 2021

ng-template in Angular

In this tutorial we’ll learn in detail about <ng-template> element in Angular.


Using ng-template

Using <ng-template> element in Angular you can define a template that doesn't render anything by default. Here note that it "only defines a template". That gives you control over how the content is displayed.

For example if you just wrap some elements in an <ng-template> without using any structural directive or some other way to display those wrapped elements, those elements disappear.

<p>Using ng-template here</p>
<ng-template>
    <p>This text is not displayed</p>
</ng-template>

The above code will display only-

Using ng-template here

<p> element wrapped within <ng-template> is not displayed.

Now we’ll see how <ng-template> is already used by many built-in structural directives in Angular. We’ll also see how to use <ng-template> in conjunction with ngTemplateOutlet and with TemplateRef to render the wrapped elements.

Sunday, August 1, 2021

Spring MessageSource Internationalization (i18n) Support

In an interview if difference between BeanFactory and ApplicationContext is asked one of the reason given by people to use ApplicationContext is the support for internationalization provided by ApplicationContext. This post shows the same thing; how Internationalization (i18n) using ApplicationContext and MessageSource can be provided in Spring.

Spring ApplicationContext and MessageSource

The ApplicationContext interface extends an interface called MessageSource in Spring framework which provides support for internationalization (i18n) functionality. Spring also provides the interface HierarchicalMessageSource, which can resolve messages hierarchically. Using these two interfaces Spring effects message resolution. The methods defined on these interfaces include:

  • String getMessage(String code, Object[] args, String default, Locale loc)- The basic method used to retrieve a message from the MessageSource. When no message is found for the specified locale, the default message is used. In the properties file it will look for the key which is having the same values as code parameter.
  • String getMessage(String code, Object[] args, Locale loc)- Essentially the same as the previous method, but with one difference: no default message can be specified; if the message cannot be found, a NoSuchMessageException is thrown.
  • String getMessage(MessageSourceResolvable resolvable, Locale locale)- All properties used in the preceding methods are also wrapped in a class named MessageSourceResolvable, which you can use with this method.

When an ApplicationContext is loaded, it automatically searches for a MessageSource bean defined in the context. The bean must have the name messageSource. If such a bean is found, all calls to the preceding methods are delegated to the message source.

There are two MessageSource implementations provided by Spring framework ResourceBundleMessageSource and StaticMessageSource. The StaticMessageSource is rarely used but provides programmatic ways to add messages to the source. ResourceBundleMessageSource can be configured as shown below.

<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">