Collections

 

Collections
A Collection allows a group of objects to be treated as a single unit. Collections define a set of core interfaces. These are -

  • Collection
  • Set
  • List
  • SortedSet
  • Map
  • SortedMap

Collections also provide implementation for these interfaces.

Core Interfaces
The Object hierarchy of Core Interfaces defined in Collections is given below.
Figure: Core Interfaces of Collections
Collection Interface
The Collection interface is the root of Collection hierarchy, and is used for common functionality across all collections. There is no direct implementation of Collection interface.
Set Interface
The Set interface is used to represent a group of unique elements. It extends the Collection interface. The class HashSet implements the Set interface.
SortedSet Interface
The SortedSet interface extends the Set interface. It provides extra functionality of keeping the elements sorted. So SortedSet interface is used to represent collections consisting of unique, sorted elements. The class TreeSet is an implementation of interface SortedSet.
List Interface
The list interface extends the Collection interface to represent sequence of numbers in a fixed order. Classes ArrayList, Vector and LinkedList are implementation of List interface.
Map Interface
The Map Interface is a basic interface that is used to represent mapping of keys to values. Classes HashMap and Hashtable are implementations of Map interface.
SortedMap Interface
The SortedMap Interface extends Map interface and maintains their mappings in key order. The class TreeMap implements SortedMap interface.

The table below gives the list of Collection interfaces and the classes that implement them.

Interface Class Implementation
Set HashSet
SortedSet TreeSet
List ArrayList, Vector, LinkedList
Map HashMap, Hashtable
SortedMap TreeMap

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)
            throws InterruptedException;
public static void sleep (long millisec, int nanosec)
            throws InterruptedException;
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;
}

File Handling

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);
<!–more–>
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.

read and write methods
InputStream class defines the following methods for reading bytes -
int read() throws IOException
int read(byte b[]) throws IOException
int 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 IOException
void write(byte b[]) throws IOException
void 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
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.
CharArrayReader The class supports reading of characters from a character array.
InputStreamReader The class supports reading of characters from a byte input stream. A character encoding may also be specified.
FileReader The class supports reading of characters from a file using default character encoding.

The table below gives a brief overview of key Writer classes.
CharArrayWriter The class supports writing of characters from a character array.
OutputStreamReader The class supports writing of characters from a byte output stream. A character encoding may also be specified.
FileWriter The 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

Declaration and Access Control

Array Fundamentals
Arrays are used to represent fixed number of elements of the same type. The following are legal syntax for declaring one-dimensional arrays.

int anArray[];
int[] anArray;
int []anArray;

It is important to note that the size of the array is not included in the declaration. Memory is allocated for an array using the new operator as shown below.
anArray = new int[10];
The declaration and memory allocation may be combined together as shown below.
int anArray[] = new int[10];
The elements of the array are implicitly initialized to default values based on array types (0 for integral types, null for objects etc.). This is true for both local arrays as well as arrays which are data members. In this respect arrays are different from normal variables. Variable defined inside a method are not implicitly initialized, where as array elements are implicitly initialized.

Array Initializations
Arrays are initialized using the syntax below
int intArray[] = {1,2,3,4};
The length operator can be used to access the number of elements in an array (for example – intArray.length).

Multidimensional Arrays
The following are legal examples of declaration of a two dimensional array.
int[] arr[];
int[][] arr;
int arr[][];
int []arr[];

When creating multi-dimensional arrays the initial index must be created before a later index. The following examples are legal.

int arr[][] = new int[5][5];
int arr[][] = new int[5][];

The following example will not compile;
int arr[][] = new int[][5];

Class Fundamentals
A class defines a new type and contains methods and variables. The example below illustrates a simple class.

class City {
String name; // member variable
String getName() // member method
{
return name;
}
public static void main(String arg[]) {
}
}

Method overloading
JavaTM technology allows two methods to have the same name as long as they have different signatures. The signature of a method consists of name of the method, and count and type of arguments of the method. Thus as long as the argument types of two methods are different, they may be over-loaded (have the same name).

Class constructors
Constructors are member methods that have same name as the class name. The constructor is invoked using the new operator when a class is created. If a class does not have any constructors then Java language compiler provides an implicit default constructor. The implicit default constructor does not have any arguments and is of the type -
class_name() { }

If a class defines one or more constructors, an implicit constructor is not provided. The example below gives a compilation error.

class Test {
int temp;
Test(int x) {
temp = x;
}
public static void main() {
Test t = new Test(); /* This would generate a
compilation error, as there is no constructor
without any arguments. */
}
}

Operators and Assignments

Operators and Assignments

Commonly used operators
Following are some of the commonly used JavaTM technology operators – Multiplication (*), Addition (+), Subtraction (-), logical and (&&) Conditional Operator ?:, Assignment (=), left shift (<<), right shift (>> and >>>), Equality comparison (==), Non-equality comparison (!=).

Conversion rules in Assignments
In the description below, I am giving basic conversion rules for assignment when source and destination are of different types.

If source and destination are of the same type, assignment happens without any issues.
If source is of smaller size than destination but source and destination are of compatible types, then no casting is required. Implicit widening takes place in this case. An example is assigning an int to a long.
If source and destination are of compatible types, but source is of larger size than destination, explicit casting is required. In this case, if no casting is provided then the program does not compile.

Floating point numbers
Decimal numbers (for example 1.3) are of type double by default. To make them of type float they must be followed by F (say, 1.3F).

The equality operator
The equality operator (==) when applied to objects return true if two objects have same reference value, false otherwise. The example below illustrates this –

String str1 = “first string”;
String str2 = new String(“first string”);
String str3 = “first string”;
boolean test1 = (str1 == str2);
boolean test2 = (str1 == str3);

In the example above, test1 is set to false because str1 and str2 point to different references. As str1 and str3 point to the same reference, test2 gets set to true. When a string is initialized without using the new operator, and with an existing string, then the new string also points to the first string’s location. So in the example above, str1 and str3 point to the same pool of memory and hence test2 gets set to true. The string str2 on the other hand is created using the new operator and hence points to a different block of memory. Hence test1 gets set to false.

The conditional operators && and ||
Operator && returns true if both operands are true, false otherwise. Operator || returns false if both operands are false, true otherwise. The important thing to note about these operators is that they are short-circuited. This means that the left operand is evaluated before the right operator. If the result of the operation can be evaluated after computing the left operand, then the right side is not computed. In this respect these operators are different from their bit-wise counterparts – bit-wise and (&), and bit-wise or (|). The bit-wise operators are not short-circuited. This means both the operands of bit-wise operator are always evaluated independent of result of evaluations.

Storing integral types
All the integer types in Java technology are internally stored in two’s complement. In two’s complement, positive numbers have their corresponding binary representation. Two’s complement representation of negative numbers is generated using the following three step process -

First get the binary representation of the number.
Then interchange zeros and ones in the binary representation.
Finally add one to the result. So for example two’s complement of -18 would be (assuming one byte representation) -
Converting 18 to binary — 0001 0010
Interchanging 0s and 1s — 1110 1101
Adding 1 — 1110 1110

So 1110 1110 would be binary representation of -18 using two bytes and using two’s complement representation.

The shift operators
The shift left operator in Java technology is “<<”. There are two operators for doing the right shift – signed right shift (>>) and zero fill right shift (>>>).

The left shift operator fills the right bits by zero. The effect of each left shift is multiplying the number by two. The example below illustrates this -

int i = 13; // i is 00000000 00000000 00000000 0000 1101
i = i << 2; // i is 00000000 00000000 00000000 0011 0100 After this left shift, i becomes 52 which is same as multiplying i by 4 Zero fill shift right is represented by the symbol >>>. This operator fills the leftmost bits by zeros. So the result of applying the operator >>> is always positive. (In two’s complement representation the leftmost bit is the sign bit. If sign bit is zero, the number is positive, negative otherwise.) The example below illustrates applying the operator >>> on a number.

int b = 13; // 00000000 00000000 00000000 0000 1101
b = b >>> 2; // b is now 00000000 00000000 00000000 0000 0011

So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explains the effect of applying the operator >>> on a negative number.

int b = -11; //11111111 11111111 11111111 1111 0101
b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101

So the result of applying zero fill right shift operator with operand two on -11 is 1073741821.

Signed right shift operator (>>) fills the left most bit by the sign bit. The result of applying the signed shift bit has the same sign as the left operand. For positive numbers the signed right shift operator and the zero fill right shift operator both give the same results. For negative numbers, their results are different. The example below illustrates the signed right shift.

int b = -11; // 11111111 11111111 11111111 1111 0101
b = b >> 2; // 11111111 11111111 11111111 1111 1101 (2′s complement of -3)
// Here the sign bit 1 gets filled in the two most significant bits.

The new value of b becomes -3.

LANGUAGE FUNDAMENTALS

Language Fundamentals
 

  1. Identifiers are names of variables, functions, classes etc. The name used as an identifier must follow the following rules in JavaTMtechnology.
    • Each character is either a digit, letter, underscore(_) or currency symbol ($,¢, £ or ¥)
    • First character cannot be a digit.
    • The identifier name must not be a reserved word.
  2. A keyword or reserved word in Java technology has special meaning and cannot be used as a user defined identifier. The list of keywords in Java technology is given below. It is important to completely remember this list as you can expect a question in Java Certification exam related to this.
    abstract boolean break byte case catch
    char class const continue default do
    double else extends final finally float
    for goto if implements import instanceof
    int interface long native new null
    package private protected public return short
    static strictfp super switch synchronized this
    throw throws transient try void volatile
    while assert enum


    It is important to note the following

    1. const and goto are not currently in use.
    2. null, true, and false are reserved literals but can be considered as reserved words for the purpose of exam.
    3. It is important to understand that Java language is case-sensitive. So even though super is a keyword, Super is not.
    4. All the Java technology keywords are in lower case.
    5. strictfp is a new keyword added in Java 1.2. assert is added in Java 1.4 and enum in Java 5.0
    6. The list of keywords as defined by Sun is present here.
  3. A literal in Java technology denotes a constant value. So for example 0 is an integer literal, and ‘c’ is a character literal. The reserved literals true and false are used to represent boolean literals. “This is a string” is a string literal.
  4. Integer literals can also be specified as octal (base 8), or hexadecimal (base 16). Octal and hexadecimal have 0 and 0x prefix respectively. So 03 and 0×3 are representation of integer three in octal and hexa-decimal respectively.
  5. Java technology supports three type of comments
    1. A single line comment starting with //
    2. A multi-line comment enclosed between /* and */
    3. A documentation or javadoc comment is enclosed between /** and */. These comments can be used to generate HTML documents using the javadoc utility, which is part of Java language.
  6. Java technology supports the following primitive types – boolean (for representing true or false), a character type called char, four integer types (byte, short, int and long) and two floating point types (float and double). The details of these types are given below -
    Data types Width (in bytes) Minimum value Maximum Value
    byte 1 -27 27 – 1
    short 2 -215 215-1
    int 4 -231 231 – 1
    long 8 -263 263 – 1
    char 2 0×0 0xffff
    float 4 1.401298e-45 3.402823e+38
    double 8 4.940656e-324 1.797693e+308
  7. Corresponding to all the primitive type there is a wrapper class defined. These classes provide useful methods for manipulating primitive data values and objects.
    Data types Wrapper class
    int Integer
    short Short
    long Long
    byte Byte
    char Character
    float Float
    double Double
  8. Instance variables (data members of a class) and static variables are initialized to default values. Local variables (i.e. variables defined in blocks or inside member functions) are not initialized to default values. Local variables must be explicitly initialized before they are used. If local variables are used before initialization, compilation error gets generated. The defaults for static and instance variables are given in the table below.
    Data types Default Values
    boolean false
    char ‘\u0000′
    Integer types (byte, short, int, long) 0
    Floating types (float, double) 0.0F or 0.0 D
    Object References null

     public static void main(String args[]) { int i; System.out.println(i); } 

    In this example printing of i generates a compilation error because local variable i is used before being initialized. The initialization of instance and static variables is an important concept both for understanding of Java language, and for Java Certification exam.

  9. A Java source file has the following elements in this specific order.
    • An optional package statement. All classes and interfaces defined in the file belong to this package. If the package statement is not specified, the classes defined in the file belong to a default package. An example of a package statement is -
      package testpackage;
    • Zero or more import statements. The import statement makes any classes defined in the specified package directly available. For example if a Java source file has a statement importing the class “java.class.Button”, then a class in the file may use Button class directly without providing the names of the package which defines the Button class. Some examples of import statement are -
      import java.awt.*; // All classes in the awt package are imported.
      import java.applet.Applet;
    • Any number of class and interface definitions may follow the optional package and import statements.

    If a file has all three of the above constructs, they must come in the specific order of package statement, one or more import statements, followed by any number of class or interface definitions. Also all the above three constructs are optional. So an empty file is a legal Java file.

  10. The Java interpreter executes a method called main, defined in the class specified in command line arguments. The main method is the entry point for execution of a class. In Java technology the main method must have the following signature -
    public static void main(String args[])
    The java interpreter is invoked with the name of the class as an argument. The class name is followed by possible set of arguments for the main function of the class. When a Java program is invoked then the Java interpreter name “java” and the class name are not passed to the main() method of the class. The rest of the command line arguments are passed as an array of String. For example invoking java Sky blue gray
    would invoke main method of Sky class with an array of two elements – blue and gray

A PHP Tutorial

PHP is an excellent server-side technology for dynamic webpage generation. Within a span of few years, it has gained immense popularity among developers. This excellent 5-Part tutorial written by Luigi Arlotta explains the basics of PHP programming. His style is so simple that even absolute beginners would have no trouble following this tutorial. This tutorial is targeted at those users who may have never programmed using any language before. Also programmers who have experience in other languages can quickly browse through this series and get their PHP code running within minutes… Introduction PHP stands for “PHP: Hypertext Preprocessor”. PHP is a scripting language through which you can generate web pages dynamically. PHP code is directly inserted in HTML documents through specific TAGs declaring the code presence and then executed when a client demands the page. PHP is a server-side language, that’s to say that PHP code is directly executed by the server, while the client receives processed results as an HTML document. This way of working is different from that of other scripting languages as JavaScript, whose code is first loaded onto the client machine and then executed by the client (the browser). A few points to note about PHP programming – 1. All compatibility problems existing between different browsers are completely solved. The Client’s browser, receives a normal HTML page after the execution of a PHP code on the server, and so it is always able to display it correctly since it deals with only HTML. This does not happen with scripting languages interpreted by the client’s browser. In this case the client downloads the script code and tries to process it on the local machine. This procedure works correctly only if the client is equipped with the right software (generally called plugins or built-in support in the browser). 2. The server side code processing sees to it that the script code is never visible to the clients. That prevents “thefts” of source code. 3. The server side code execution requires that your webserver has been well configured. It must be able to recognize HTML documents containing PHP code. In order to make this, it is necessary to install a PHP engine and to edit some lines in the webserver’s configuration file. 4. Server side code processing needs resources (CPU time) for generating the dynamic pages. A high number of client requests could overload the server. But generally today’s servers such as Apache are made stable enough to handle a relatively large number of clients. To make the webserver differentiate between HTML documents containing PHP code and normal HTML pages, .php, .php4 or .phtml extensions are used in place of the .html . These extensions can change according to the webserver configuration. We shall stick to the standard .php extension. Assume that a client requests the following page (example1.php). The source code for the file is shown belowThis page will be recognized, thanks to the extension from which it is characterized and it will be processed as a HTML document containing PHP code by the server. The code is interpreted before the output is sent to the client. The webserver passes this page through the PHP engine which processes it and executes the PHP instructions in the code. It then substitutes the result of the execution in place of the original PHP code. Once processed by the PHP engine, the webserver then transmits this dynamically generated page to the client. The client receives the following HTML document

This is an example

As you see, in the document sent by the web server to the client there is no sign of PHP code. The code has been interpreted/processed and replaced with HTML lines. The client will never be able to deduce what code generated the particular HTML lines. PHP instructions are placed inside special TAGsThese tags allow the PHP engine to distinguish the PHP syntax from the rest of the document. It is possible to use different TAGs editing the engine configuration file php.ini . We shall stick to the most common ones – the ones shown above. Necessary Setup to Run PHP on your machine To start writing and testing your PHP scripts you need a webserver and a PHP engine. The PHP engine must be combined with the webserver so that the webserver can process the PHP code in your pages. As far as webservers are concerned, on the Linux platform – Apache rules. It is probably the most used webserver at the moment. You can download Apache from www.apache.org. The PHP engine (release 3 or 4) can here be downloaded from www.php.net You could learn how to configure Apache to run PHP with the help of the manual that you would be provided or you could search for articles on Tips For Linux itself. First steps My first PHP script consists of the classic program that displays the famous ” HELLO WORLD “. Copy the code shown below, paste and save it in a file with the name helloworld.php in your webserver standard directory (or in the webserver’s php files directory).Then start your web browser and type the following in the address bar – http://127.0.0.1/helloworld.php or http://127.0.0.1/~username/helloworld.php Note : In case you have not yet configured Apache Server you could read Article No. 29 which explains Apache Server’s configuration. Once you Apache Server is configured, you could continue with this article. If it works correctly you can proceed and read the rest of this tutorial, otherwise you would have to do some more tweaking and get PHP configured on your machine. If you can’t solve the problem, before abandoning, try to have a look to the software documentation. Even try posting your problem on discussion forums on the Web. You will definitely find a solution. Variables A variable is a block of memory, accessible through a name chosen by the software developer, in which a value is stored. This value, is usually given a default value at the beginning of the application, and you can change that value during the execution of the program. PHP requires variable names to begin with the dollar ‘ $ ‘ character. Variable names can be composed of uppercase and lowercase letters, digits and underscores. But it is not possible to include spaces or other special or reserved characters to define the names of a variable. Remember that PHP is a case-sensitive language. This means it distinguishes between uppercase and lowercase variable names. For instance, if we write the following script. The code below shows the case sensitive aspect of PHP.We’ll get an error message because the PHP interpreter does not find $var1 variable (The variable defined initially was $VAR1). A script involving variable declarations and displaying the values of those variables is shown below. Read it carefully because it contains some important points that we will discuss later.The program defines and prints the variable $website. Observe that in the echo() function, whose purpose is to write a string on the screen, two different kinds of inverted commas are used – they are the single and double ones. Important : In this tutorial we will refer to the double inverted commas (“) as only inverted commas and we will refer to single inverted commas (‘) as only quotes. The main difference between these two types of syntax is that PHP interprets what is enclosed in the inverted commas, while everything appearing between quotes is considered a constant value and it is not interpreted. The example given above produces the following output Surf to: http://www.bitafterbit.com Surf to: $website The text $website is in fact interpreted and replaced with the value of the corresponding variable only in the first echo() statement. This because in the first statement we have used inverted commas to enclose the text to print. The result of this first instruction is Surf to: http://www.bitafterbit.com As explained previously, in the second echo() statement, where quotes have been used in place of inverted commas, the enclosed text is not interpreted, because it is considered to be a constant. The output of the second echo() instruction therefore is Surf to: $website It is important to take notice of this important characteristic of PHP. It is different from other programming languages where all that appears enclosed between inverted commas is considered a constant value (a string). We will talk about strings in detail in later articles when we’ll discuss PHP’s datatypes.

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!