Saturday, 31 October 2015

Garbage Collection

Garbage Collection- For automatic memory management
Any Object on heap which cannot be reached through a reference from the stack is "eligible for garbage collection".




Memory Leak(Soft leak)
  • An object is referenced on Stack even though it will never be used again 
  • Unused object is never freed


PermGen/MetaSpace
  • PermGen is part of heap until Java7. It is replaced by Metaspace from Java8.
  • Objects in PermGen will survive for ever. It is never Garbage collected. 
  • Application crashes if it runs out of memory.
  • Objects placed in PermGen
    • Internalized Strings- Strings placed in POOL for reuse. (in Java6 only)
    • Class Metadata
    • Application crashes with "out of PermGen" when
      • too many classes to load
      • too many internalized strings
      • Server application - When ever application is redeployed with minor changes, a new complete set of meta data is created. Metadata pertaining to prior deployments is still in the PermGen, but never referred. Hence, if an appln is redeployed number of times, eventually PermGen will runout of space. 
  •  MetaSpace
    • Meta data of the classes are placed
    • Not part of heap
    • Allocated out of your computers native memory(out side of jvm memory or heap memory)


  • Introduction
    • In java, programmer is responsible only for object creation and not for destruction of unused objects.  Jvm provides Garbage Collector to destroy no longer used objects. Because of garbage collector, the chances of java program failing with out of memory is very less.
    • It is part of jvm.
    • It is daemon thread to destroy unused objects
  • The  ways to make an object eligible for garbage collection
    • Nullifying the reference variable
    • reassigning the reference variable
    • Objects created inside a method (local variables will be destroyed after method execution completes)
      • Exception1: For a returned object, if there is reference is caller method, then it is not eligibile for GC
    • Island of isolation
      • If an object does not have any reference variable then it is always eligible for GC
      • Even though object having Reference variable still sometimes it may be eligible for GC, when all references are internal references.
eg:
class Test{
  Test i;
   public static void main(String[] args){
   Test t1=new Test();  Test t2=new Tests();
   t1.i=t2;  t2.i=t1;
   t1=null; t2=null
}
}

  • Methods for requesting jvm to run garbage collector
    • Once we make object eligible for GC, GC may not destroy right away. It will be destroyed only when JVM runs GC. Timing of when jvm runs GC varies from jvm to jvm and we cannot predict it.
    • Instead of waiting for jvm, we can request jvm to run GC. No guarantee that the jvm will accept the request, however in most cases it accepts.
    • System class 
      • System.gc() // Static method
    • Runtime Class
      • Runtime r=Runtime.getRuntime();
        • freeMemory(); //returns free memory present in heap in bytes
        • totalMemory(); //returns total heap memory in bytes
        • gc() // requests jvm to run GC. This is instance method.
  • finalization
    •  
Singleton Class:  Class where only one Object can be created.
eg: Runtime

Factory Method: A method in a class which returns object of the same class is called Factory Method
eg: Runtime r=Runtime.getRuntime();
import java.util.*
class Test{
   public static void main(String[] args){
      Runtime r=Runtime.getRuntime();
      System.out.println(r.totalMemory);
      System.out.println(r.freeMemory);
      for(int i=0; i<1000; i++){
           Date d=new Date();
           d=null;
   }
System.out.println(r.freeMemory);
r.gc();
System.out.println(r.freeMemory);
}

Note
  • Just before destroying an Object, Garbage collector always calls finalize() on that Object. For example, if String Object is eligible for GC, the String class finalize() will be executed, but not on the class where it was created. 
  • finalize() can be called explicitly by program as well. However, it will not destroy the object. Even in the given cases, GC will execute finalize() before destroying the object.
 Memory Leaks:
  • Objects which are no longer used by our program, and still not available for Garbage Collection called Memory Leaks.
  • Program will fail with out of memory error if memory leaks exist
  • To over come the problem, programmer have to make the no longer useful objects available for GC
  • Memory leaks is a purely a programmers mistake
  • Memory management tools to identify memory leaks
    • HP-J-METER
    • HP-OVO
    • J-PROBE
    • HP-PATROL
    • IBM-TIVOLI

Tuning JVM
  • -Xmx - to set Maximum heap size
  • -Xms - to set the starting heap size
    • eg: -Xmx512m -Xms150m  --mega bytes
  • -XX:MaxPermSize  - to set the size of the permgen
    • eg: -XX:MaxPermSize=256M
  • -verbose:gc  print to the console when a garbage collection takes place
  • Young Generation 
    • default 1.3 of heap size
    • -Xmn  - set the size of young generation
      • eg: -Xmn256m
  • -XX:HeapDumpOnOutOfMemory - Creates a heap dump file
  • -XX:MaxPermSize=256M  - set the size of perm gen 
  • -verbose:gc  - print to console when a garbage collection takes place
  • -Xmn  - set the size of the young generation
  • -XX:HeapDumpOnOutOfMemory - creates a heap dump file
 
 
 
Types of Garbage Collectors
  • Serial - uses single thread 
    • -XX: +UseSerialGC
  • Parallel - 
    • -XX: +UseParallelGC
  • Mostly Concurrent. There are 2 such collectors
    • -XX: +UseConcMarkSweepGC
    • -XX: +UseG1GC
  • Use -XX:+PrintCommandLineFlags to find out which is your default garbage collector




Permgen

Weak and soft references:
Weak reference - Reference that may not survive garbage collection. If a variable is declared as Weak, then the object is eligible for garbage collection even though there is variable referencing from stack. When garbage collection takes place, the variable may or may not survive.

Soft reference - Slightly stronger than weak reference. If a variable is declared as Soft, then the object is eligible for garbage collection even though there is variable referencing from stack. Garbage collection considers such variables only when there is real memory crunch.

WeakReference<Book> myBook=book1;
SoftReference<Book> myBook=book2;

These are used for cacheing scenarios.

WeakHashMap - It is implementation of a MAP that works exactly like regular hashmap, but the references between keys and values are Weak references. They are ideal for storing objects in memory. HashMap can be referenced by variable from Stack which is a Strong reference.

Wednesday, 28 October 2015

Regular Expressions

Regular Expression is used to represent a group of String objects according to a particular pattern. They are useful in Validation frameworks, Pattern Matching applications(Ctrl F, Grep), Communication Protocols.

Regular Expression in java is implemented using Pattern and Matcher classes
A Pattern Object represents java object of regular expression. It can be created using compile() method. Pattern.compile("regularExpression");
A Matcher Object to Match the given pattern in target String. It can be created using matcher() of Pattern class.

Methods in Matcher class:
  • find() - Attempts to find next match and returns true if it is applicable. Otherwise returns false
  • start() - Start index of the match
  • end() - end+1 index of the match
  • group() - returns matched pattern

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

class RegExDemo1{
  public static void main(String args[]){
   int count=0;
   Pattern p=Pattern.compile("dv1");//If a class.method() returns object of the class then it is called static factory method.
   Matcher m=p.matcher("dv1dv113dv1");//target string
   while (m.find()){
       count++;
       System.out.println(m.start()+"   "+m.end()+"    "+m.group());
       }
       System.out.println("The Number of Occurences:" +count);  
}
}

Character Classes:
[abc] -> Either a or b or c
[^abc] -> any character except a, b and c
[a-z] -> Any lower case alphabet
[A-Z] -> Any upper case alphabet
[a-z A-Z] -> Any alphabet
[0-9] -> any digit from 0-9
[a-z A-Z 0-9] -> any alpha numerical number
[^a-z A-Z 0-9] -> except alpha numerical number(any special character)

 eg:
   Pattern p=Pattern.compile("[^a-zA-Z0-9]");
   Matcher m=p.matcher("dv1$dv1*13dv1");
   while (m.find())        System.out.println(m.start()+"    "+m.group());

Pre-Defined Character Classes: 
\s   -> Space character
\S   ->Any character except space
\d   ->any digit from 0-9
\D   ->any character except digit
\w   ->any word (alpha numeric character) [a-z A-Z 0-9]
\W   -> except alpha numerical number(any special character)
.       ->any symbol including Special Character also

   Pattern p=Pattern.compile("\\s");  //double backslash to indicate compiler not to treat \ as escape character.

Quantifiers: to specify number of occurrences to match

  a -> Exactly one a
  a+ -> Atleast one a
  a* -> 0 or more a's
  a? -> atmost one a (0 or 1)


split() -> to split the given target string according to the given pattern


class RegExDemo1{
  public static void main(String args[]){
   int count=0;
   Pattern p=Pattern.compile("\\s");
   String[] str=p.split("dv1 dv113 dv1");
   for(String s1 : str){
       System.out.println(s1);
       }
}
}

   Pattern p=Pattern.compile("\\."); // [.]
   String[] str=p.split("venkatdesu.blogspot.com");


String Class - split() method

   String str="dv1 dv113 dv1";
   String[] s=p.split("\\s");
   for (s1:s) System.out.println(s1);

Note: Pattern class split takes Target string as arugument, where as String class split takes pattern as argument.

StringTokenizer - This is designed for Tokenization activity. It is present in java.util package
   StringTokenizer st=new StringTokenizer("dv1 dv113 dv1");
   while (st.hasMoreTokens())
          System.out.println(st.nextToken);

 Note - Default regular expression for StringTokenizer is space.
   StringTokenizer st=new StringTokenizer("dv1 dv113 dv1","1");
  
Regular Expression to represent 10 digit mobile number
  • Every number should contain exactly 10 digits
  • first digit should be 7 or 8 or 9
    • [7-9][0-9] [0-9][0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] 
    • [7-9][0-9]{9}
    • [789][0-9]{9}
  •  If number is 11 digits then the first number should be 0. 10 or 11 digit number regex
    •  0?[7-9][0-9]{9}
  •  If number is 12 digits then the first two numbers should be 91. 10 or 11 or 12 digit number regex
    •  (0|91)?[7-9][0-9]{9}
Regular Expression to all valid mail ids
  • [a-zA-Z0-9][a-zA-Z0-9_.]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+
 Regular Expression to represent gmail ids
  • [a-zA-Z0-9][a-zA-Z0-9_.]*@gmail[.]com
     
Regular Expression to identifier with following rules:
1) Allowed are alpha numeric, # and $
2) length should be atleast 2
3) first should be lower case alphabetic between a and k
4) second should be divisible by 3

  • [a-k][0369][a-zA-Z0-9#$]*
 Regular Expression to represent all names that start with A or a
  • [aA][a-zA-Z]*
 Regular Expression to represent all names that end with L or l
  • [a-zA-Z]*[lL]
 Regular Expression to represent all names that start with A or a AND end with L or l
  • [aA][a-zA-Z]*[lL]

 Program to check a valid mobile number.

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

class checkValidMobile{
  public static void main(String args[]){
   int count=0;
   Pattern p=Pattern.compile("(0|91)?[7-9][0-9]{9}");
   Matcher m=p.matcher(args[0]);//target string
   if (m.find() && m.group().equals(args[0])){
       System.out.println("Valid Mobile Number");
       }
  else {
       System.out.println("invalid Mobile Number");
}
}
}

Program to extract valid mail ids in a text file

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

class checkValidMobile{
  public static void main(String args[]){
   Pattern p=Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9_.]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+");

   PrintWriter pw=new PrintWriter("output.txt");
   BufferedReader br=new BufferedReader(new FileReader("input.txt"));
   String line =br.readLine();

   while (line!=null){
        Matcher m=p.matcher(line);//target string
         while (m.find()){
              pw.print(m.group());
             }
   line=br.readLine();
}
pw.flush();
pw.close();
br.close();
}
}

Program to extract valid mail ids or mobile numbers in a text file
( [a-zA-Z0-9][a-zA-Z0-9_.]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+[789][0-9]{9})
(mail|mobile)

Program to print all .txt files in a directory 

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

class FileNames{
  public static void main(String args[]) throws Exception{
   int count=0;
   Pattern p=Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9_$.]*[.]txt");
   File f= new File("d:\\temp");
   String[] files = f.list();
   while(String f1: files){
   Matcher m=p.matcher(f1);
   if (m.find() && m.group().equals(f1)){
       count++;
       System.out.println(f1);
       }
       System.out.println("Total file counts is:"+count);
}
}


Wednesday, 21 October 2015

Exception Handling

Introduction
An unexpected unwanted event that disturbs normal flow of program is exception. It is highly recommended to handle exceptions. The main objective of exception handling is graceful termination of the program. 

Runtime Stack mechanism
For every thread, jvm creates a runtime stack. Each and every method call performed by the thread will be stored in the corresponding stack. Each entry in stack is called activation record/stack frame. After completing every method call, corresponding entry from the stack will be removed. After completing all method calls, stack will become empty. The empty stack will be destroyed by jvm just before terminating the thread.

eg: Step1: jvm creates a run time stack for main thread. Inserts(push) main(), subFunction1(), subFunction2() and so. Pops the stack as the execution is complete.

Default exception handling in java
  • When an exception occurs, the respective method in which it is raised, is responsible to create Exception Object by including Name of exception, Description of exception, location at which exception occurred(Stack Trace)
  •  After creating exception object method hand overs the object to the jvm.
  • jvm will check whether the method contains exception handling code. If method doesn't contain exception handling code, then jvm terminates the method abnormally and remove the corresponding failed method entry from run time stack of method calls.
  • Jvm identifies the called method, and checks for Exception handling code. If NOT exits, it will terminate abnormally and remove the corresponding method entry from stack
  • The above process will be continued until main method. If main method also does not contain handling code, then jvm terminates the main() abnormally and removes the entry from stack. 
  • JVM will then handover the control/responsibility of exception handling to default exception handler which is the part of jvm, by passing the Exception object. 
  • Default exception handler prints the exception information to console, and terminates the program abnormally.
  • Default exception handler prints exception information in following format:
    • <exception thread>:<exception name>:<exception description> followed by stack trace
    • eg: Exception in thread main(): java.lang.ArthimaticException:division by zero 
      • at Demo.subFunction2()
      • at Demo.Funtion1()
      • at Demo.main()

Example:
 class Demo{
  public static void main(String args[]){
    subFunction1();
}
public static void subFunction1(){
subFunction2()
}
public static void subFunction2(){
int a=5/0;
}}


Exception hierarchy
  • Throwable class acts as root for java exception hierarchy
  • Throwable class defines 2 child classes, Exception and Error.
  • Exception
    • Most of the time exceptions are caused by our program. These are recoverable. eg: remote file not found 
    • RuntimeException
      • ArthimeticException
      • NullPointerException 
      • IndexOutOfBoundsException
        • ArrayIndexOutOfBoundException
        • StringIndexOutOfBoundException 
      • IllegalArgumentException
        • NumberFormatException
    • IOException
      • EndOfFileException 
      • FileNotFoundException
      • InterruptedIOException
    • ServletException
    • RemoteException
    • InterruptedException..
  • Error: Most of the times, errors are NOT caused by our program. These are due to lack of system resources. These are non-recoverable. eg: stack overflow error or out of memory error
    • VirtualMachineError  
      • StackOverflowError
      • OutOfMemoryError
      • AssertionError
      • ExceptionInInitializerError

Checked exceptions:-  Exceptions which are checked by compiler(whether programmer handled or not) for smooth execution of program at runtime are called Checked exceptions. Programmer should handle all such exceptions.

eg:
import java.io.*;
Class TestException{
public static void main(String args[]){
PrintWriter pw=new PrintWriter("file11.txt");
pw.print("Hello World");
}
}

Compiler will throw: Unreported exception java.io.FileNotFoundException must be caught or declared to be thrown

RuntimeExceptions and its child classes are unchecked, Error and its child classes are unchecked. Except these remaining are CHECKED.

Fully Checked vs Partially Checked
  Fully Checked means all Excpetions and its child classes are checked

Customized exception handling by using try-catch
The code which may raise exception is called risky code, and we have to define that code inside TRY block. Corresponding handling code, we have to define inside Catch block.
try{
   risky code;
}catch(Exception e){
   handling code;
}

try{
   stmt1;
   stmt2;
   stmt3;
}catch(Exception e){
   stmt 4;
}
stmt5;

Any where exception is raised, rest of try block will not be executed. Hence length of try block should be as less as possible.
If exception occurs at stmt 4 or 5(not part of try block), it will be an abnormal termination
There may be chance of raising an exception inside catch and finally blocks.

Different methods to get Exception information.
Throwable class defines following methods to print Exception information
printStackTrace(): - Use the method to get Name of exception, description & stack Trace
toString() :- Use the method to get Name of exception and description
getMessage():- Use the method to get description.

Class Test{
public static void main(String args[]){
try{
System.out.println(10/0);
} Catch(ArthimematicException e){
   e.printStackTrace();
  System.out.println(e); //  System.out.println(e.toString());
  System.out.println(e.getMessage()); 
}
}}

Default exception handler uses printStackTrace() to print exception information

If try with multiple catch blocks present then the order of catch blocks is important. Child should be present first then child, other wise it will be compile time error. "Exception XXX has already been caught"

difference between final, finally, finalize
final
   final - It is a modifier applicable for classes, methods and variables
  • When a class is declared as final, then it is not allowed to extend the class i.e not allowed to create child class for it(inheritance not possible)
  • When a method is declared as final, it is not allowed to override in child class
  • When a variable is declared as final, it is not allowed to change the value assigned. 
finally
  finally is a block, always associated with try-catch to maintain clean up code. The block will be executed always irrespective of whether exception is raised/not raised and handled/not handled.

try{
  risky code;
}catch(Exception e){
handling code;
}
finally {
  clean up code;
}

finalize()
It is a method, always invoked by Garbage Collector, just before destroying object, to perform clean up activities. Garbage collector destroys object once the finalize method is executed.

finally block is responsible to perform clean up activities related to try-block i.e what ever resources we opened as part of try block will be closed inside finally block.

finalize() method is responsible to perform clean up activities related to object ie what ever resources associated with object will be deallocated before destroying an object by using finalize().

Points to note:
Either catch or finally has to be associated with try block, else it will be a compile time error.

try block with out catch and having finally block is valid. However it will be abnormal termination.

throw keyword
 It is to hand programmatically created Exception object to jvm manually. It is useful for user defined/custom exceptions. It can be used only for Throwable types.

throws keyword
 In a program, if there is a possibility of raising checked of exception, then we should handle the checked exception. Otherwise, compile time will be raised saying, "Unreported Exception XXX must be caught or declared to be thrown".

  Throws key word can be used to delegate responsibility of exception handling to caller of the method.  The caller could be either jvm or another method.
  Throws key word required only for checked exception. No impact for unchecked exceptions.
  Throws key word is just to avoid compile time exception. It doesn't prevent abnormal termination of program.
  Throws key word for class is invalid. It can be used for methods & constructors.

Within Try block, if there is no chance of raising an exception then adding catch block for fully checked exception will raise compile time error, "Exception ABC is never thrown in the body of corresponding try statement".

Customized or user defined exceptions
  These are exceptions defined by programmer to meet programming requirements.

Class MyException extends RuntimeException
{
     MyException(String str){
    super(str);
}
}

Throw key word is best suitable for user defined or custom exceptions but not for pre defined exceptions. It is recommended to define custom exceptions as unchecked(extend runtime exception).

Top-10 exceptions
Exceptions are divided into  2 categories jvm exceptions & programmatic exception
Exceptions raised automatically by jvm when ever a particular event occurs are jvm exceptions
eg: ArthimaticException, NullPointerException,
Exceptions which are raised explicitly either by programmer or api developer are programmatic exceptions.
eg: IllegalArgumentException

ArrayIndexOutOfBoundsException- When array is accessed with out of range index
NullPointerException - When any operation is performed on NULL
ClassCastException- When we try to typecast parent object to child type
StackOverflowError-Caused by unconditional recursive method call
NoClassDefFoundError- When jvm fails to find .class file
ExceptionInInitializerError- The exception is raised when ever there is error while executing static blocks or static variable assignments.
   Class test{
     static int a=10/0  // ExceptionInIntializerError caused by Arthimatic exception.
}
   Class test{
     static{
     String s=null;
     system.out.println(s.length); /// ExceptionInIntializerError caused by NullPointerException
}
}

IllegalArgumentException- Raised explicitly either by programmer or by api developer to indicate a method has been invoked with illegal argument.

Thread t=new Thread()
t.setPriority(15); // valid range is 0 to 10

NumberFormatException- It is child of IllegalArgumentException. Raised explicitly either programmer or api developer when attempting to convert String that is not properly formatted to Number.
int i = Integer.parseInt("adf");

IllegalStateException- Raised explicitly either by programmer or by api developer to indicate a method has been invoked wrong time.
Thread t = new Thread();
  t.start();
  t.start(); // IllegalThreadStateException

AssertionError- It is child of Error. Raised explicitly either by programmer or by api developer to indicate Assert statement failed.
 assert(x>10);


1.7 version enhancements
         try with resources
try(BufferredReader br = new BufferredReader(new FileReader("input.txt")))
{
//application logic
}
catch(Exception e)
{
}

br will be closed automatically once control reaches end of try block either normally or abnormally.  Programmer is not responsible to close explicitly.
eg: multi resources
try(FileReader fr = new FileReader("input.txt"); FileWriter fr = new FileWriter("output.txt"))
{
//application logic
}

NOTE: The resources(in try) should be autoCloseable.  A resource is autoCloseable if corresponding class implements java.lang.AutoCloseable interface
All I/O resources, DB resources and Network related resources are already implemented AutoCloseable interface.  AutoCloseable interface contains only one method  public void close()
All resource reference variables which are declared as try block are implicitly final. Hence, within try block reassignment is not possible.
Until java 1.6, try should be associated with either catch or finally. From 1.7 onwards, only try with resource with out catch or finally.

try(R)
{
}


 Finally block is not required as resources will be closed implicitly.

multi-catch block 
Until java1.6, even though multiple different exceptions having same handling code,  for every exception type, we have to write a separate catch block. It increases length of code and reduces readability.

Multi-catch block introduced in 1.7 version. Single catch block can handle multiple different type of exceptions.
try{
}
catch(ArthimaticException | IOException  e)
{
  e.printStackTrace();
}
catch(NullPointerException | InteruptionException e)
{
  e.getMessage();
}

In multi catch block, there should not be any relation between Exception types(Parent-Child).

Inside a method when exception handling is not done and when an exception is raised , the exception object will be propagated to caller. Then caller method is responsible to handle exception. This process is called Exception Propagation.

re throwing exception: Use the approach to convert one exception type to another exception.
try {
}
catch(ArthimaticException e){
  throw new nullPointerExcepion();
}



Friday, 2 October 2015

Streams

Important classes in streams
1) File
2) FileWriter
3) FileReader
4)BufferedWriter
5)BufferedReader
6)PrintWriter

File f=new File("newfile.txt");

The above line checks if there exists any physical file already available with name newfile.txt. 
If file already exists, then f points to that file
If it does not exist, it will create a Java File Object to represent the name newfile.txt .(The above statement doesn't create physical file)

various methods in File class are:
exists(), createNewFile(), mkdir(),isFile(), isDirectory(),delete() -> all these methods returns Boolean output
String[] list() -> To retrieve list of files in a directory.

FileWriter
Use FileWriter Object to write Character Data(text data) to the file.
Constructors (Creates a new physical file. If file already exists it will override)
FileWriter fw=new FileWriter(String name);
FileWriter fw=new FileWriter(File f);

Constructors (Following constructors append to the existing physical file)
FileWriter fw=new FileWriter(String name, boolean append);
FileWriter fw=new FileWriter(File f, boolean append);

Methods of File Writer class:
write(int ch) -> to write single character to the file.
write(char[] ch) -> to write array of characters to the file
write(String s) -> to write a String to the File
flush() -> To give the guarantee that, total data including last character is written properly to the file.
close() ->

Limitation: Insert line separator (\n), which is varied from system to system is very difficult

FileReader -> Its a low level reader to read text/char data from file
Use FileReader Object to read Character Data(text data) from the file.
Constructors 
FileReader fr=new FileReader(String name);
FileReader fr=new FileReader(File f);

Methods:
int read();  int read(char[])
   Reads next character returns its Unicode value. Perform type casting while printing.
   Returns -1, on end of file

Limitation: Reading character by character is not convenient and impacts performance.

BufferedWriter -To write Character Data(text data) to the file. It can't communicate directly with file. It can communicate via some writer object only. When a BufferedWriter is closed, automatically underlying file writer will be closed.

Constructors (Creates a new physical file. If file already exists it will override)
BufferedWriter fw=new BufferedWriter(Writer w);
BufferedWriter fw=new BufferedWriter(Writer w, int buffersize);


Methods of Buffered Writer class:

write(int ch) -> to write single character to the file.
write(char[] ch) -> to write array of characters to the file
write(String s) -> to write a String to the File
newLine() -> To insert a line separator 
flush() -> To give the guarantee that, total data including last character is written properly to the file.
close() ->

BufferedReader -> It is a most enhanced reader to read character data from file, either line by line or character by charecter. It can't communicate directly with file. It can communicate via some reader object only. When a BufferedReader is closed, automatically underlying file reader will be closed.

Use BufferedReader Object to read Character Data(text data) from the file.
Constructors 
BufferedReader fr=new BufferedReader(Reader r);
BufferedReader fr=new BufferedReader(Reader r, int buffersize);

Methods:
int read();  int read(char[]), void close(), String readLine()
   Reads next character returns its Unicode value. Perform type casting while printing.
   Returns -1, on end of file
readLine() returns NULL on end of file.

PrintWriter -Most enhanced writer to write Character Data(text data) to the file. It can write any Primitive type data directly to the file.   It can communicate directly with file as well as via some writer object

Constructors (Creates a new physical file. If file already exists it will override)
PrintWriter pw=new PrintWriter(String filename);
PrintWriter pw =new PrintWriter(File f);
PrintWriter pw=new PrintWriter(Writer w);


Methods of Buffered Writer class:

print(char ch) -> to write single character to the file.
print(int i)
print(double d)
print(boolean b)
print(String s)

println(int i)  -> prints and then inserts a new line.

write(100)  -> corresponding character will be added to file
print(100) -> int value 100 will be added to file

POINTS TO NOTE:
1. Most enhanced writer to write character data to the file is PrintWriter, where as the most enhanced reader to read character data from the file is BufferedReader.
2. One should use Readers and Writers to handle Character data(Text data). Use Streams to handle Binary Data.
   We can use FileInputStream to read Binary data from file and we can use FileOutputStream to write Binary data to the File (like Images, Video files, Audio Files etc).