Wednesday 24 August 2016

Exception in java

"An exception is an event or condition which interrupted the normal flow of program execution.Which causes the program termination abnormally."
FileNotFoundException,ArithmeticException and NullPointerException etc.
IntoException
Demo program based on ArithmeticException:
package com.navneet.javatutorial;
public class ExceptionIntroduction {
public static void main(String[] args) {
m1();
}
public static void m1(){
int var1=12;
int var2=0;
int c=var1/var2;
System.out.print(c);
m2();
}
public static void m2(){
System.out.print("Method m2 statement");
}
}
Console Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.navneet.javatutorial.ExceptionIntroduction.m1(ExceptionIntroduction.java:16)
at com.navneet.javatutorial.ExceptionIntroduction.main(ExceptionIntroduction.java:6)
The last two lines shows that the method m2() not executed and program terminates abnormally.
To avoid such conditions ,exception handling comes to the picture.
For more details click here

Monday 25 July 2016

Java File IO

In the early 1990s database concept are not very popular, developer mostly use the File IO concept to store data into System Files.

In the 1995s Database concept comes to the picture and large amount of people uses the database concept ,but being a developer we should know the concept of IO & File and why we should go for u Java IO.We can easily access all the  file handling methods in java by using java IO API.In this blog post we will learn about File & IO concept in Java .Before proceeding to File IO we also know about what is File & IO .

"Java I/O (Input/Output) is used to read data from the various sources from(File,Console and Network Streams or Various Servers etc.) and write data to other file or location .Java uses the concept of streams to make I/O operations fast.
"























File:
"
File is an abstract representation of path name.The main component of the File is

1-Prefix according to System OS like Windows prefix should be  "\\\\" and for UNIX  "\" .
2-And group of String to represent File Name or Directory Name.
java.io package contains File and IO classes. "


Application area of Java Input/Output:

If we want to store small amount of data we should always go for Java File IO Concept.

What kind of Data to store File
1-Textual Data
2-Binary Data(Audio files ,Video files,Network Files etc)


Demo Example:

My file existed in Windows locating at C: Drive and file name is Demo.txt so file representation are as follows.

File f=new File("C:\\File Demo.txt");

Note 1:
Many people feel doubt for below statement creates a file to local system but this myth is not true the below code creates instance of File Class not created file in local system.

So i will discuss some most important methods inside File Class:

1-f.exists()
Description:
The above method return type is boolean it checks file existed or not .

2-f.createNewFile()

Description:
 Atomically creates a new, empty file named by this abstract path name if and only if a file with this name does not yet exist.

3-f.isFile()

Description:
This method return type is boolean and Tests whether the file denoted by this abstract path name is a normal file or not.

4-f.isDirectory()

Description:
This method return type is boolean and Tests whether the file denoted by this abstract path name is a directory or not.

5-f.mkdir()

Description:
This method return type is boolean and it creates directory denoted by this abstract path name.

6-f.getName()

Description:
The above method return type is String and return the name of File and Directory defined by abstract path name.

7-f.delete()

Description:
The above method return type is boolean and Deletes the file or directory denoted by this abstract pathname

JDK has two sets of IO packages
1-(java.io package), introduced since JDK 1.0 for stream-based I/O, and
2-The new I/O (java.nio package), introduced in JDK 1.4, for more efficient buffer-based I/O.

There are various readers are available in java.io package.The FileReader is basic reader for reading stream of character data, and the most powerful reader for reading stream of character data is BufferedReader.

Similarly for reading Binary data 

Two most powerful readers to read stream of binary data are 
1-FileInputStream
2-BufferedInputStream


We will discuss the all the above readers one by one with proper example.

Character Data:

1-FileReader:

Class Declaration

public class FileReader extends InputStreamReader

Implemented interfaces
Closeable, AutoCloseable, Readable

FileReader is meant for reading streams of characters.The constructor details of FileReader is given below

1-public FileReader (String fileName) throws FileNotFoundException

Creates FileReader given the name of the file to read from and throws FileNotFoundException if the named file does not exist.

2-public FileReader (File file) throws FileNotFoundException
Creates FileReader ,given the file to read from and throws FileNotFoundException if the named file does not exist.

3-public FileReader (FileDescriptor fd)
Creates a new FileReader, given the FileDescriptor to read from.


Disadvantage

1-The biggest disadvantage of FileReader class is the maximum size of character is taken in int but the length of the file is long so the rest of the content is missing.

2-The second disadvantage is reading the content of the file is char by char not line by line (performance issue)

Demo Example:Reading file using FileReader

package com.navneet.IO;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {

public static void main(String[] args) {
try{
File f=new File("D:\\Navneet Document\\File.txt");

FileReader fr=new FileReader(f);

char [] data1=new char [900];
fr.read(data1);
for(char s:data1){
System.out.println(s);

}


}
catch(IOException ex){

ex.printStackTrace();

}



}

}


BufferedReader:

To overcome the problem encountered in FileReader ,BufferedReader comes to the picture.BufferedReader reads the data line -by- line performance gets increased.Demo Example :If my file contain 1000 mobile phones list so reading mobile phone char by char
is the best practice or read line by line is the best practice.So last method is also good one.
BufferedReader can't communicate with the file it is necessary need any FileReader to communicate with the file.



















Buffering provides most efficient way to read characters,array and lines.The buffer size may be specified if not specified default size may be used.


There are two constructors inside BufferedReader Class:

1-BufferedReader(Reader in)
This constructors creates a buffering character-input stream that uses default buffer sized input buffer.


2-BufferedReader(Reader in, int sz)
This constructor creates the BufferedReader with subordinate streams with specified buffered size.


Important Methods:

1-int read()
This method reads char from inputstream and return int in the range of 0-65535.

2- int read(char[] buf, int offset, int count)
This method reads an array of destination buffer.

Here the above method parameters are

char[] buf=The destination buffer where we store characters
int offset =index of the array to store chars into the destination buffer.
int count =Maximum numbers of characters

3-public String readLine() throws IOException

The method reads a line of text .A line is considered to be terminated any one of the feed line ("\n"),("\r")


4-public long skip(long n) throws IOException
The method used for skips the characters in BufferedReader and returned the number of charcetrs to be skiped.

Demo Example:Reading file using BufferedReader

package BufferedReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class BufferedReaderskipMethodDemo {

public static void main(String[] args) throws IOException {
String data ="ttrewuuwwnnsnsmamauurururururururuhfkkssueieoesoowowgffhhfjfhfjfjfkfkfkfkkfk";
StringReader sr1=null;
BufferedReader br1=null;
     try{
     sr1 = new StringReader(data);
              br1 = new BufferedReader(sr1);

        int i = 0;
        while((i = br1.read()) != -1)
        {
       
           br1.skip(1);    // skips a character
           System.out.print((char)i);
        }
     
     } catch (Exception e) {
     
        // exception occurred.
        e.printStackTrace();
     }finally{
           sr1.close();
     
           br1.close();
     }


}

}


4-public void close() throws IOException

This method closes the stream and releases any System resources associated with it.After invoking(calling) close() method any other methods such as read(),skip(),readLine() not working and invoking on these methods throws IOException.

close() is the method inside Interface Closeable and extends AutoCloseable interface.

Interface Declaration:

public interface Closeable extends AutoCloseable

Method Declaration:
void close() throws IOException



package com.navneet.IO;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderDemo {

public static void main(String[] args) {

BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("D:\\Navneet Document\\File.txt"));
            String line = reader.readLine();

            while (line!=null) {
                // Print read line
                System.out.println(line);

                // Read next line for while condition
                line = reader.readLine();
            }

        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }





}

}


For Reading Binary Data:

All of the above described Readers for reading text/character data ,and similarly for binary data/raw bytes we will use two most important Readers are
1-FileInputStream
2-BufferedInputStream


1-FileInputStream:
FileInputStream obtains input bytes from a file in a File System.This type of Reader is meant for reading binary data like video files ,audio files and image files not for reading text files.

Various Constructors:
1-FileInputStream (File file)
Creates FileInputStream by opening connection to the File


2-FileInputStream(FileDescriptor fdObj)
Creates FileOInputStream by using the filedescriptor,which representats an existing connection to an actual file system.


3-FileInputStream(String name)
Creates FileInputStream by opening connection to the actual file with filename.


Various Methods of FileInputStream:
1-public int available() throws IOException

This method returns an estimate of the remaining bytes that can be read from inputstream.

 2-public final FileDescriptor getFD() throws IOException
This method returns FileDescriptor object that represents the connection to the actual file in the File System being used by FileInputStream.



3-public FileChannel getChannel()
This method returns FileChannel object associated with the file inputstream.

4-public int read() throws IOException
This method reads byte from this inputstream and returns the next byte of data, or -1 if the end of the file is reached.


5-public int read(byte[] b) throws IOException
 This method reads byte array from this inputstream and returns the next byte of data, or -1 if the end of the file is reached.



Demo Example:
package com.navneet.IO;

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {

public static void main(String[] args) throws IOException {
FileInputStream fis=null;
int i;
     char ch;
      try{
    fis =new FileInputStream("D:\\Navneet Document\\File.txt");
        byte[] b = new byte[fis.available()];
        i=fis.read(b);
        System.out.println("Number of bytes ="+i);
        for(byte data:b)
        {
           ch=(char)data;
           System.out.print(ch);
        }
   
     }catch(Exception ex){
     
        ex.printStackTrace();
    }
      finally{
    {  
    fis.close();
    }
    }
}
}


2-BufferedInputStream

This is hierarchy of BufferedInputStream and class declaration is

"public class BufferedInputStream extends FilterInputStream "


java.lang.Object
  .java.io.InputStream
    .java.io.FilterInputStream
      .java.io.BufferedInputStream


Just like BufferedReader ,BufferedInputStream provides buffering facility to speed-up the file processing ,and BufferedInputStream can't communicate with the file directly.It also need any Stream Reader


Various Important Constructors

1-BufferedInputStream (InputStream in)
Creates a BufferedInputStream and saves its argument, the input stream in, for later use.

2-BufferedInputStream(InputStream in, int size)
Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in for later use.

Demo Example:

package com.navneet.IO;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class BufferedIOStream {
 public static void main(String args[]) throws IOException {
  BufferedInputStream bis = null;
  BufferedOutputStream bos = null;

  try {
 File f=new File("D:\\Navneet Document\\demofile.txt");
 f.createNewFile();
   bis = new BufferedInputStream(new FileInputStream("D:\\Navneet Document\\File.txt"));
 
   bos = new BufferedOutputStream(new FileOutputStream("D:\\Navneet Document\\demofile.txt"));
   int data;
   while ((data =bis.read())!=-1) {
 char ch=(char)data;
    System.out.println(ch);
   bos.write(ch);
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } finally {
   if (bis != null)
    bis.close();
   if (bos != null)
    bos.close();
  }
 }
}


Writer Class:
The writer class is used for write data to the File.There are various File Writers are available in java.io package here we will discuss most important and most commonly used Writers.In the above described writers the most widely used writers are 

FileWriter,BufferedWriter and PrintWriter for character data ,OutputStreamWriter for byte/binary data.

Before proceeding to discuss various Writers we will discuss Writer Class.

The writer class is the parent class of all the writers like StringWriter, CharArrayWriter ,PipedWriter, FileWriter, OutputStreamWriter.This class implements four interfaces.

1-Closeable
2-Flushable
3-Appendable
4-AutoCloseable

The various important methods supported by Writer class are
1-public void write(int c) throws IOException
 "This method writes single character to the file."

2-public void write(char[] cbuf) throws IOException
"This method writes an array of characters to the file."

3-public abstract void write(char[] cbuf,int off,int len) throws IOException
"This method writes a portion of charactes to the file".
Parameters:
cbuf - Array of characters
off - Offset from which to start writing characters
len - Number of characters to write

4-public void write(String str) throws IOException
"This method write string data to the file."

5-public void write(String str,int off,int len) throws IOException
"This method write a portion of string data to the file."

Parameters:
str - A String
off - Offset from which to start writing characters
len - Number of characters to write
6-public Writer append(CharSequence csq) throws IOException
"This method appends the specified characters to this writer."

7-public Writer append(CharSequence csq,int start,int end) throws IOException
"This method appeneds a subsequent character sequence to this writer."

8-public Writer append(char c) throws IOException
"This method appends the specified character to this writer."

9-public abstract void flush() throws IOException
"This method closes the stream, flushing it first.Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown."

10-public abstract void close() throws IOException
"This method flushes the stream.If the stream has saved or any remaning characters from the various write() methods in a buffer,write them immediately to their destination file."




































1-FileWriter :

"FileWriter is the basic or low level writer to write streams of character/text data to the file.FileWriter class extends OutputStreamWriter class.The  hierarchy of FileWriter class is given below."

java.lang.Object
  java.io.Writer
     java.io.OutputStreamWriter
         java.io.FileWriter

class declaration

public class FileWriter extends OutputStreamWriter

Constructors Details:

There are four constructors for FileWriter Class.

1-FileWriter f=new FileWriter(String filename);
Constructs a FileWriter object with the given a filename.

2-FileWriter f=new FileWriter(File file);
Constructs a FileWriter object with the given a File object.

The above two constructors provide override operation.Execution of above constructor writes fresh content to the file.

For performing append operation other two constructors are added to the FileWriter class are

3-FileWriter f=new FileWriter(String filename,booolean appened);
Constructs a FileWriter object given a file name with a boolean indicating appened operation whether or not to append the data written.

4-FileWriter f=new FileWriter(File file,booolean appened);
Constructs a FileWriter object given a file with a boolean indicating appened operation whether or not to append the data written.

Note:
If the provided filename is not existed this constructor automatically creates the given filename to the physical directory.  

The below hierarchy of FileWriter Class:

Class FileWriter

java.lang.Object
   java.io.Writer
     java.io.OutputStreamWriter
         java.io.FileWriter

Methods of FileWrite Class

1-As we know every class is inherited from object class so Object Class Methods are
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

2-Methods inherited from class java.io.Writer
append, append, append, write, write

3-Methods inherited from class java.io.OutputStreamWriter

close, flush, getEncoding, write, write, write

Disadvantage of FileWriter Class:
1-The biggest disadvantage of FileWriter is to add line separator "\n" manually for writing text data into new line.

2-The other drawback is some system not recognized this ("\n") symbol as a new line.

Demo Example:

package com.navneet.IO;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterDemo {

public static void main(String[] args){
 
      FileWriter fw=null;;
           try {
fw=new FileWriter("D:\\NavneetDemo.txt",false);
fw.write(100);  // Write char data to the file
fw.write("\n");
char [] ch={'x','y','z'};  // Write an array of char data to the file

fw.write(ch);
fw.write("\n");
String str="This is demo sample";
fw.write(str);  // Write string data to the file
fw.write("\n");
fw.flush();
       }
    
      catch(IOException io){
 System.out.println(io.getMessage());
       
       }
    finally
         {
    try{
    fw.close();
     }
    catch(IOException ex)
      {
    System.out.println(ex.getMessage());
     }
      }
      
   }


}


2-BufferedWriter:

Class Declaration:
"public class BufferedWriter extends Writer  "

Why we should go for BufferedWriter Class

1-The main disadvantage of FileWriter is adding new line manually which is not good programming practice So BufferedWriter newLine() method solved the problem encountered in FileWriter.

2-Many system does't reconigzed symbol "\n" as a new line.

Note: 
BufferedWriter can't communicate with the File directly it always need any writers like(FileWriter,PrintWriter etc).









Constructors:

There are two constructors are in BufferedWriter class.

1-BufferedWriter bw=new BufferedWriter(Writer w);

2-BufferedWriter bw=new BufferedWriter(Writer w,int buffered size);


Methods:
1-The FileWriter methods available for BufferedWriter class also

FileWriter Methods
------------------------------------
1-write(int ch)
2-write(char[] ch)
3-writer(String str)
4-flush()
5-close()
-----------------------------------
BufferedWriter added method

6-newLine()

"Calling of this method insert line separator to the file"

Note :Many people feel doubt about bw.close() method >Calling of this method automatically closes the any resources associated to the file.There are no need to close 

any other writer object explicitly.




DemoExample:


package com.navneet.IO;

import java.io.*;

public class BufferedWriterDemo {

public static void main(String[] args) {
BufferedWriter bw=null;
FileWriter fw=null;
try{
fw=new FileWriter("D:\\BufferedWriter.txt");
bw=new BufferedWriter (fw);
bw.write(100);
bw.newLine();
char [] ch={'a','b','g','h'};
bw.write(ch);
bw.newLine();
bw.write("BufferedWrite Demo Example By Navneet");
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
finally{
try{
bw.flush();
bw.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}

}

}

3-PrintWriter

PrintWriter is the most powerful and enhanced writer in the java language.PrintWriter gives the facility to write any type of primitive data to the file.The print() 

method is the power of PrintWriter class.

Disadvantage of pervious Writers:
The pervous level of writers faces two biggest problems.
1-The FileWriter uses "\n" symbol for insert line separator manually where as BufferedWriter calls newLine() method for inserting line boths ways are not good 

programming practice.Causes performance and readability.

2-Both writers can't write other primitive data types like (int,double,float,boolean) to the File.If we tried to write this data type to the file program gives error
Demo Example:
if we want to write interger value 100 to the file we write like  this 
write("100");   // Write 100 to the file
write(100);  // Write char 'd' to the file

For writing boolean data to the file we write 

write("true");  //Write true value to the file


Constructor :
According to Java 8 API
1-PrintWriter(File file)
Description:

Creates a new PrintWriter, without automatic line flushing, with the specified file.

2-PrintWriter(File file, String csn)
Description:
Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.

Parameters:
file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output 

will be written to the file and is buffered.

csn - The name of a supported charset

3-PrintWriter(OutputStream out)
Description:
Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.

4-PrintWriter(OutputStream out, boolean autoFlush)
Description:
Creates a new PrintWriter from an existing OutputStream.

5-PrintWriter(String fileName)
Description:
Creates a new PrintWriter, without automatic line flushing, with the specified file name.

6-PrintWriter(String fileName, String csn)
Description:
Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.

csn - The name of a supported charset

7-PrintWriter(Writer out)
Description:
Creates a new PrintWriter, without automatic line flushing.

8-PrintWriter(Writer out, boolean autoFlush)
Description:
Creates a new PrintWriter.

PrintWriter Methods:

The PrintWriter's print method solves the biggest problem encounterd in both the writers.Here we will describe all methods of PrintWriter Class.

FileWriter Class Methods:
---------------------------
1-writer(int ch);
2-writer(char [] ch);
3-writer(String str);
4-flush()
5-close()
----------------------------

----------------------------
Print Methods of PrintWriter:
---------------------------

1-pw.print(100);                                 // Write 100 to the file without line separation  
2-pw.print('c');                                // Write char data to the file without line separation 
3-pw.print("Print method of PrintWriter");      // Write string data to the file without line separation 
4-pw.print(34.6);                               // Write double data to the file without line separation 
5-pw.print(true);                               // Write boolean data to the file without line separation 
6-pw.print(ch);                                 // Write char array to the file without line separation 
==================================
Println Methods of PrintWriter:
==================================

1-pw.println(100);                               // Write 100 to the file with line separation  
2-pw.println('c');                               // Write char data to the file with line separation 
3-pw.println("Print method of PrintWriter");     // Write string data to the file with line separation 
4-pw.println(34.6);                              // Write double data to the file with line separation 
5-pw.println(true);                              // Write boolean data to the file with line separation 
6-pw.println(ch);                                // Write char array to the file with line separation 










package com.navneet.IO;
import java.io.*;

public class PrintWriterDemo {

public static void main(String[] args) {
PrintWriter pw=null;
try{
pw=new PrintWriter("D:\\PrintWriterDemo.txt");
//FileWriter Class methods
pw.write(105);
char [] ch={'a','b','c','r'};
pw.write(ch);
pw.write("PrintWriter Demo Program");

//Various print method of PrintWriter
pw.print(100);
pw.print("c");
pw.print("Print method of PrintWriter");
pw.print(34.6);
pw.print(true);
pw.print(ch);

//Various println method of PrintWriter
pw.println(100);
pw.println("c");
pw.println("Print method of PrintWriter");
pw.println(34.6);
pw.println(true);
pw.println(ch);

}
catch(IOException ex){
System.out.println(ex.getMessage());
}
finally{
pw.flush();
pw.close();

}

}

}


Conclusion :
In the above discussion ,for writing data to the file PrintWriter is the best writer and for reading BufferedReader is the best one.















Saturday 9 July 2016

Java Methods

What is Java Methods :

A java method is nothing but collection of java pre-defined keywords and collection of statements that are group together to perform an operation.The below figure shows the following concept clearly.






















OR

Methods is a piece of code that performs set of operations on operands.Suppose i want to perform an addition operation on two numbers ,what things we should need.

Methods components are..

1-Method Name
2-Return type
3-Passing parameters(Overloading methods)
4-Access Modifiers
5-Collection of statements




















Demo Example:  

The given demo example shows how to make method in Java

package com.navneet.javatutorial;

public class JavaMethods{

public static void main(String[] args) {

Addition.Add(10, 20);    // Calling Add method
System.out.println(Addition.Add(10, 20)); // For Addition

Subtraction.Subtraction(10,20);       //Calling Subtraction Method

System.out.println(Subtraction.Subtraction(10,20));   //For Subtraction

division.Division(10, 20);     // Calling Division method

System.out.println(division.Division(10, 20));   //For Division

Multiplication.Multiplication(10, 20);

System.out.println(Multiplication.Multiplication(10, 20));   //For Multiplication


}

}




class Addition{

 static int Add(int a,int b){
int c=a+b;
return c;
 }
}

class Subtraction{

static int Subtraction(int a,int b){
int c=a-b;
return c;

}

}





class division{


static double Division(double a,double b){
double c=a/b;
return c;

}

}



class Multiplication{

 static float Multiplication(int a,int b){
int c=a*b;
return c;

}



}


O/P Result:

30
-10
0.5
200.0



Types of Methods :

We divide java methods into two broad categories 

1-System Defined Methods (Built-in methods) 

The methods defined inside JavaAPI is the best example of system defined methods for example
main() method ,println() methods and so on.


2-User Defined or Programmer defined methods

The method defined (created ) by the user or programmer is the best example of user defined method.For example ,addition() method described above is user defined method.














Sunday 3 July 2016

Java Regular Expression

In this blog post we will learn about Java Regular Expression.This feature added on java 1.4 version.
Java provides java.util.regex package for searching, extracting, and modifying text in String.This is widely used to validate strings such as password and email validation.Before proceeding to the topic first we should focus on what is regular expression.


Regular Expression:

"A group of String Objects to represent (validate) according to a particular pattern is known as regular expression.A regular expression determine a pattern for a String.Regular Expressions can be used to search, validate or manipulate string."

OR

Representation of a group of String Objects in a particular pattern is known as regular expression. 










The most important application areas where we can use regular expressions are .

>Validate phone,email on login and sign up forms.
>Validation Framework
>Pattern Matching Applications(Search)
>Compiler Design(Translater like compiler,interpreter).
>Digital circuit design(like Binary adder,Binary incremental).
>Communication area(TCP/IP,UDP).

java.util.regex package provides three classes and one interface.The below is the java.util.regex package internal hierarchy.






Java Regular Expression classes are present inside java.util.regex package that contains three classes.

1) java.util.regex.Pattern – Used for design or making patterns
2) java.util.regex.Matcher – Used for performing match operations on text using patterns
3) java.util.regex.PatternSyntaxException 
4) MatchResult interface


1-Pattern object is the compiled version of the regular expression.This class doesn’t have any  constructor and we use it’s public static method compile to create the pattern object by passing regular expression argument ya pattern String.

2- Matcher is the regex engine object that matches the input String pattern with the pattern object created.We get a Matcher object using pattern object matcher method that takes the input String as argument.We then use matches method that returns boolean result based on input String matches the regex pattern or not.

3- PatternSyntaxException is thrown if the regular expression syntax is not correct.


If you want to work with regular expression in java you always start with Pattern class.For defining and validating any expression we need pattern which is nothing but comes from Pattern Class.How to define pattern the below codes gives much more clearity.

Pattern p=p.compile("abc");              // This method gives compiled version of Regular Expression []

 String target="abcdefgabchuydabc";

Suppose this is my target String "abcdefgabchuydabc" & I want to find the above String contains String "abc" or not if  abc exits in the above expression in which postion they occur and how many times occurs in the traget String.For the above such applications we need Regular Expression.This is not the traditional concept but it is the new concept which add on Java 1.4 version.Other examples which uses Regular expression concept is Ctrl+F command in Microsoft Windows and grep command in UNIX.


Here is the sample pattern matching java program to find particular pattern Strings from target Strings using Regular Expression.

For making this program firstly we need three steps:

1-Define the pattern (Using Patterns Compile method)
2-Compare with Input String(Using Matcher ) 
3-Use find method to search pattern string position and count (occurence).

1-Pattern Matching Application:

package com.navneet.javatutorial;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpression {

public static void main(String[] args) {
       int count=0;
       Pattern pt=Pattern.compile("xy");                // Define pattern using compile method of pattern class
       Matcher m=pt.matcher("zxvxybfxyuvxyioxy");      // Create matcher object to find match
       while(m.find()){
      count++;
      System.out.println(m.start());
      
      
          }
       System.out.println("The number of occurence"+count);

}

}

2-Validating Mobile And Email IDs:


package com.navneet.javatutorial;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidateMobileNumber {

public static void main(String[] args) {
Pattern p=Pattern.compile("[0]?[7-9][0-9]{9}");
String input;
// Phone number starting with 0 and followed by 10 digit mobile number starting digit should be 7 to 9.
System.out.println("Please enter 10 & 11 digit Mobile Number"); 
Scanner sc=new Scanner(System.in);
input=sc.nextLine();
Matcher m=p.matcher(input);
        if(m.find()&&m.group().equals(input))
        {
        System.out.println("Valid Mobile Number ");
        }
        else
        {
        System.out.println("Invalid Mobile Number ");
        }
}

}

Email Validation:

Suppose i want to validate any email id staring with "xxx7_.yddhh89@gmail.com" how can i make regular expression to validate such email ,below is the process how can define pattern.

Firstly make a pattern 

1-The first character starting with any digit or UpperCase/LowerCase letters  [a-zA-Z0-9]
2-The second character pattern talks about remaining characters   [a-zA-Z0-9_.]*
3-The third character is mandatory symbol @
4-The fourth character is any alpha Numeric character atleast one time [a-zA-z0-9]+
5-The fifth character is  ([.][a-zA-z0-9]+)

So complete pattern for any mail ID is

[a-zA-Z0-9][a-zA-Z0-9_.]*@[a-zA-z0-9]+[.]([a-zA-z]+)+

Pattern for only gmail IDs

[a-zA-Z0-9][a-zA-Z0-9_.]*@gmail[.]com

Pattern for yahoo IDs

[a-zA-Z0-9][a-zA-Z0-9_.]*@yahoo[.]com

package com.navneet.javatutorial;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GmailIDValidation {

public static void main(String[] args) {

Pattern p=Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9_.]*@gmail[.]com");
String input;
System.out.println("Please enter Gmail ID"); 
Scanner sc=new Scanner(System.in);
input=sc.nextLine();
Matcher m=p.matcher(input);
        if(m.find()&&m.group().equals(input))
        {
        System.out.println("Valid Mail ID");
        }
        else
        {
        System.out.println("InValid Mail ID");
        }




}

}


Character Class:

Character class are mostly used to make a pattern.

[abc]=Either a or b or c.
[^abc]=^ symbole means Except a,b and c
[a-z]=Any lower case letter from a to z.
[A-Z]=Any upper case letter from a to z.
[a-zA-Z]=Any lower case and upper case letter.
[0-9]=Any digit from 0 to 9.
[a-zA-Z0-9]=Any alpha numeric character.
[^a-zA-Z0-9]=Except any alpha numeric characters means special characters.


Pre-defined character classes:

\s =Space character
\S =Except space character
\d=Any digit from 0-9
\D=Except digit from 0 to 9
\w =Any word character [a-zA-Z0-9]
\W =Except any word character [a-zA-Z0-9] (means special characters)
.=Any character

Note:
The another most important method inside Pattern Class is split() method:

This method is used to split the target String according to particular pattern.

Sunday 19 June 2016

Date -Time API in Java

In this blog post we will explain both Java 8 & 7 Date -Time API.Java date time API has been changed in Java 8 with the introduction of a new set of packages & classes.The below figure showing the Java date-time API architecture.






















In Java 8, a new Date-Time API is introduced to cover the following disadvantages of Java 7 Date-time API

1-Thread safe - java.util.Date is not thread safe, thus developers have to deal with concurrency issue while using date. The new date-time API is immutable.

2-Date Time Format design - Default Date starts from 1900, month starts from 1, and day starts from 0, so no uniformity. The Java 7 Date -Time API had less direct methods for date operations.The new API provides numerous methods for such operations.

3-Different time zone handling -Developers had to write a lot of code to deal with time zone issues.The new Date-Time  API has been developed keeping zone-specific design in mind.



Java 8 Date -Time API:

The Java 8 new date time API is introduced in the Java package java.time which is part of the standard Java 8 API docs.

The java.time package also contains a set of subpackages which contains following below sub packages.
1-java.time.chrono 
2-java.time.class-use
3-java.time.format
4-java.time.temporal
5-java.time.zone

java.time.chrono contains classes to work with different countries calendars.
The java.time.format package contains classes used to parse and format dates from and to strings.


Following are the important classes introduced in java.time package ...

Local - Simplified date-time API with no complexity of time zone .
Zoned - Specialized date-time API to deal with various time zones.


1-Local Data-Time API

LocalDate/LocalTime and LocalDateTime classes simplify the development where time zones are not required.The below is demo example showing how to use Local Date-Time API.


Demo Example:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;

public class DateTime {

public static void main(String[] args) {

// Get the current date and time

LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current DateTime: " + currentDateTime);
LocalDate date = currentDateTime.toLocalDate();    // Get the local date From Current Local date time
System.out.println("date: " + date);
Month month = currentDateTime.getMonth();
int day = currentDateTime.getDayOfMonth();
int seconds =currentDateTime.getSecond();
System .out.println("Month: " + month +"day:" + day +"seconds: " + seconds);

LocalDateTime date1 = currentDateTime.withDayOfMonth(10).withYear(2016);
System .out.println("date1: " + date1);
//12 december 2016
LocalDate date2 = LocalDate.of(2016, Month.DECEMBER, 12);
System .out.println("date2: " + date2);
//20 hour 15 minutes
LocalTime date3 = LocalTime.of(20, 15);
System .out.println("date3: " + date3);
//parse a string
LocalTime date4 = LocalTime.parse("20:15:30");
System.out.println("date5: " + date4);

 
}

}

O/P Result:

Current DateTime: 2016-06-19T20:58:03.674
date: 2016-06-19
Month: JUNEday:19seconds: 3
date1: 2016-06-10T20:58:03.674
date2: 2016-12-12
date3: 20:15
date5: 20:15:30


2-Zoned Data-Time API

Zoned Date-Time API is to be used when time zoned is to be considered.Let see the below demo program.



import java.time.ZoneId;
import java.time.ZonedDateTime;

public class DateTime {

public static void main(String[] args) {

// Zone Date-Time API Testing


// Get the Zone Date Time
ZonedDateTime date = ZonedDateTime.parse("2016-06-19T10:15:30+05:30[Europe/Paris]");
System.out.println("date: " + date);
// Getting the current Zone ID
ZoneId currentZone = ZoneId.systemDefault();
System.out.println("CurrentZone: " + currentZone);

 
}

}

O/P Result:

date: 2016-12-03T10:15:30+01:00[Europe/Paris]
ZoneId: Europe/Paris
CurrentZone: Asia/Calcutta



Period & Duration:
In Java 8 Date-Time API introduced two most important deals with the time differences.

Period - It finds the period between date based time.
Duration - It finds the period between time based duration.



import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

public class DateTime {

public static void main(String[] args) {

//Test Duration
LocalDate date1 = LocalDate.now();
System.out.println("Current date:" + date1);
//add 2 months to the current date
LocalDate date2 = date1.plus(2, ChronoUnit.MONTHS);
System.out.println("Next month: " + date2);
Period period = Period.between(date2, date1);
System .out.println("Period: " + period);

// Test Period
LocalTime time1 = LocalTime.now();
Duration fourHours = Duration.ofHours(4);
LocalTime time2 = time1.plus(fourHours);
Duration duration = Duration.between(time1, time2);
System.out.println("Duration: " + duration);
 
}
}


O/P Result:
Current date:2016-06-19
Next month: 2016-08-19
Period: P-2M
Duration: PT-20H



The Java 8 date time API consists of the following classes:

Instant class:

Represents an instant in time on the time line.In Java 8 the Instant class represents an instant in time represented by a number of seconds and a number of nanoseconds since Jan. 1st 1970.

Duration Class:

Duration class represents a duration of time,for instance the time between two instants.

LocalDate Class:

Represents a date without time zone information.

LocalDateTime Class:

Represents a date and time without time zone information.

LocalTime Class:
Represents a local time of day without time zone information.


ZonedDateTime Class:
Represents a date and time including time zone information

DateTimeFormatter Class:
Formats date time objects as a Strings. For instance a ZonedDateTime or a local date time.