Friday, 2 April 2010

File Handling and Input/Output

java.io package
Classes related to input and output are present in the JavaTM language package java.io . Java technology uses "streams" as a general mechanism of handling data. Input streams act as a source of data. Output streams act as a destination of data.
File class
The file class is used to store the path and name of a directory or file. The file object can be used to create, rename, or delete the file or directory it represents. The File class has the following constructors - File(String pathname); // pathname could be file or a directory name File(String dirPathname, String filename); File(File directory, String filename); The File class provides the getName() method which returns the name of the file excluding the directory name. String getName();
Byte Streams
The package java.io provides two set of class hierarchies - one for handling reading and writing of bytes, and another for handling reading and writing of characters. The abstract classes InputStream and OutputStream are the root of inheritance hierarchies handling reading and writing of bytes respectively. Figure : InputStream class hierarchy (partial) Figure : OutputStream class hierarchy (partial)
read and write methods
InputStream class defines the following methods for reading bytes - int read() throws IOExceptionint read(byte b[]) throws IOExceptionint read(byte b[], int offset, int length) throws IOException Subclasses of InputStream implement the above mentioned methods. OutputStream class defines the following methods for writing bytes - void write(int b) throws IOExceptionvoid write(byte b[]) throws IOExceptionvoid write(byte b[], int offset, int length) throws IOException Subclasses of OutputStream implement the above mentioned methods. The example below illustrates code to read a character. //First create an object of type FileInputStream type using the name of the file.FileInputStream inp = new FileInputStream("filename.ext");//Create an object of type DataInputStream using inp.DataInputStream dataInp = new DataInputStream(inp);int i = dataInp.readInt();
Reader and Writer classes(l.w. = chr = character and last r = reader )
Similar to the InputStream and OutputStream class hierarchies for reading and writing bytes, Java technology provides class hierarchies rooted at Reader and Writer classes for reading and writing characters. A character encoding is a scheme for internal representation of characters. Java programs use 16 bit Unicode character encoding to represent characters internally. Other platforms may use a different character set (for example ASCII) to represent characters. The reader classes support conversions of Unicode characters to internal character shortage. Every platform has a default character encoding. Besides using default encoding, Reader and Writer classes can also specify which encoding scheme to use.The Reader class hierarchy is illustrated below. The Writer class hierarchy is illustrated below. The table below gives a brief overview of key Reader classes.
CharArrayReaderThe class supports reading of characters from a character array.
InputStreamReaderThe class supports reading of characters from a byte input stream. A character encoding may also be specified.
FileReaderThe class supports reading of characters from a file using default character encoding.
The table below gives a brief overview of key Writer classes.
CharArrayWriterThe class supports writing of characters from a character array.
OutputStreamReaderThe class supports writing of characters from a byte output stream. A character encoding may also be specified.
FileWriterThe class supports writing of characters from a file using default character encoding.
The example below illustrates reading of characters using the FileReader class. //Create a FileReader class from the file name.FileReader fr = new FileReader("filename.txt");int i = fr.read(); //Read a character

Threads

Threads
A thread is in process in execution within a program. Within a program each thread defines a separate path of execution.
Creation of a thread
A thread can be created in two ways a) By implementing the Runnable interface. The Runnable interface consists of only one method - the run method. The run method has a prototype of public void run(); b) By extending the class Thread.
Execution of a thread
To execute a thread, the thread is first created and then the start() method is invoked on the thread. Eventually the thread would execute and the run method would be invoked. The example below illustrates the two methods of thread creation. You should note that the run method should not be invoked directly.

public class ThreadExample extends Thread {
public void run() {
System.out.println("Thread started");
}
public static void main(String args[]) {
ThreadExample t = new ThreadExample();
t.start();
}
}
Example - Creation of Thread by extending the
Thread class.
When the run method ends, the thread is supposed to "die". The next example shows the creation of thread by implementing the Runnable interface.

public class ThreadExample2 implements Runnable {
public void run() {
.../* Code which gets executed when
thread gets executed. */
}
public static void main(String args[]) {
ThreadExample2 Tt = new ThreadExample2();
Thread t = new Thread(Tt);
t.start();
}
}

Example - Creating thread by implementing Runnable
States of thread
A thread can be in one of the following states - ready, waiting for some action, running, and dead. These states are explained below. Running State A thread is said to be in running state when it is being executed. This thread has access to CPU. Ready State A thread in this state is ready for execution, but is not being currently executed. Once a thread in the ready state gets access to the CPU, it gets converted to running state. Dead State A thread reaches "dead" state when the run method has finished execution. This thread cannot be executed now.Waiting State In this state the thread is waiting for some action to happen. Once that action happens, the thread gets into the ready state. A waiting thread can be in one of the following states - sleeping, suspended, blocked, waiting for monitor. These are explained below.
Yielding to other processes
A CPU intensive operation being executed may not allow other threads to be executed for a "large" period of time. To prevent this it can allow other threads to execute by invoking the yield() method. The thread on which yield() is invoked would move from running state to ready state.
Sleep state of a thread
A thread being executed can invoke the sleep() method to cease executing, and free up the CPU. This thread would go to the "sleep" state for the specified amount of time, after which it would move to the "ready" state. The sleep method has the following prototypes.

public static void sleep (long millisec) //sleep for millisec
throws InterruptedException;
public static void sleep (long millisec, int nanosec) //sleep for x millisec
throws InterruptedException; // and y nanoseconds
Synchronized state
A code within the synchronized block is "atomic". This means only one thread can execute that block of code for a given object at a time. If a thread has started executing this block of code for an object, no other thread can execute this block of the code (or any other block of synchronized code) for the same object.

public synchronized void synchExample() {
/* A set of synchronized statements. Assume
here that x is a data member of this class. */
if(x == 0)
x = 1;
}

Various Classes in Java technology


The Object class
All classes in JavaTM technology are directly or indirectly derived from the Object class. Some of the subclasses of Object class are - Boolean, Number, Void, Math, String, StringBuffer etc.
Some of the important methods defined in the Object class are given below. These methods are available to all Java classes.
  1. boolean equals(Object obj) - The equals method in Object class returns true if two references point to the same object. Some classes like String and Boolean overload this method. 
  2. String toString() - The function is used to convert objects to String. If a subclass does not override this method, the method returns a textual representation of the object, which has the following format : @".
  3. The following methods related to threads are also defined in Object class -
    void notify()
    void notifyall()
    void wait(long timeout) throws InteruptedException
    void wait(long timeout, int nanosec) throws InteruptedException
    void wait() throws InteruptedException
Wrapper classes
Corresponding to all the primitive types Java technology defines wrapper classes. Some examples of these wrapper classes are - Character, Boolean, Integer, Double.
Important methods in the Math class
Some of the methods defined in the Math class are used frequently. These are explained below. Besides the functionality, it is important to understand the arguments and return type of these functions.static double ceil(double(d)) : The method ceil returns the smallest double value equal to a mathematical integer, that is not less than the argument. For example,


ceil(3.4) returns 4.0

ceil(-2.3) returns -2.0

ceil(3.0) returns 3.0

static double floor(double(d)) : The method floor returns the largest double value equal to a mathematical integer, that is not greater than the argument. For example,


floor(3.4) returns 3.0

floor(-2.3) returns -3.0

floor(3.0) returns 3.0

static int round (float f) and static long round(double d) : The method round returns the integer closest to the argument.


round(3.7) returns 4

round(3.2) returns 3

round(3.0) returns 3

round(-3.1) returns -3

String class
The String class is used to implement immutable character strings. This means that the character string cannot be changed once it has been created. Some of the important methods are explained below.int length() - The number of characters in the String class are returned by the length() method. String substring(int startIndex) String substring(int startIndex, int endIndex) The method substring extracts a substring from a string. The method extracts a string from the startIndex to the index endIndex - 1. If endIndex is not specified then string till the end of input string is returned. The example below illustrates this


String str = "I am a string";

int len = str.length();

String str2 = str.substring(2,5);

After the above statements str2 contains the string "am ". The string str still has the same value "I am a string". The variable len has value 13.
StringBuffer class
The StringBuffer class implements mutable strings. This means that the characters stored in the string and the capacity of the string can be changed.
Garbage Collection
Java technology's Garbage collection is complex. In this section I am only giving a brief overview of Garbage Collection. Java technology supports automatic garbage collection. This means that the programmer does not need to free the memory used by objects. Java technology's runtime environment can claim the memory from the objects that are no longer in use. Objects that are not being referred become candidates for garbage collection. It is important to note that these objects are candidates only. Java technology does not guarantee that Garbage collection would happen on these objects. Before actually freeing up the memory, garbage collector invokes the finalize() method of the Object being freed. The System.gc() method can be invoked by the program to suggest to Java technology that the Garbage Collector be invoked. However there is no guarantee when the garbage collection would be invoked. There is also no guarantee on the order in which objects will be garbage collected. The example illustrates when a string Object becomes available for Garbage Collection.


public class GCTest {

public static void main(String args[]) {

String a,b;

String c = new String("test");

a = c;

c = null; // The String "test" is not yet

//available for GC as a still points to "test"

b = new String("xyz");

b = c; // String "xyz" is now available for GC.

a = null;

//String "test" is now available for GC.

}

}

Monday, 21 December 2009

Static in java

Static Members
Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references.

Constants
  Static variables are quite rare. However, static constants are more common. For example, the Math class defines a static constant:
public class Math
{
. . .
public static final double PI = 3.14159265358979323846;
. . .
}
You can access this constant in your programs as Math.PI.

If the keyword static had been omitted, then PI would have been an instance field of the Math class. That is, you would need an object of the Math class to access PI, and every Math object would have its own copy of PI.

Another static constant that you have used many times is System.out. It is declared in the System class as:
public class System
{
. . .
public static final PrintStream out = . . .;
. . .
}

As we mentioned several times, it is never a good idea to have public fields, because everyone can modify them. However, public constants (that is, final fields) are ok. Because out has been declared as final, you cannot reassign another print stream to it:
System.out = new PrintStream(. . .); // ERROR--out is final

NOTE:
If you look at the System class, you will notice a method setOut that lets you set System.out to a different stream. You may wonder how that method can change the value of a final variable. However, the setOut method is a native method, not implemented in the Java programming language. Native methods can bypass the access control mechanisms of the Java language. This is a very unusual workaround that you should not emulate in your own programs.

Static Methods
Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression:
Math.pow(x, a)

computes the power x^a. It does not use any Math object to carry out its task. In other words, it has no implicit parameter.

You can think of static methods as methods that don't have a this parameter. (In a non-static method, the this parameter refers to the implicit parameter of the method)

Because static methods don't operate on objects, you cannot access instance fields from a static method. But static methods can access the static fields in their class. Here is an example of such a static method:

public static int getNextId()
{
return nextId; // returns static field
}

To call this method, you supply the name of the class:
int n = Employee.getNextId();

Could you have omitted the keyword static for this method?
Yes, but then you would need to have an object reference of type Employee to invoke the method.

NOTE :
It is legal to use an object to call a static method. For example, if harry is an Employee object, then you can call harry.getNextId() instead of Employee.getnextId(). However, we find that notation confusing. The getNextId method doesn't look at harry at all to compute the result. We recommend that you use class names, not objects, to invoke static methods.

You use static methods in two situations:
• When a method doesn't need to access the object state because all needed parameters are supplied as explicit parameters (example: Math.pow)
• When a method only needs to access static fields of the class (example: Employee.getNextId).

Also see difference between java and c++ static.
Points to note about static.




Tuesday, 15 December 2009

Nesting of classes : Introduction

It is possible to define a class within another class; such classes are known as nested classes.

The scope of a nested class is bounded by the scope of its enclosing class. Also a nested class has access to the members, including private members, of the class in which it is nested. However, the
enclosing class does not have access to the members of the nested class.

Consider the case that class B is defined within class A. So it means:
  • B is known to A, but not outside of A. 
  • B as has access to A's members, including private members.
See types of nested classes .

    Abstract classes

    As seen from the previous example, the superclass is more general than its subclass(es). The superclass contains elements and properties common to all of the subclasses. The previous example was of a concrete superclass that instance objects can be created from. Often, the superclass will be set up as an abstract class which does not allow objects of its prototype to be created. In this case, only objects of the subclass are used. To do this the reserved word abstract is included in the class definition.
    Abstract methods are methods with no body specification. Subclasses must provide the method statements for their particular meaning. If the method was one provided by the superclass, it would require overriding in each subclass. And if one forgot to override, the applied method statements may be inappropriate.

    public abstract class Animal  // class is abstract
    {
      private String name;
      public Animal(String nm)      // constructor method
      { name=nm; }
      public String getName()       // regular method
      { return (name); }
      public abstract void speak(); // abstract method - note no {}
    }


    Abstract classes and methods force prototype standards to be followed (ie. they provide templates).
    See also - Abstract classes : cpp vs java

    Saturday, 12 December 2009

    Access modifiers in Java

    Access modifiers specifies who can access them. There are four access modifiers used in java. They are :
    • public
    • private
    • protected
    • no modifer (declaring without an access modifer). Using ‘no modifier’ is also sometimes referred as ‘package-private’ or ‘default’ or ‘friendly’ access.
    Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.

    I) Class level access modifiers (java classes only)

    Only two access modifiers is allowed, public and no modifier
    • If a class is ‘public’, then it CAN be accessed from ANYWHERE.
    • If a class has ‘no modifer’, then it CAN ONLY be accessed from ‘same package’.

    II) Member level access modifiers (java variables and java methods)

    All the four public, private, protected and no modifer is allowed.
    • public and no modifier – the same way as used in class level.
    • private – members CAN ONLY access.
    • protected – CAN be accessed from ‘same package’ and a subclass existing in any package can access.
    Understanding by the table below

    For better understanding, member level access is formulated as a table:

    Access Modifiers

    Same Class Same Package Subclass Other packages
    public Y Y Y Y
    protected Y Y Y N
    no access modifier Y Y N N
    private Y N N N

    First row {public Y Y Y Y} should be interpreted as:

    • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same class’.
    • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same package’.
    • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘subclass’.
    • Y – A member declared as ‘public’ CAN be accessed from ‘Other packages’.

    Second row {protected Y Y Y N} should be interpreted as:

    • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same class’.
    • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same package’.
    • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘subclass’.
    • N – A member declared with ‘protected’ access modifier CANNOT be accessed by the members of the ‘Other package’.

    similarly interpret the access modifiers table for the third (no access modifier) and fourth (private access modifier) records.

    Examples
    Public Members:
    For a subclass, if a member of its superclass is declared public, the subclass inherits that member regardless of whether both classes are in the same package.

    package pack1;
    public class Parent {
    public String getName() {
    return “Parent”;
    }
    }

    package pack2;
    Import pack1.Parent;
    Public class Child extends Parent{
    Public String getParentsName() {
    return getName();
    }
    }

    If you see the example above, the child class is able to access the parent class’s method getName() even without instantiating an object of the parent because it inherits the Parent class and all its method as part of the inheritance (extends) feature.

    Private Members:
    Members marked private can’t be accessed by code in any class other than the class in which the private member was declared. Let’s make a small change to the Parent class from an earlier example.

    package pack1;
    public class Parent {
    private String getName() {
    return “Parent”;
    }
    }

    Now the getName() method is private and is not visible from within the Child class and the same piece of code would throw up the below compilation error when you try to compile the class.

    cannot find symbol
    symbol : method getName()
    This error method looks as if the method getName() does not exist at all. Of course the method exists but unfortunately it is declared private and hence no class (except the class that has the exact code written into it) can access it. This includes a child class that extends the parent class that has the method.
    Note: You can write a method inside the child class that has the same name as the private method in the parent. This does not account as Overriding because the parent class method is not even visible and hence it is just another method and is not considered overriding.

    Tip: Though you may feel that public is better because all other classes can access your methods, that is seldom the case because a code that is visible to all other classes is not secure and that is not the best way to write your code. It is always best to provide just the appropriate level of access to methods and variables instead of having all of them public.

    Protected and Default Members:
    The protected and default access control levels are almost identical, but with one critical difference. A default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package.
    Take a look at the following two classes:

    package certification;
    public class ClassOne {
    void testIt() { // No modifier means method has default access
    System.out.println("ClassOne");
    }
    }

    In another source code file you have the following:

    package otherCertification;
    import certification.ClassOne;
    class ClassTwo {
    static public void main(String[] args) {
    ClassOne o = new ClassOne();
    o.testIt();
    }
    }

    As you can see, the testIt() method in the first file has default (think: package-level) access. Notice also that class OtherClass is in a different package from the AccessClass. When you compile the ClassTwo.java file you will get an error like below:
    No method matching testIt() found in class
    certification.ClassOne.o.testIt();
    From the preceding results, you can see that AccessClass can’t use the OtherClass method testIt() because testIt() has default access, and AccessClass is not in the same package as OtherClass. So AccessClass can’t see it, the compiler complains.
    Default and protected behavior differs only when we talk about subclasses. If the protected keyword is used to define a member, any subclass of the class declaring the member can access it through inheritance. It doesn’t matter if the superclass and subclass are in different packages, the protected superclass member is still visible to the subclass. This is in contrast to the default behavior, which doesn’t allow a subclass to access a superclass member unless the subclass is in the same package as the superclass. (See the example above)
    Whereas default access doesn’t extend any special consideration to subclasses, the protected modifier respects the parent-child relationship, even when the child class moves away (and joins a new package). So, when you think of default access, think of package restrictions. No exceptions at all. But when you think protected, think package + kids. A class with a protected member is marking that member as having package-level access for all classes, but with a special exception for subclasses outside the package.


    Tip: Remember that Default and Protected access is the same as long as inheritance is not involved.


    Local Variables and Access Modifiers

    Can access modifiers be applied to local variables? A BIG NO!
    There is never a case where an access modifier can be applied to a local variable, so watch out for code like the following:


    class Test {
    void doTest() {
    private int x = 7; //Not Possible
    this.doSomethingElse(x);
    }
    }

    The above code will not compile or run. Dont think that the private keyword is legal inside the method doTest().
    You can be certain that any local variable declared with an access modifier will not compile. In fact, there is only one modifier that can ever be applied to local variables—final.