Wednesday, October 17, 2012

Java Tidbits ....................... reading streams from File

1) FileReader fop = new FileReader(f);   // file or string
int n =0;
       
  while ((n=fop.read())!=-1)     // read a single character from file
      System.out.print((char )n);
in above  code  we can use read(byte[]) too .
in that case it will read the data from file and  populate in a defined  byte array that can be printed / used later  in next example done like that .


2) FileInputStream fis = new FileInputStream(f);  // file or string
byte b[] = new byte[1048];
System.out.println(fis.read(b));

3)  InputStream can be piped to InputStreamReader

     InputStreamReader reader = new InputStreamReader(fis);    // inputstream

4) Any reader instance can be piped to BufferedReader .

   BufferedReader bufferedReader = new BufferedReader(fop);  // Reader instance is required
    BufferedReader bufferedReader = new BufferedReader(reader);// allowed instance of reader

we can readLine from BufferedReader.

Java Tidbits ...................wrinting streams to file

The other low level ways to write  bytes into File rather than chars  requires the use of stream classes.
Like reading image data and writing into file . 

Hierarchy of stream classes is published on previous post.

To write byte or character stream into File we need  instance of OutputStream 
ie: ObjectOutputStream or FilterOutputStream  or FileOutputStream

OutputStreamWriter opts = new OutputStreamWriter( OutputStream opt); 

1) FileOutputStream fops = new FileOutputStream(f, true);
    OutputStreamWriter opts = new OutputStreamWriter(fops);   // fops instanceof OutputStream
        opts.write(97);
        opts.close();


public BufferedOutputStream(OutputStream out , in size)  // size is optional
2) BufferedOutputStream bf = new BufferedOutputStream(fops);
        bf.write(66);
        bf.close();


3) Pipe any instance of Outputstream to DataOutputStream       bf or fops both qualifies
        DataOutputStream df = new DataOutputStream(bf);   // from (2) bf instance of OutputStream
        df.write(67);
        df.close();

flexibility given in DataOutputStream is its instace can write  double , int , boolean float etc too the writer .
        df.writeBoolean(new Boolean(true));
        df.writeDouble(34.12);

4) use of PrintStream with file as argument will override the whole file.
     PrintStream pf = new PrintStream(f); // override file
        pf.write(68);
        pf.close();


piping it to any outputstream will prevent it from overriding .

5) PrintStream pf = new PrintStream(fos,true);
        pf.write("hello");
        pf.close();

It has very specific methods for writing , formatting , printing text into file.
6)
   BufferedWriter bw= new BufferedReader(fow);  // Writer
   we can wrap printwrite into bufferwriter  and reverse too
   BufferedWriter bw = new BufferedWriter(pos);  // allowed
   PrintWriter pos = new PrintWriter(bw);  // allowed


   we can write a new line character by using bufferwriter .

Java Tidbits .................... (File Streams heirarchy)




















In the above picture  , all classes that implements DataInput / DataOut interfaces provide the facility to  read / write  byte streams into the File .

Java Tidbits ..........................(File I/O)

File f = new File(string str)

f is an instance of File object . It wont  create or delete any file  with the name  str on DISK.
it can be checked to see if there is any such file with the path name specified by str or not .
f.createNewFile() will craete the file in specified path  throws IOException
f.mkDir() is for making directories

To write into file FileWriter object is required
 FileWriter fow = new FileWriter(file instance , boolean  append );
new FileWriter(file instance );  // by default append  is false  & it will overwrite the file./string
FileWriter fow = new FileWriter(f,true);  // append at last 

FileOutputStream fops = new FileOutputStream(file ) // file or string
FileOutputStream fops = new FileOutputStream(f, append);

ways to write into file 

1) FileWriter fow fow = new FileWriter(f,true);       
       
        fow.append("Hello ");   
        fow.append("\nHow r u ?");
        fow.flush();
        fow.close();

//Note : FileWriter extends FileOutPutStream

2) FileOutputStream fops = new FileOutputStream(f, true);
        fops.write("My name is khan".getBytes());
        fops.flush();
        fops.close();

3) PrintWriter pos = new PrintWriter(file); // or string
        pos.write("Ayyaiyya!");       
        pos.flush();
        pos.close();

4) FileOutPutStream can be  piped to PrintWriter .
PrintWriter pos = new PrintWriter(fops, true); // autoFlush true
        pos.write("Ayyaiyya!");       
        pos.flush();
        pos.close();


5) FileWriter can be  piped to PrintWriter .
PrintWriter pos = new PrintWriter(fow, true); // autoFlush true
        pos.write("Ayyaiyya!");       
        pos.flush();
        pos.close(); 


6)Pipe OutputStreamWriter to PrintWriter 
OutputStreamWriter opts = new OutputStreamWriter(fops);
        PrintWriter pos = new PrintWriter(opts, true);
        pos.write("Great!");

        pos.flush();
        pos.close();

Tuesday, October 16, 2012

Java Tidbits ............................(Initializers!)

A class has  instance vars and instance methods , constructors  and  init block and static init block.
The order of initializer block to be called is 
  1. declaration of  vars ( both static as well as non -static)
  2. static block
  3. init block
  4. constructor

declaration-before-reading Rule
declaration of a field must occur before its usage in any initializer
expression if the field is used on the RHS of an assignment in the initializer expression.
declaration-before-reading rule: it does not apply if the
initializer expression defines an anonymous class, as the usage then occurs in a different class which has its own accessibility rules in the enclosing context.
final static fields can only be initialized either at time of declaration or with in static block.


Here is an example 


public class MyInitializer {
   
     boolean flag = true;
     final static int ROOM=7;
     int l=h=8; // declaration-before-reading
     int f=  new mysmall(){
                 int getsmall( ){return h;}
                 }.getsmall();
     //mytest.BOOK;
     int k = getK(); 
   
     int  getK(){
        return h; // declaration-before-reading
     }

   
     static{
         NUM=200; // declaration-before-reading
        // ROOM=45;
         System.out.println("static init block "+ROOM);
     }
     {
         System.out.println(" instance init block ");

         try{
         if(flag )
             throw new Exception();
         }catch(Exception e){System.out.println(" caught in init block"+ROOM);}
     }
     int h=9;
   
     MyInitializer(){
           
         System.out.println(" A constructor will be called in end "+ROOM);
     }
     private static int NUM;
   
     interface mytest { int BOOK=60;}
     class mysmall{ int getsmall( ){return 20;} }

    public static void main(String args[]){
        MyInitializer mObj = new MyInitializer();
        System.out.println(" mObj.f="+ mObj.f + " mObj. k="+mObj.k + " NUM"+NUM);
        // both k & f will be 0 since h is not initialized .
        // if h is initialized  before then it will take its value
        // here its picking 8  since h 's value is overwritten
    }
}

Tuesday, October 9, 2012

Java Tidbits......................(Polymorphism)

This is the topic that had shown me stars during day ! Every time when i read any java book i felt that i am pretty clear with this & can handle  any type of Qs but every time i failed .

polymorphism  is simple concept of deciding  at run time which object's method to be called .
Here i will paste few examples where i was most confused

case 1

class ABC {
           private int a=10;
           int getA ( )
            {return a;}
}

class BCD extends ABC{
            private int a=20;
            int getA ( )
            {return 2*a;}
}

public static void main(Strings args[])
{

ABC a = new ABC();
s.o.p ( a.getA( ) )  ;  
BCD b = new BCD();
s.o.p ( b.getA( ) ) ;

//   b=a;                  Compiler Error

b = ( BCD ) a;            //  Need to type cast explicitly
s.o.p ( b.getA( ) ) ;      // ClassCastException at run time


}

Reason 1

Compiler will error because upcasting is not automatic in java
ClassCastException will come when the object reference of base class point to base class object .

to remove that
a = new BCD ( ) ;
b= ( BCD ) a;

....to be continued ....





Ramblings of a confused Java programmer

javac -d path_to_classes_dir name of java file

The -cp option can be used to set the class path for each application individually

for example
-cp /pgjc/work:/top/bin/pkg:.
Here  path-separator character ':' for Unix platforms to separate the entries, and also included the current directory (.) as an entry.
For windows it is ';' used as path separator

One cannot call method of base class using super keyword from static method.
Given below is example
   class SuperCalc {
                 protected static  int multiply(int a, int b) { return a * b;}
    }
    class SubCalc extends SuperCalc{
                 public  static  int multiply(int a, int b) {
                 int c =super.multiply(a, b);   // wrong !! cannot use super from inside static
                 return c;
     }
 }

Class names and method names exist in different namespaces.


Collections.sort() // can only be used for List or its subclasses
Arrays.sort() // can only be used for object arrays or long[]

Default modifier is narrower than protected modifier . Method having default access modifier can be declared as protected in its  sub class.
Default member  accessibility is more restrictive than protected member accessibility.

A base class reference cannot be assigned to sub class reference . ( it will give compile time error ) if
type casted then will give runtime class cast exception.
but a subclass ref can be assigned to base class ref

Need to go through Locale / Date / Date format / Localization


An anonymous inner class can extend either one subclass or implement one
interface. Unlike non-anonymous classes (inner or otherwise), an anonymous
inner class cannot do both. In other words, it cannot both extend a class and
implement an interface, nor can it implement more than one interface.

this is not only a keyword its a constructor !

class Base1{
               private int  score;
               private int goal;
   
              Base1()
              {
                 this(20);   
              }
              Base1(int score)
              {
               //this.score=score;   valid
               this(score, 2*score);
              }
              Base1(int score, int goal)
              {
               this.score=score;
               this.goal=goal;
               }
               void printScore()
              {
                 System.out.println(" Score ="+score + "goal = "+goal);
              }
}

addAll() , retainAll(), removeAll () are destructive operations .!! be safe while playing .

Generic Type classes cann't be instantiated !
nor Arrays can be formed of Generic Type .




The && and || operators are short circuit operators. A short circuit operator is one that doesn't
necessarily evaluate all of its operands. Take, for example, the operator &&. What happens when Java
executes the following code?
if (0 == 1 && 2 + 2 == 4) {
out.println("This line won't be printed.");
}


Realize that the condition (2 + 2 == 4 || whatever) must be true, no matter what
the whatever condition happens to be.



Field of an object is accessed using a reference, it is the type of the reference, not the class of the
current object denoted by the reference at runtime  .  It is called Field Hiding .

Interfaces are by default static , irrespective of their declaration.
Non static Inner classes can't have static  members/ interfaces / static  methods .
Only inner classes can be declared as static  .

Interfaces cannot be static unless they are inside a class.