Thursday, October 13, 2016

matcher

Subexpression
Matches
^
Matches beginning of line.
$
Matches end of line.
.
Matches any single character except newline. Using m option allows it to match newline as well.
[...]
Matches any single character in brackets.
[^...]
Matches any single character not in brackets
\A
Beginning of entire string
\z
End of entire string
\Z
End of entire string except allowable final line terminator.
re*
Matches 0 or more occurrences of preceding expression.
re+
Matches 1 or more of the previous thing
re?
Matches 0 or 1 occurrence of preceding expression.
re{ n}
Matches exactly n number of occurrences of preceding expression.
re{ n,}
Matches n or more occurrences of preceding expression.
re{ n, m}
Matches at least n and at most m occurrences of preceding expression.
a| b
Matches either a or b.
(re)
Groups regular expressions and remembers matched text.
(?: re)
Groups regular expressions without remembering matched text.
(?> re)
Matches independent pattern without backtracking.
\w
Matches word characters.
\W
Matches nonword characters.
\s
Matches whitespace. Equivalent to [\t\n\r\f].
\S
Matches nonwhitespace.
\d
Matches digits. Equivalent to [0-9].
\D
Matches nondigits.
\A
Matches beginning of string.
\Z
Matches end of string. If a newline exists, it matches just before newline.
\z
Matches end of string.
\G
Matches point where last match finished.
\n
Back-reference to capture group number "n"
\b
Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.
\B
Matches nonword boundaries.
\n, \t, etc.
Matches newlines, carriage returns, tabs, etc.
\Q
Escape (quote) all characters up to \E
\E
Ends quoting begun with \Q
No.
Character Class
Description
1
[abc]
a, b, or c (simple class)
2
[^abc]
Any character except a, b, or c (negation)
3
[a-zA-Z]
a through z or A through Z, inclusive (range)
4
[a-d[m-p]]
a through d, or m through p: [a-dm-p] (union)
5
[a-z&&[def]]
d, e, or f (intersection)
6
[a-z&&[^bc]]
a through z, except for b and c: [ad-z] (subtraction)
7
[a-z&&[^m-p]]
a through z, and not m through p: [a-lq-z](subtraction)


enum

Enumerations was added to Java language in JDK5.
 Enumeration means a list of named constant.
 In Java, enumeration defines a class type.
An Enumeration can have constructors, methods and instance
 variables.
It is created using enum keyword.
Each enumeration constant is public, static and final by
 default.
Even though enumeration defines a class type and have
constructors, you do not instantiate an enum using new.
Enumeration variables are used and declared in much a same way
as you do a primitive variable.

How to Define and Use an Enumeration

An enumeration can be defined simply by creating a list of
 enum variable.
Let us take an example for list of Subject variable,
 with different subjects in the list.
enum Subject           //Enumeration defined
{
 Java, Cpp, C, Dbms
}

enum WeekDays
{ sun, mon, tues, wed, thurs, fri, sat }

class Test
{
 public static void main(String args[])
 {
  WeekDays wk;
  wk = WeekDays.sun;
  System.out.println("Today is "+wk);
 }
}

program2
enum Student
{
 John(11), Bella(10), Sam(13), Viraaj(9);
 private int age;                   //age of students
 int getage { return age; }
 public Student(int age)
 {
  this.age= age;
 }
}

class EnumDemo
{
 public static void main( String args[] )
 {
  Student S;
  System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ "years");
 }
}

Thursday, October 6, 2016

Java tips


1. Prefer returning Empty Collections instead of Null

If a program is returning a collection which does not have any value, make sure an Empty collection is returned rather than Null elements. This saves a lot of “if else” testing on Null Elements.
1public class getLocationName {
2    return (null==cityName ? "": cityName);
3}

2. Use Strings carefully

If two Strings are concatenated using “+” operator in a “for” loop, then it creates a new String Object, every time. This causes wastage of memory and increases performance time. Also, while instantiating a String Object, constructors should be avoided and instantiation should happen directly. For example:
1//Slower Instantiation
2String bad = new String("Yet another string object");
3      
4//Faster Instantiation
5String good = "Yet another string object"

3. Avoid unnecessary Objects

One of the most expensive operations (in terms of Memory Utilization) in Java is Object Creation. Thus it is recommended that Objects should only be created or initialized if necessary. Following code gives an example:
01import java.util.ArrayList;
02import java.util.List;
03 
04public class Employees {
05 
06    private List Employees;
07 
08    public List getEmployees() {
09 
10        //initialize only when required
11        if(null == Employees) {
12            Employees = new ArrayList();
13        }
14        return Employees;
15    }
16}

4. Dilemma between Array and ArrayList

Developers often find it difficult to decide if they should go for Array type data structure of ArrayList type. They both have their strengths and weaknesses. The choice really depends on the requirements.
01import java.util.ArrayList;
02 
03public class arrayVsArrayList {
04 
05    public static void main(String[] args) {
06        int[] myArray = new int[6];
07        myArray[7]= 10// ArraysOutOfBoundException
08 
09        //Declaration of ArrayList. Add and Remove of elements is easy.
10        ArrayList<Integer> myArrayList = new ArrayList<>();
11        myArrayList.add(1);
12        myArrayList.add(2);
13        myArrayList.add(3);
14        myArrayList.add(4);
15        myArrayList.add(5);
16        myArrayList.remove(0);
17         
18        for(int i = 0; i < myArrayList.size(); i++) {
19        System.out.println("Element: " + myArrayList.get(i));
20        }
21         
22        //Multi-dimensional Array
23        int[][][] multiArray = new int [3][3][3];
24    }
25}
  1. Arrays have fixed size but ArrayLists have variable sizes. Since the size of Array is fixed, the memory gets allocated at the time of declaration of Array type variable. Hence, Arrays are very fast. On the other hand, if we are not aware of the size of the data, then ArrayList is More data will lead to ArrayOutOfBoundException and less data will cause wastage of storage space.
  2. It is much easier to Add or Remove elements from ArrayList than Array
  3. Array can be multi-dimensional but ArrayList can be only one dimension.

5. When Finally does not get executed with Try

Consider following code snippet:
01public class shutDownHooksDemo {
02    public static void main(String[] args) {
03        for(int i=0;i<5;i++)
04        {
05            try {
06                if(i==4) {
07                    System.out.println("Inside Try Block.Exiting without executing Finally block.");
08                    System.exit(0);
09                }
10            }
11            finally {
12                System.out.println("Inside Finally Block.");
13            }
14        }
15    }
16}
From the program, it looks like “println” inside finally block will be executed 5 times. But if the program is executed, the user will find that finally block is called only 4 times. In the fifth iteration, exit function is called and finally never gets called the fifth time. The reason is- System.exit halts execution of all the running threads including the current one. Even finally block does not get executed after try when exit is executed.
When System.exit is called, JVM performs two cleanup tasks before shut down:
First, it executes all the shutdown hooks which have been registered with Runtime.addShutdownHook. This is very useful because it releases the resources external to JVM.
Second is related to Finalizers. Either System.runFinalizersOnExit or Runtime.runFinalizersOnExit. The use of finalizers has been deprecated from a long time. Finalizers can run on live objects while they are being manipulated by other threads.This results in undesirable results or even in a deadlock.
01public class shutDownHooksDemo {
02 
03    public static void main(String[] args) {
04            for(int i=0;i<5;i++)
05            {
06                    final int final_i = i;
07                    try {
08                            Runtime.getRuntime().addShutdownHook(
09                                            new Thread() {
10                                            public void run() {
11                                            if(final_i==4) {
12                                            System.out.println("Inside Try Block.Exiting without executing Finally block.");
13                                            System.exit(0);
14                                            }
15                                            }
16                                            });
17                    }
18                    finally {
19                            System.out.println("Inside Finally Block.");
20                    }
21 
22            }
23    }
24}