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.

Monday, October 8, 2012

Java Tidbits .................(Perm Space)

Permanent Generation Space in JVM is a separate memory area than usual heap / stack .
It contains the information about static classes , variables etc that are stored permanently ..like Class's definitions are stored on it permanently . Class loaders deploy and undeploy classes all the time.When an application is deployed or undeployed, its class definitions and Classloader are respectively put into and removed from the permanent generation heap. 
When this space in memory gets filled  then program throws  OutOfMemoryError: PermGen Space error.
More information for this are at 


To make size of the permanent generation heap space bigger

-XX:MaxPermSize=256m is the cmd

Friday, October 5, 2012

Overriding start() ?...........gotcha !!

I tried overriding start() , even though its not required since extending  thread means one can override run() that will be sufficient to do desired work . But again showing my stupidity i did that as below 


public class MyThread extends Thread{   
   
    public void start()
    {       
        System.out.println( " MyThread started " );
        run();
    }
    public void run(){
       
        for(int i =0 ; i < 3 ; i + + )


            System.out.println( i );


             throw new RuntimeException();
    }
   
    public static void main(String...a)

  {
        MyThread mt =  new MyThread();
        mt.start();
        System.out.println ( " Done " );
    }

}


And it made me puzzled that while running this program it executed in single threaded environment .
did you get the cause ? 
because in order to spawn a new thread start() method must call super.start() from with in start() that internally invokes run() method of custom thread .Other wise it would have been a regular method call .

So i need to over start as below & no need to call run() explicitly

public void start(String... args)
    {
       
        System.out.println ( " MyThread started " );
        super.start();
    }


Next Time respect Thread little more ! :-)

Wednesday, October 3, 2012

Java Tidbits ....................5(Covariant)

  •  An overriding method, should define exactly same set of argument list, as the overridden method, or else we will end up defining an overloaded method. This includes the covariant data types, i.e., if any argument in the overriding method is a subclass of the argument defined in the super class, we will end up defining an overloaded method.
  •  A valid overriding method can define a return type, which is a subclass of the return type defined by the Overridden method in the super class. 
Run this example  and tweak your brain.
---------------------------------------------------------------------------------
class TestB{
    int kk=9;
    public  Object mytest(Object o)
    {
        System.out.println("ok in Base");
        return o;
    }
}

public class TestA extends TestB{
   
    int kk =8;
   
    public  String mytest(Object o )
    {
        System.out.println("ok in overloaded sub class");
        return o.toString();

    }
    public  void mytest(String o )
    {
        System.out.println("ok in sub class");

    }
    public static void main(String args[])
    {
      
        TestB tb = new TestB();
        TestA ta = new TestA();

        
        ta.mytest("ok");
        tb.mytest("ok");
        System.out.println(" ta.kk = "+ ta.kk + "tb.kk = "+tb.kk);
      
        tb = new TestA();
        tb.mytest("ok");
        System.out.println("tb.kk = "+tb.kk);

      
        System.exit(0);

     }

For more examples on covariant types refer >>
http://cafe4java.com/mockexams/scjp/mock1/q1.php

Monday, October 1, 2012

Java Tidbits ............................4(enum)

  • Enums are special classes whose fields are constants.
  • Enum can be declared either inside of a class or as separate class.
  • When outside a class Enum can either be public or default access modifier. By default nested enum are static ( ie inside class ).
  • In Enum definitions the enum constants must be declared before any other declarations in an enum type. ( compile error will be thrown if it is occurs )
  • Enum cannot be declared inside methods .why ? ( because methods cannot have class ) 
  • ; colon is optional to be placed at end of enum syntax.
  • Enum cannot be invoked via new operator .
  • Like classes Enum can have multiple argument constructor or may have overloaded constructors  .
  • Like classes Enum can have methods definitions.
  • Enum can  provide constant specific class body ie : a particular constant can override one or more  of its methods .
  • Enum are implicitly Serialiazable and comparable and extends Enum abstract class , so enum can be  serialized and can be put into  ordered collection.
  • If there is any abstract method declared inside enum class then each of its enum type must have to provide its definition.
  • Abstract & Final Enum cannot be defined.
  • equals(), compareTo(), finalize() methods are final . it cannot be overridden.
  • Enum can implement interfaces but cannot extends any other class. 
  • Enum cannot be of Generic Type.
Practice few Enum from K & B book .

http://www.ejavaguru.com/scjp5freemockexam.php#enumq9

Generics aren't so generic !

Generics in Java 5 enables Types(class/interface) to  have parameters when defining classes, interfaces and methods.A generic type is a type with formal type parameters. While A parameterized type is an instantiation of a generic type with actual type arguments.

A generic type is a reference type that has one or more type parameters. These type parameters are later replaced by type arguments when the generic type is instantiated (or declared )

If the compiler erases all type parameters at compile time, why should you use generics?

1) To provide compile time casting.
2) Elimination of casts
3) Enabling programmers to implement generic algorithms. ..( more later )

******UpperBound WildCards
ex:
List <  ? extends Number >

take method
public static double sumOfList(List < ? extends Number > list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}


here both
List < Integer >  li = Arrays.asList(1, 2, 3);
List < Double > li = Arrays.asList(1.1, 2.1, 3.1); 
can substitute at compile time.


******LowerBound WildCards 


public static void addNumbers(List < ? super Integer > list) {
    for (int i = 1; i <= 10; i++) {
        list.add(i);
    }
}
 
Here only  
List < Integer > li = Arrays.asList(1, 2, 3);
or List < Number > li = Arrays.asList(1, 2, 3); 
can be passed at compile time.
Since Integer or any of its super class is allowed .

More explanation on Generic Types is given at

http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html