Thursday, 18 December 2014

Java Regular Expressions (Regex) with Examples

          A Regular Expression (Regex) defines a search pattern for strings. A search pattern can be as simple as a single character, a fixed string, or a complex expression containing special characters that describe a specific pattern. The pattern defined by a regular expression may match a given string once, multiple times, or not at all.

Regular expressions are commonly used to search, validate, edit, and manipulate text. A Regular Expression is also known as a regex or regexp.

The java.util.regex package was introduced in Java SE 1.4. If you are using an older version of Java, it is recommended that you upgrade to a newer version.

The java.util.regex package contains the following three main classes:

  • Pattern – Represents a compiled regular expression.

  • Matcher – Performs match operations on an input string using a Pattern.

  • PatternSyntaxException – Indicates a syntax error in a regular expression pattern.


  1. Pattern
    The Pattern class represents the compiled version of a regular expression. It does not have a public constructor. Instead, you can create a Pattern object by using its static compile() method and passing the regular expression as an argument.

  2. Matcher
    The Matcher class is the regular expression engine that performs match operations on an input string using a Pattern object. This class also does not have a public constructor. You can obtain a Matcher object by calling the matcher() method on a Pattern object and passing the input string as an argument. The matches() method returns a boolean value indicating whether the entire input string matches the specified regular expression.

  3. PatternSyntaxException
    The PatternSyntaxException class is thrown when the syntax of a regular expression is invalid.


Java Regular Expression Metacharacters

Regular expressions provide several metacharacters, which are special characters used as shorthand for common matching patterns. These metacharacters make regular expressions more powerful and concise.

The ^ and $ metacharacters are known as anchors:

  • ^ – Indicates the beginning of a line or string.

  • $ – Indicates the end of a line or string.

To ensure that the entire input matches a pattern, the regular expression is typically enclosed between ^ and $.

Common Regular Expression Metacharacters

MetacharacterDescription
\dMatches any digit. Equivalent to [0-9].
\DMatches any non-digit. Equivalent to [^0-9].
\sMatches any whitespace character.
\SMatches any non-whitespace character.
\wMatches any word character. Equivalent to [a-zA-Z0-9_].
\WMatches any non-word character. Equivalent to [^\w].
\bMatches a word boundary.
[..]Matches any single character within the brackets.
[^..]Matches any single character not within the brackets.
\tMatches a tab character (U+0009).
\vMatches a vertical tab (U+000B).
+Matches the preceding character one or more times. Equivalent to {1,}.
*Matches the preceding character zero or more times. Equivalent to {0,}.
?Matches the preceding character zero or one time. Equivalent to {0,1}.
.Matches any single character except the newline character.

Examples

Below are some commonly used regular expressions:

Regular ExpressionDescription
^\\d+$Matches one or more numeric digits only.
^\\w+$Matches one or more alphanumeric characters and underscores.
^[a-z0-9_-]{3,16}$Matches lowercase letters, digits, underscores (_), or hyphens (-). The length must be between 3 and 16 characters.
^\\d{5}$Matches exactly five numeric digits.
^(\\d{1,2})-(\\d{1,2})-(\\d{4})$Matches a date in the dd-MM-yyyy format (basic format validation only).

Regular Expression Example

Regular expressions make it possible to find all occurrences of text that match a specific pattern. They can also be used to determine whether an input string matches a pattern by returning a boolean value (true or false).

Regular expressions are widely used for validating user input, such as phone numbers, Social Security numbers, email addresses, web form data, decimal values, numeric values, alphanumeric strings, and many other text formats.

For example, if a regular expression is designed to match only numeric values and the input string satisfies that pattern, the input is considered a valid numeric value. Otherwise, the validation fails.

     import java.util.ArrayList;  
     import java.util.List; 
     public class ValidateDemo {  
            public static void main(String[] args)  {
                    List<String> input = new ArrayList<String>(); 
                    input.add("123");
                    input.add("98HT12");
                    input.add("345") ;
                    for (String numeric : input) { 
                             if (numeric.matches("^\\d+$")) { 
                                      System.out.println("Numerics : " + numeric);  
                             } 
                   } 
            }                
    }

Output:-
      Numerics : 123
      Numerics : 345
      

Syntax Error Validation in Java Using Pattern:-

        public class RegularExpValidation {
                public static void main(String[] args){
                        String valid = RegExpValidation("^\\w{1,$");
                        if(valid != null ){
                               System.out.println(valid);
                        } 
               }

               public static String RegExpValidation(String regPattern){
                       String errorMessage = null;
                       try {
                               Pattern.compile(regPattern);
                       }
                       catch (PatternSyntaxException exception) {
                              errorMessage = exception.getDescription();
                       }
                       return errorMessage;
              }
       }

Output:-
     Illegal repetition

Backslashes in Java with Regular Expressions:-

           In literal Java strings the backslash is an escape character. The literal string "\\" is a single backslash. In regular  expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash. This regular expression as a Java string, becomes "\\\\". That's right: 4 backslashes to match a single one.

The regex \w matches a word character. As a Java string, this is written as "\\w".

Saturday, 8 November 2014

Postgresql Trigger Example(Appending Dynamic Column Name):-

Postgresql Trigger Example(Appending Dynamic Column Name):-


            In this example there are two tables REGISTRATION_PREFERENCES & PATIENT_HEADER_PREFERENCES.
            In registration_preferences there are 28 columns. out of this 28 , 19 column names are custom_field1_label,custom_field2_label,....,custom_field19_label other 9 columns are also samething. It start with custom_list1_name,custom_list2_name ,.....,custom_list9_name.
           In patient_header_preferences there is only one column i.e field_desc. This column value can contains all column value of registration_preferences. Mean field_desc column having 28 rows.

Question:-    When you update the registration_preferences table then we should update the field_desc column of the patient_header_preferences table.

           In registration_preferences out 0f 28, 19 column names are same except 1 to 19. appending 1 to 19 in function using while loop. other 9 columns are also samething. It start with custom_list1_name,custom_list2_name ,.....,custom_list9_name. Here also appended 1 to 9 in function using another while loop.

   First create function modify_patient_header_pref that you can call it in trigger.

DROP FUNCTION IF EXISTS modify_patient_header_pref() CASCADE;
CREATE FUNCTION modify_patient_header_pref() RETURNS TRIGGER AS $$
DECLARE
    i integer;
    pcolName character varying;
    regFieldName character varying;
    regColName character varying;
    defaultValue character varying;
BEGIN
   i:=1;
   while(i<20)
    loop
         regColName := 'custom_field' || i::text || '_label';
         pcolName := 'custom_field'|| i::text;
         regFieldName := '(' || quote_literal(NEW) || '::' || TG_RELID::regclass || ').' || regColName;
         defaultValue := 'Custom Field ' || i::text;

          EXECUTE $SomeTag$UPDATE patient_header_preferences SET field_desc=CASE WHEN ($SomeTag$ || regFieldName || $SomeTag$ !='') THEN $SomeTag$ || regFieldName || $SomeTag$ ELSE '$SomeTag$|| defaultValue || $SomeTag$' END WHERE field_name = '$SomeTag$ || pcolName || $SomeTag$'$SomeTag$;
         i:=i+1;
   END loop;

   i := 1;
   while(i<10)
     loop
        regColName := 'custom_list' || i::text || '_name';
        pcolName := 'custom_list' || i::text ||'_value';
        regFieldName := '(' || quote_literal(NEW) || '::' || TG_RELID::regclass || ').' || regColName;
        defaultValue := 'Custom List ' || i::text;

          EXECUTE $SomeTag$UPDATE patient_header_preferences SET field_desc=CASE WHEN ($SomeTag$ || regFieldName || $SomeTag$ !='') THEN $SomeTag$ || regFieldName || $SomeTag$ ELSE '$SomeTag$|| defaultValue || $SomeTag$' END WHERE field_name = '$SomeTag$ || pcolName || $SomeTag$'$SomeTag$;
        i:=i+1;
     END loop;

RETURN NEW;
END;
$$ language plpgsql;

DROP TRIGGER IF EXISTS update_patient_header_preferences ON registration_preferences;
CREATE TRIGGER update_patient_header_preferences after UPDATE ON registration_preferences FOR each row EXECUTE PROCEDURE modify_patient_header_pref();

Sunday, 17 August 2014

Java Date and Calendar Examples

 Date Examples and Conversions:--


             In this post shows you how to work with java.util.Date() and java.util.Calendar examples and also to conversions.
            Date is sufficient if you need only a current timestamp in your application, and you do not need to operate on dates, e.g., one-week later. You can further use SimpleDateFormat to control the date/time display format.

If you want to display the current system date using the Date() class is as follows,

                 java.util.Date date = new java.util.Date();

                 System.out.println(date);

In this code you will get output:- Sun Aug 10 00:59:22 IST 2014.
Here you will get Week,Month,Day,Time,Region and Year.

 Some common date and time patterns used in the java.text.SimpleDateFormat are

       d      -       indicates day 1 to 31,
      dd     -       indicates day in two digits including zero e.g 01 to 31.
       E     -       Day name in week e.g Monday,Tuesday and so on.
       M    -       indicates Month e.g 1 to 12,MM indicates month in two digits like 01 to 12
                               MMM  -   indicates month in words e.g Jan,Feb,Mar and so on
                               MMMM - indicates month in full words e.g Janaury,February and so..
       y        -     indicates Year e.g 2014
       a        -     am/pm Marker e.g AM/PM.
       H       -     hour in day e.g 0-23.
       h        -     hour in am/pm e.g 1-12.
       m       -     minute in hour 0-60.
       s         -    second in minute 0-60.

If you want to display only specific Date format then use SimpleDateFormat,

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

             String date = sdf.format(new java.util.Date());
             System.out.println(date);

The output- 05/10/2014.

    Date with time example,

            SimpleDateFormat  sdf = new SimpleDateFormat("dd/MM/yyyy  hh:mm:ss");
            String date = sdf.format(new java.util.Date());
            System.out.println(date);

The output- 05/10/2014 01:10:29

            The above example is to converting the Date into String. Next see how to convert the String into Date Format using  SimpleDateFormat,

            String date = "20/07/2014";
            SimpleDateFormat  sdf = new SimpleDateFormat("dd/MM/yyyy");
            System.out.println(sdf.parse(date));           //parse method can convert string to date

The output-Sun Jul 20 00:00:00 IST 2014.

    The above sdf.parse(date) returns the Date object with specified date format.

Summary of Date class:
  •  Date  class is sufficient if you just need a simple timestamp.                                                                  
  • You could use SimpleDateFormat to control the date/time display format.
        Use java.text.DateFormat to format a Date (form Date to text) and parse a date string (from text to Date). SimpleDateFormat is a subclass of DateFormat.

      Date is legacy class, which does not support internationalization. Calendar and DateFormat support locale (you need to consider locale only if you program is to be run in many countries concurrently).

         Use java.util.Calendar class if you need to extract year, month, day, hour, minute, and second, or manipulating these field (e.g., 7 days later, 3 weeks earlier).  Next we can discuss Calendar examples.


DateFormat Examples:

 

          java.text.DateFormat is an abstract class for formats (from date to text) and parses (from text to date) date/time in a text-language-independent manner. SimpleDateFormat is an implementation subclass. Date formatter operates on Date object.

      To use the date formatter, first create a DateFormat object for the desired date/time format, and then use the format() method to produce a date/time string. 

To use the DateFormat, use one of these static factory method to create an instance:  

    DateFormat.getDateTimeInstance(): use the default style and locale to format date and time.                 DateFormat.getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale): style  include 
                                            DateFormat.FULL, LONG, MEDIUM, and SHORT.
    DateFormat.getInstance():     uses SHORT style for date and time.
    DateFormat.getDateInstance(), DateFormat.getDateInstance(int style, Locale aLocale):  date only.
    DateFormat.getTimeInstance(), DateFormat.getTimeInstance(int style, Locale aLocale):   time only.

Example:
                 import java.util.Date;
                 import java.text.DateFormat;
                 import java.text.SimpleDateFormat;
                 import java.util.Locale;
                
                 public class DateFormatExample{
                         public static void main(String[] args) {

                                  Date date = new Date();
                                                   // Use DateFormat
                                  DateFormat formatter = DateFormat.getInstance(); // Date and time
                                  String dateStr = formatter.format(date);
                                  System.out.println(dateStr);
                                  formatter = DateFormat.getTimeInstance();        // time only
                                  System.out.println(formatter.format(date));
                                                    // Use locale
                                  formatter = DateFormat.getDateTimeInstance(DateFormat.FULL,                                                                         DateFormat.FULL, Locale.ENGLISH);
                                  System.out.println(formatter.format(date));
 
                         }
                 }

    Output--
                                         8/17/14 10:58 PM
                                         10:59:19 PM
                                         Sunday, August 17, 2014 11:01:27 PM IST

Calendar Examples:--

 The Calendar class provides support for:

    1) maintaining a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR ,                                                                             MINUTE, SECOND, MILLISECOND; and

    2)  manipulating these calendar fields, such as getting the date of the previous week,next week,next 
         month and so on.

Calendar provides internationalization support.

            Calendar is a abstract class, and you cannot use the constructor to create an instance. Instead, you use the static method Calendar.getInstance() to instantiate an implementation sub-class.

     Calendar.getInstance(): return a Calendar instance based on the current time in the default time zone with the default locale.
    Calendar.getInstance(TimeZone zone)
    Calendar.getInstance(Locale aLocale)
    Calendar.getInstance(TimeZone zone, Locale aLocale)

Some of the usefull calendar fields are as follows,

        Calendar.YEAR                      -  Identifies the year.
        Calendar.MONTH                   - Identifies the month.
        Calendar.DAY_OF_MONTH  - Identifies the day.
        Calendar.HOUR                       - Identifies the hour.
        Calendar.MINUTE                   - Identifies the minute.
        Calendar.SECOND                  - Identify the second.

Example:-
                    import java.text.SimpleDateFormat;
                    import java.util.Calendar;

                    public class CalendarExample {
                           public static void main(String[] args) {
                                     // Get an instance of a Calendar, using the current time.
                                  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd                                                                                                               HH:mm:ss");
                                  Calendar calendar = Calendar.getInstance();
                                  System.out.println(dateFormat.format(calendar.getTime()));
                                       // Printing some information...
                                  System.out.println("ERA: " + calendar.get(Calendar.ERA));
                                  System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
                                  System.out.println("MONTH: " + calendar.get(Calendar.MONTH));                
                                  System.out.println("WEEK_OF_YEAR: "+
                                                                  calendar.get(Calendar.WEEK_OF_YEAR));
                                  System.out.println("WEEK_OF_MONTH: " +                   
                                                                  calendar.get(Calendar.WEEK_OF_MONTH));
                                  System.out.println("DATE: " + calendar.get(Calendar.DATE));
                                  System.out.println("DAY_OF_MONTH: " 
                                                                        +calendar.get(Calendar.DAY_OF_MONTH));
                                  System.out.println("DAY_OF_YEAR: " + 
                                                                 calendar.get(Calendar.DAY_OF_YEAR));
                                  System.out.println("DAY_OF_WEEK: " +    
                                                                 calendar.get(Calendar.DAY_OF_WEEK));
                                  System.out.println("DAY_OF_WEEK_IN_MONTH: " +  
                                                                 calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
                                  System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
                                  System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
                                  System.out.println("HOUR_OF_DAY: " + 
                                                                 calendar.get(Calendar.HOUR_OF_DAY));
                                  System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
                                  System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
                                  System.out.println("MILLISECOND: " +   
                                                                         calendar.get(Calendar.MILLISECOND));
                        }
              }

A sample execution is shown below:

2014-02-06 17:33:40
ERA: 1
YEAR: 2014
MONTH: 1
WEEK_OF_YEAR: 6
WEEK_OF_MONTH: 2
DATE: 6
DAY_OF_MONTH: 6
DAY_OF_YEAR: 37
DAY_OF_WEEK: 5
DAY_OF_WEEK_IN_MONTH: 1
AM_PM: 1
HOUR: 5
HOUR_OF_DAY: 17
MINUTE: 33
SECOND: 40
MILLISECOND: 692

Manipulating the Calendar dates:

         If you want to add or substract the days from the existing calendar then,

                       Calendar cal = Calendar.getInstance();
                       System.out.println("The current date is: "+cal.getTime());
                       cal.add(Calendar.DATE, 2);                                  //added two days
                       System.out.println("After adding 2 days: "+cal.getTime());
                       cal.add(Calendar.Date,-8);
                       System.out.println("After substracting 8 days: "+cal.getTime());

output--
                      The current date is: Wed Aug 27 15:00:56 IST 2014
                      After adding 2 days: Fri Aug 29 15:00:56 IST 2014
                      After substracting 8 days: Thu Aug 21 15:28:50 IST 2014

        If you want to add or substract the month from the existing calendar then,

                      Calendar cal = Calendar.getInstance();
                      System.out.println("The current date is: "+cal.getTime());
                      cal.add(Calendar.MONTH, 4);                //After 4 months
                      System.out.println("After 4 months : "+cal.getTime());
                      cal.add(Calendar.MONTH, -6)                //6 months ago
                      System.out.println("6 months ago : "+cal.getTime());

output-
                     The current date is: Wed Aug 27 15:00:56 IST 2014
                    After 4 months : Sat Dec 27 15:37:02 IST 2014
                    6 months ago :Fri Jun 27 15:37:02 IST 2014

Samething follow for other calendar fields like year,day,day of week and so on.

Converting Date Object to Calendar Object :-

                 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                 String dateStr = "10/10/2014";
                 Date date = sf.parse(dateStr);
                 Calendar cal = Calendar.getInstance();
                 cal.setTime(date);
                 System.out.println(cal.getTime());

Setting the Calendar fields:-

                  Calendar cal = Calendar.getInstance();
                  System.out.println("The current date is: "cal.getTime());
                  cal.set(Calendar.MINUTE, 25);
                  cal.set(Calendar.DAY_OF_MONTH, 10);
                  cal.set(Calendar.YEAR, 2013);
                  System.out.println("After setting: "cal.getTime());
output-
                 The current date is: Wed Aug 27 16:04:21 IST 2014
                 After setting: Sat Aug 10 16:25:21 IST 2013

 

java.util.GregorianCalendar:-


                   The calendar that we use today, called Gregorian calendar, came into effect in October 15, 1582 in some countries and later in other countries. It replaces the Julian calendar. 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian). The only difference between the Gregorian and the Julian calendar is the "leap-year rule". In Julian calendar, every four years is a leap year. In Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible by 400 (removing 3 leap years (or 3 days) for every 400 years). Furthermore, Julian calendar considers the first day of the year as march 25th, instead of January 1st.

                    java.util.Calendar is an abstract class. Calendar.getInstance() returns an implementation class java.util.GregorianCalendar (except locales of "th" and "jp"). In Java, this GregorianCalendar handles both the Gregorian calendar as well as the Julian calendar, including the cut over.



Related Posts:-- 
1) Exception Handling Interview questions and answers
2) String Interview Questions and Answers
3) Spring @Qualifier Annotation with example    
4) Spring MVC with Hibernate CRUD Example
5) Java Program to Count Occurrence of Word in a Sentence     

Sunday, 20 July 2014

What are the Implicit Objects in JSP?

             JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.

    JSP supports nine Implicit Objects which are listed below:

 1) request :
            This is the HttpServletRequest object associated with the request.

 2) response :
           This is the HttpServletResponse object associated with the response to the client.

 3) out :
         This is the PrintWriter object used to write any data to buffer.

 4) session :
         This is the HttpSession object associated with the request.

  5) application :
         This is the ServletContext object associated with application context.

  6) config :
         This is the ServletConfig object associated with the page.

  7) pageContext :
        This encapsulates use of server-specific features like higher performance JspWriters.

  8) page :
       This is simply a synonym for this, and is used to call the methods defined by the
      translated servlet  class.

  9) Exception :
         The Exception object allows the exception data to be accessed by designated JSP.

Sunday, 13 July 2014

Difference between HashMap and Hashtable in collection in Java



There are several differences between HashMap and Hashtable in Java:
  1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).    
  2.  HashMap does not guarantee that the order of the map will remain constant over time.
  3. HashMap is non synchronized whereas Hashtable is synchronized.
  4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.
Note on Some Important Terms
  1. Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
  2. Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
  3. Structurally modification means deleting or inserting element which could effectively change the structure of map.
HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

            Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface, as discussed later in this section. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; Hashtable did not. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key, because the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the interface's consistency — containsValue parallels containsKey.


Related Post:
 1) Collection Interview Qusetions and Answers
 2) How HashMap works internally in java?

Saturday, 28 June 2014

What is Dependency Injection in Spring ? Explain DI types and advantages with examples

             Dependency Injection (DI) in Spring is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. It allows objects to be loosely coupled by injecting the dependencies from the outside rather than creating them internally.

            The basic concept of the Inversion of Control pattern  is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. In a typical IOC scenario, the container creates all the objects, wires them together by setting the necessary properties, and determines when methods will be invoked.  
    
        There are two types of DI,
  • Setter Injection
  • Constructor Injection                                                                 

Setter Injection:-

    Spring framework will inject the dependency via a setter method.
XML configuration for setter Dependency Injection is below.

  <bean id="classBean" class="com.adnjava.ClassBean">
     <!-- setter injection using the nested <ref/> element -->
       <property name="studentBean"><ref bean="studentBean"/></property>
  </bean>
  <bean id="studentBean" class="com.adnjava.StudentBean"/> 

         The ClassBean java POJO class is as below,

 package com.adnjava;

  public class ClassBean {

       private StudentBean studentBean;

       public void setStudentBean(StudentBean studentBean){
           this.studentBean=studentBean;
       }

       public void getStudentBean(){
             return studentBean;
       }
 }

 Constructor Injection:-

          Here Spring uses the  Constructor and the arguments passed to it to determine the dependency. Rest all is same as setter injection.
     
      XML configuration for
Constructor Dependency Injection is below.


  <bean id="classBean" class="com.adnjava.ClassBean">
       <constructor-arg><ref bean="studentBean"/></constructor-arg>
      <!--OR you can use <constructor-arg ref="yetAnotherBean"/>-->
  </bean>
  <bean id="studentBean" class="com.adnjava.StudentBean"/>  

         The ClassBean java POJO class is as below,

 package com.adnjava;
  
  public class ClassBean {

         private StudentBean studentBean;

         public ClassBean(StudentBean studentBean){
              this.studentBean=studentBean;
         }

         public void getStudentBean(){
               return studentBean;
         }
  }


              Interface Injection:

             This is not implemented in Spring currently, but by Avalon. It’s a different type of DI that involves mapping items to inject to specific interfaces.

Advantages Of Dependency Injection:

  • Loosely couple code
  • Separation of responsibility
  • Configuration and code is separate.
  • Using configuration, you can provide implemented code  without changing the dependent code.
  • Testing can be performed using mock objects.

Related Post:--
Spring MVC workflow with example  
Spring MVC with Hibernate CRUD Example  
Spring Annotations  

Friday, 27 June 2014

Bean Lifecycle in Spring Framework

            The Spring Framework is based on the Inversion of Control (IoC) principle, which is why it is often referred to as an IoC container. Spring beans reside within the IoC container and are managed by it. A Spring bean is simply a Plain Old Java Object (POJO) that is instantiated, configured, and managed by the Spring container.

The following steps explain the lifecycle of a Spring bean within the container.
  1. The container looks for the bean definition in the configuration file (e.g., beans.xml).
  2. Using the Reflection API, the container creates the bean object. If any properties are defined in the bean definition, the container also injects and initializes those properties.
  3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
  4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
  5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called before the properties for the Bean are set.
  6. If an init() method is specified for the bean, it will be called.
  7. If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.
  8. If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.

Sunday, 22 June 2014

Why Doesn't the Map Interface Extend the Collection Interface in Java?

 The main reason is that Map and Collection represent two different data models.
  • A Collection represents a group of individual elements.

  • A Map represents key-value pairs (mappings).

Because of this fundamental difference, the Map interface does not extend the Collection interface.

Why doesn't Map extend Collection?

1. A Collection stores only elements

A Collection interface (implemented by List, Set, and Queue) stores a group of individual objects.

List<String> names = List.of("John", "David", "Smith");

Here, each item is a single element.

2. A Map stores key-value pairs

A Map stores data in the form of keys and values.

Map<Integer, String> employees = new HashMap<>();

employees.put(101, "John");
employees.put(102, "David");
employees.put(103, "Smith");

Each entry consists of a key and its corresponding value.

3. Duplicate handling is different

Collection

  • List allows duplicate elements.

  • Set does not allow duplicate elements.

Map

  • Keys must be unique.

  • Values can be duplicated.

Map<Integer, String> map = new HashMap<>();

map.put(1, "Java");
map.put(2, "Java");   // Allowed (duplicate value)
map.put(1, "Spring"); // Replaces the previous value for key 1


4. Their operations are completely different

Collection methods work with elements.

add(E e)
remove(Object o)
contains(Object o)

Map methods work with key-value mappings.

put(K key, V value)
get(Object key)
remove(Object key)
containsKey(Object key)
containsValue(Object value)
Because their APIs are fundamentally different, inheritance would not make sense.

5. A Map can expose collections when needed

Although a Map is not a Collection, it provides methods that return collections of its contents.

map.keySet();      // Returns Set<K>
map.values();      // Returns Collection<V>
map.entrySet();    // Returns Set<Map.Entry<K, V>>

Example:

Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Spring");

Set<Integer> keys = map.keySet();
Collection<String> values = map.values();
Set<Map.Entry<Integer, String>> entries = map.entrySet();

Collection vs Map

CollectionMap
Stores individual elementsStores key-value pairs
Represents a group of objectsRepresents mappings between keys and values
Uses methods like add() and remove()Uses methods like put() and get()
Implemented by List, Set, and QueueImplemented by HashMap, TreeMap, LinkedHashMap, etc.
Elements may or may not be unique (depending on implementation)Keys must be unique; values may be duplicated



Related Posts:--
1) How HashMap works internally in Java?
2) Internal Implementation of TreeMap in Java
3) Internal implementation of ArrayList in Java
4) Collection Interview Questions and Answers in Java
5) Internal Implementation of LinkedList in Java
6) Collection Hierarchy in Java

Saturday, 21 June 2014

Singleton Design Pattern in Java with Examples

         In this post, we will learn the principles of the Singleton design pattern, explore different ways to implement it, and discuss some best practices for using it.

       The Singleton design pattern restricts the instantiation of a class, ensuring that only one instance of the class exists within the Java Virtual Machine (JVM). A Singleton class provides a global access point through which the single instance of the class can be accessed.

       The Singleton design pattern is commonly used for logging, database driver objects, caching, configuration management, and thread pools. It is also used by several other design patterns, such as Abstract Factory, Builder, Prototype, and Facade.

To implement the Singleton Design Pattern, the following principles should be followed:

  1. Private constructor – Prevents other classes from creating new instances of the class.

  2. Private static instance reference – Holds the single instance of the class and prevents external modification.

  3. Public static method – Provides a global access point to retrieve the Singleton instance.


Below are the different approaches for implementing the Singleton design pattern.

  • Eager initialization

            In eager initialization, the Singleton instance is created when the class is loaded into memory. This is the simplest way to implement the Singleton design pattern. However, it has one drawback: the instance is created even if the client application never uses it, which may result in unnecessary memory usage.
Below is the implementation of the Singleton class using eager initialization.     

  public class EagerInitializer{
        
        private static final EagerInitializer instance = new EagerInitializer();

        //private constructor to avoid client applications to use constructor.
        private  EagerInitializer(){
        }
        public static EagerInitializer getInstance(){
              return instance;
        }
  }

           If your Singleton class does not consume many resources, eager initialization is a suitable approach. However, in most real-world scenarios, Singleton classes are used to manage resource-intensive objects such as file systems, database connections, or configuration managers. In such cases, it is better to delay the creation of the instance until the client invokes the getInstance() method.

Another limitation of eager initialization is that it does not provide flexibility for handling exceptions that may occur during instance creation.

  • Static block initialization

            The static block initialization approach is similar to eager initialization, except that the Singleton instance is created inside a static initialization block. This approach provides the flexibility to handle exceptions that may occur during instance creation.

 public class StaticInitializer {
        private static StaticInitializer instance ;
        //private constructor to avoid client applications to use constructor.
        private  StaticInitializer() {
        }
        static {
             try {
                 instance = new StaticInitializer();
             } catch(Exception e) {
                     throw new RuntimeException("Exception in static block");
             }
        }
        public static StaticInitializer getInstance() {
               return instance;
        }
 }

          Both eager initialization and static block initialization create the Singleton instance before it is actually needed. In many cases, this is not considered a best practice because the instance is created even if it is never used. In the following sections, we'll explore how to implement a Singleton class that supports lazy initialization.

  • Lazy Initialization

            The lazy initialization approach creates the Singleton instance only when it is requested through the global access method (getInstance()). This ensures that the instance is created only when it is actually needed.

Below is a sample implementation of the Singleton design pattern using the lazy initialization approach.


  public class LazyInitializer{

        private static LazyInitializer instance;

        //private constructor to avoid client applications to use constructor.
        private  LazyInitializer(){
        }
        public static LazyInitializer getInstance(){
              if(instance == null){
                       instance = new LazyInitializer();
              }
              return instance;
        }
  }

        The above implementation works well in a single-threaded environment. However, in a multithreaded environment, it can cause issues if multiple threads enter the if block simultaneously. In such a scenario, multiple instances of the Singleton class may be created, violating the Singleton design pattern and causing different threads to obtain different instances.

In the next section, we'll explore different approaches for implementing a thread-safe Singleton class.

  • Thread Safe Singleton

       The simplest way to make a Singleton class thread-safe is to synchronize the global access method (getInstance()). This ensures that only one thread can execute the method at a time, preventing multiple instances from being created concurrently.

A typical implementation of this approach is shown below.


  public class ThreadSafe{

        private static ThreadSafe instance ;
                        
        //private constructor to avoid client applications to use constructor.
        private  ThreadSafe(){
        }

        public static synchronized ThreadSafe getInstance(){
               if(instance == null){
                     instance = new ThreadSafe();
               }
               return instance;
         }
  }

         The above implementation is thread-safe and works correctly. However, it can reduce performance because every call to the getInstance() method requires synchronization, even after the Singleton instance has already been created. In practice, synchronization is only needed when the instance is created for the first time.

To avoid this unnecessary synchronization overhead, the Double-Checked Locking pattern is used. In this approach, the instance is checked before entering the synchronized block and checked again inside the synchronized block. This ensures that synchronization occurs only during the initial creation of the Singleton instance while maintaining thread safety.

The following code snippet demonstrates the Double-Checked Locking implementation.


                 public static ThreadSafe getInstance(){
                          if(instance == null){
                                    synchonized(ThreadSafe.class){
                                             if(instance == null ){
                                                      instance = new ThreadSafe();
                                             }
                                     }
                           }
                           return instance;
                 }


JDBC Example using Singleton Design pattern:--

          A common real-world example of the Singleton design pattern is a ConnectionFactory class. This class is implemented as a Singleton and contains the database connection configuration along with methods for creating database connections.

The reason for making the ConnectionFactory class a Singleton is that only one instance of the factory is required throughout the application. This single factory instance can then be used to create multiple database Connection objects whenever needed—one factory, many connections.


package com.adnjavainterview;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {
           //static reference to itself
         private static ConnectionFactory instance = new ConnectionFactory();
         public static final String URL = "jdbc:mysql://localhost/jdbcdb";
         public static final String USER = "YOUR_DATABASE_USERNAME";
         public static final String PASSWORD = " YOUR_DATABASE_PASSWORD";
         public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
              //private constructor
         private ConnectionFactory() {
                 try {
                        Class.forName(DRIVER_CLASS);
                  }
                  catch (ClassNotFoundException e) {
                        e.printStackTrace();
                  }
         }
    
         private Connection createConnection() {
                   Connection connection = null;
                   try {
                          connection = DriverManager.getConnection(URL, USER, PASSWORD);
                   }
                   catch (SQLException e) {
                           System.out.println("ERROR: Unable to Connect to Database.");
                   }
                   return connection;
         } 
    
         public static Connection getConnection() {
                 return instance.createConnection();
         }
 }

Thank you for visiting blog..

Related Post:--