Search This Blog

Sunday 5 March 2017

The Set Interface

The Set Interface
A Set is a Collection that cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are not added. 
The Java Platform contain three general purpose implementations of Set
·        HashSet 
·        TreeSet
·        LinkedHashSet

HashSet stores its elements in a hash table, and performance wise it is the best implementation. It makes no guarantees concerning the order of iteration.

TreeSet stores its elements in a tree structure, and the elements are orders based on their values. Its performance is slower than HashSet. 

LinkedHashSet is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the Set. 

Set Interface Basic Operations

·        The add() method adds the specified element to the Set if it is not already present.
·        The remove() method removes the specified element from the Set if it is present.
·        The size() operation returns the number of elements in the Set. The isEmpty() method is used to check if this set contains no elements
·        The iterator() method returns an Iterator over the Set.

Set Interface Bulk Operations

Bulk operations are particularly well suited to Sets; when applied, they perform standard set-algebraic operations. Suppose s1 and s2 are sets. Here's what bulk operations do:
  • s1.containsAll(s2) — returns true if s2 is a subset of s1.
  • s1.addAll(s2) — transforms s1 into the union of s1 and s2.
  • s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2.
  • s1.removeAll(s2) — transforms s1 into the set difference of s1 and s2.
Example of Set using HashSet and SortedSet

import java.util.*;
public class SetDemo {

  public static void main(String args[]) {
      int numbers[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
            set.add(numbers[i]);
         }
        
         System.out.println("Natural Set : ");
         System.out.println(set);

         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("Sorted Set : ");
         System.out.println(sortedSet);
      }
      catch(Exception e) {}
   }
}

Thursday 2 March 2017

Collection Interfaces

Collection Interfaces
The core collection interfaces encapsulate different types of collections. These interfaces allow collections to be manipulated independently of the details of their representation. Core collection interfaces are the foundation of the Java Collections Framework.

The following describes the core collection interfaces:
  • Collection — Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform provides implementation of more specific sub interfaces like Set and List and doesn't provide any direct implementations of Collection interface.
  • Set — Set is a collection that cannot contain duplicate elements.
  • List — List is an ordered collection. Lists can contain duplicate elements.
  • Queue — Queue is a collection used to hold multiple elements prior to processing.
  • Deque — Deque is a collection used to hold multiple elements prior to processing. In a deque all new elements can be inserted, retrieved and removed at both ends.
  • Map — Map is an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.
  • SortedSet — SortedSet is a Set that maintains its elements in ascending order.
  • SortedMap — SortedMap is a Map that maintains its mappings in ascending key order.
The Collection interface contains methods that perform basic operations, such as 
·        int size()
·        boolean isEmpty()
·        boolean contains(Object element)
·        boolean add(E element)
·        boolean remove(Object element)
·        Iterator<E> iterator()

It also contains methods that operate on entire collections
·        boolean containsAll(Collection<?> c)
·        boolean addAll(Collection<? extends E> c)
·        boolean removeAll(Collection<?> c)
·        boolean retainAll(Collection<?> c)
·        void clear().
Traversing Collections
There are three ways to traverse collections
1.     using aggregate operations
2.     using the for-each construct
3.     using Iterators

Aggregate Operations
In JDK 8 and later, the preferred method of iterating over a collection is to obtain a stream and perform aggregate operations on it.
Aggregate operations are often used in conjunction with lambda expressions to make programming more expressive, using less lines of code.
The following code sequentially iterates through a collection of Employees and prints out the Name of Employee of HR department
myEmployeeCollection.stream()
.filter(e -> e.getDepartment() == “HR”)
.forEach(e -> System.out.println(e.getName()));

for-each Construct
The for-each construct allows you to concisely traverse a collection or array using a for loop.
The following code uses the for-each construct to print out each element of a collection on a separate line.
for (Object o : collection)
    System.out.println(o);
           
Iterators
An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively.
You get an Iterator for a collection by calling its iterator method. The following is the Iterator interface.
public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional
}
The hasNext method returns true if the iteration has more elements, and the next method returns the next element in the iteration.

The remove method removes the last element that was returned by next from the underlying Collection. 

Collection Interfaces
Collection Interfaces

Wednesday 1 March 2017

Collections in Java

Collections in Java


A collection is an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:
  • Interfaces: Interfaces allow collections to be manipulated independently of the details of their representation.
  • Implementations: These are the concrete implementations of the collection interfaces. They represent reusable data structures.
  • Algorithms: Are the methods that perform useful operations, for example searching and sorting, on objects that implement collection interfaces. The algorithms are polymorphic: that is, the same method can be used on many different implementations the collection interface.

Benefits of the Java Collections Framework


  • Reduces programming effort
  • Increases program speed and quality
  • Interoperability among unrelated APIs.
  • Reduces effort to learn and to use new APIs
  • Reduces effort to design new APIs
  • Increases software reuse

Sunday 26 February 2017

Exceptions in Java

Exceptions in Java

 An exception in Java is an event, which occurs during the execution of a program that disrupts the normal flow of the program.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, contains information about the error, including exception type and the state of the program when the error occurred and is called an exception object. Creating an exception object and handing it to the runtime system is called throwing an exception.
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler.
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
  • A user has entered an invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.


The Three Kinds of Exceptions
  • Checked exceptions − Checked exception is an exception that occurs at the compile time, and are also called as compile time exceptions. As these exceptions occur at the time of compilation of code, the programmer should take care to handle these exceptions.
  • Unchecked exceptions − Unchecked exception is an exception that occurs at the time of execution. As they occur at time of execution they are also called as Runtime Exceptions. These type of exception include programming bugs, such as logic errors or improper use of an API.
  • Errors − Errors are not exceptions, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in the code because you can rarely do anything about an error. For example, out of memory error.


Catching and Handling Exceptions
The exception mechanism in Java uses three exception handler components — the trycatch, and finally blocks.

The try Block
The try block is used to enclose the code which might throw an exception.
try {
    code
}
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it.

The Catch Block
We associate exception handlers with a try block by providing one or more catch blocks directly after the try block.
try {
//some code that throws Exception
} catch (ExceptionType name) {
// code that is invoked once the exception is thrown
} catch (ExceptionType name) {
// code that is invoked once the exception is thrown
}
Each catch block is an exception handler that handles the type of exception indicated by its argument.
The catch block contains code that is executed if and when the exception handler is invoked.

The finally Block
The finally block always executes when the try block exits.
This ensures that the finally block is executed even if an unexpected exception occurs.
finally is useful for more than just exception handling — it allows the programmer to write the clean-up code , even if there are no exceptions.
 finally{
 // code for clean up
 }

Advantages of Exceptions

  • Separating Error-Handling Code from "Regular" Code.
  • Propagating Errors Up the Call Stack.
  • Grouping and Differentiating Error Types
Exceptions in Java

Exceptions in Java




Friday 24 February 2017

Spring - Bean

Spring - Bean Definition

The objects that form the backbone of application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled and managed by a Spring IoC container. These beans are created with the configuration metadata that we supply to the container.
The bean definition contains the information called configuration metadata which is needed for the container to know the followings:
·        How to create a bean
·        Bean's lifecycle details
·        Bean's dependencies
The above configuration metadata translates into a set of the following properties that make up the bean definition.
class
The class attribute is mandatory. The class attribute specifies the class of the bean to be constructed

id and name
Every bean has one or more ids called identifiers, or names. These ids must be unique within the BeanFactory or ApplicationContext the bean is hosted in. In an XmlBeanFactory, you use the id or name attributes to specify the bean id.

singleton or prototype
Beans are defined to be deployed in either singleton or non-singleton mode. When a bean is a singleton, only one shared instance of the bean will be managed and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned.
The non-singleton or prototype mode of a bean deployment results in the creation of a new bean instance every time a request for that specific bean is done. This is ideal for situations where for example each user needs an independent user object.

By default beans are deployed in singleton mode. By changing the type to prototype, each request for a bean will create a new bean object.
In the below example, two beans are declared of which one is defined as a singleton, and the other one is a non-singleton (prototype). 
protoBean is created each and every time a client asks the BeanFactory for this bean, while singleBean is only created once; a reference to the exact same instance is returned on each request for this bean.

Spring - Bean
constructor arguments

This is used to inject the dependencies. Beans define their dependencies only through constructor arguments, arguments to a factory method, or properties which are set on the object instance after it has been constructed.  The container then inject those dependencies when it creates the bean.
Inversion of Control/Dependency Injection exists in two major variants:
  • setter-based dependency injection is realized by calling setters on the beans after invoking a no-argument constructor or no-argument static factory method to instantiate the bean.
  • constructor-based dependency injection is realized by invoking a constructor with a number of arguments, each representing a collaborator or property.

bean properties
Bean properties and constructor arguments can be defined as either references to other managed beans or values defined inline. The XmlBeanFactory supports a number of sub-element types within its property and constructor-arg elements for this purpose.  This is used to inject the dependencies.


autowiring mode

It is possible to automatically let Spring framework resolve dependencies for the bean by inspecting contents of the BeanFactory. This is kown as Autowiring.  A BeanFactory is able to autowire relationships between collaborating beans.
The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans won't be autowired.
Using autowiring, it is possible to reduce or eliminate the need to specify properties or constructor arguments, saving a significant amount of typing. In an XmlBeanFactory, the autowire mode for a bean definition is specified by using the autowire attribute of the bean element.
 Autowiring modes