Friday, July 6, 2012

SuppressWarnings in Java

Today I had to spent some time on writing SuppressWarnings syntax for multiple values. So thought of posting it ...


It can be written in following ways :
  1. @SuppressWarnings("deprecation")
  2. @SuppressWarnings({ "unchecked", "unused" })
  3. @SuppressWarnings(value = {"unchecked", "unused"})

Friday, June 8, 2012

Regex for Password validation

Regex
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$


Explanation:
^                 # start-of-string
(?=.*[0-9])       # a digit must occur at least once
(?=.*[a-z])       # a lower case letter must occur at least once
(?=.*[A-Z])       # an upper case letter must occur at least once
(?=.*[@#$%^&+=])  # a special character must occur at least once
(?=\S+$)          # no whitespace allowed in the entire string
.{8,}             # anything, at least eight places though
$                 # end-of-string
It's easy to add, modify or remove individual rules, since every rule is an independent "module".

The (?=.*[xyz]) construct eats the entire string (.*) and backtracks to the first occurrence where [xyz] can match. It succeeds if [xyz] is found, it fails otherwise.

The alternative would be using a reluctant qualifier: (?=.*?[xyz]). For a password check, this will hardly make any difference, for much longer strings it could be the more efficient variant.

The most efficient variant (but hardest to read and maintain, therefore the most error-prone) would be (?=[^xyz]*[xyz]), of course. For a regex of this length and for this purpose, I would dis-recommend doing it that way, as it has no real benefits.

Source : http://stackoverflow.com/questions/3802192/regexp-java-for-password-validation

Monday, March 12, 2012

Eclipse Shortcuts

  1. Ctrl+Shift+O – auto repair imports
  2. Ctrl+1 – quick assist
  3. Ctrl+Shift+G – search references
  4. Ctrl+G – search implementations
  5. Alt+Shirt+R – rename refactoring
  6. ctrl + T : display hierarchy of the selected type in a popup (better than F4)
  7. Ctrl + / or Ctrl+Shift+C or Ctrl+7  - Comments a block of code
  8. Ctrl Shift + / : comment block of code
  9. Alt + Shift + J : Add author for JavaDoc 

Thursday, February 9, 2012

Regular Expression to remove special characters from a String

This Regular expression will remove all special character from String except underscore(_) and numbers and this formatted String can be used in creating table in database where special characters are not allowed and other places as well as per need.

String rawInput = " Company (Details_)  India?]$$$";
String regEx = "[^A-Za-z0-9_]+";
String expctedOutput = rawInput.replaceAll(regEx, "");
System.out.println(expctedOutput);
  Output = CompanyDetails_India



Monday, January 23, 2012

Iterating Map in a better way

Generally people write code in this way to iterate Map ...

Set set = map.keySet();
for (Integer key : set) {
      System.out.println("Key = " + key + " & Value = " + map.get(key));
} 

In practice it is pretty slow and inefficient as getting values by a key might be time consuming. This method should be avoided.

A better way - A map is a series of Map.Entry objects. It's better to get a reference to Map.Entry and then iterate instead of getting all the keys and making the Map object do the work of fetching the value each time.

for (Map.Entry entry : map.entrySet()) {
     System.out.println("Key = " + entry.getKey() + " & Value = "+ entry.getValue());
}

Also some more good  example @ http://www.sergiy.ca/how-to-iterate-over-a-map-in-java/

References - http://jtoee.blogspot.com/2008/05/better-way-to-iterate-java-maps.html

Sunday, August 22, 2010

Java Collection Framework - Overview

Core Collection Interfaces
The core interfaces that define common functionality and allow collections to be manipulated independent of their implementation.

The 6 core Interfaces used in the Collection framework are:
    1. Collection
    2. Set
    3. List
    4. Iterator (Not a part of the Collections Framework)
    5. SortedSet
    6. Map
    7. SortedMap
    Note: Collection and Map are the two top-level interfaces.

    Collection Interface
    Concrete Classes
    The concrete classes that are specific implementations of the core interfaces, providing data structures that a Java program can use.



    Collection Overview
    Java ArrayList

        * Resizable-array implementation of the List interface. A java ArrayList is used to store an "ordered" group of elements where duplicates are allowed.
        * Implements all optional list operations, and permits all elements, including null.
        * This class is similar to Vector, except that it is unsynchronized.        
        * The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. ArrayList's give great performance on get() and set() methods, but do not perform well on 
           add() and remove() methods when compared to a LinkedList.
        * An ArrayList capacity is the size of the array used to store the elements in the list. As elements are added to an ArrayList, its capacity grows automatically. It is an Array based 
           implementation where elements of the List can be accessed directly through get() method.

    To prevent unsynchronized access to the list: List list = Collections.synchronizedList(new ArrayList(...));

    Java Linked List
        * A LinkedList is used to store an "ordered" group of elements where duplicates are allowed.
        * A LinkedList is based on a double linked list where elements of the List are typically accessed through add() and remove() methods.
    Java Vector
    public class Vector extends AbstractList implements List, RandomAccess, Cloneable, Serializable 
        * The Vector class implements a growable array of objects where the size of the vector can grow or shrink as needed dynamically.
        * Like an array, it contains components that can be accessed using an integer index.
        * An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
    Map Interface




    Map Overview


    Saturday, August 21, 2010

    OOPS Concepts - Inheritance

    Inheritance
    It is the inclusion of behavior (i.e. methods) and state (i.e. variables) of a base class in a derived class so that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for code reuse. Any shared piece of business logic can be moved from the derived class into the base class as part of refactoring process to improve maintainability of your code by avoiding code duplication. The existing class is called the superclass and the derived class is called the subclass. Inheritance can also be defined as the process whereby one object acquires characteristics from one or more other objects the same way children acquire characteristics from their parents.

    There are two types of inheritances:
    1. Implementation inheritance (aka class inheritance):
      You can extend an application’s functionality by reusing functionality in the parent class by inheriting all or some of the operations already implemented. In Java, you can only inherit from one superclass. Implementation inheritance promotes reusability but improper use of class inheritance can bcause programming nightmares by breaking encapsulation and making future changes a problem. With implementation inheritance, the subclass becomes tightly coupled with the superclass. This will make the design fragile because if you want to change the superclass, you must know all the details of the subclasses to avoid breaking them. So when using implementation inheritance, make sure that the subclasses depend only on the behavior of the superclass, not on the actual implementation. For example in the above diagram, the subclasses should only be concerned about the behavior known as area() but not how it is implemented.
    2. Interface inheritance (aka type inheritance):This is also known as subtyping. Interfaces provide a mechanism for specifying a relationship between otherwise unrelated classes, typically by specifying a set of common methods each implementing class must contain. Interface inheritance promotes the design concept of program to interfaces not to implementations. This also reduces the coupling or implementation dependencies between systems. In Java, you can implement any number of interfaces. This is more flexible than implementation inheritance because it won’t lock you into specific implementations which make subclasses difficult to maintain. So care should be taken not to break the implementing classes by modifying the interfaces.
    Which one to use? 
    Prefer interface inheritance to implementation inheritance because it promotes the design concept of coding to an interface and reduces coupling. Interface inheritance can achieve code reuse with the help of object composition. If you look at Gang of Four (GoF) design patterns, you can see that it favors interface inheritance to implementation inheritance.

    Interview Questions

    1. Using == and equals()When you really need to know if two references are identical, use ==. But when you need to know if the objects themselves (not the references) are equal, use the equals().