Saturday, November 16, 2013

Deserializing an Object in Java

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:

import java.io.*;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn =
new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println(.Employee class not found.);
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}

Serializing an Object in Java

The ObjectOutputStream class is used to serialize an Object. The following Serialize Demo program instantiates an Employee object and serializes it to a file. When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.

Note: When serializing an object to a file, the standard convention in Java is to give the file a.ser extension.

import java.io.*;
public class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("employee.ser");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
}
}

Data Structures (Properties) in Java

Example: Properties
The following program illustrates several of the methods supported by this data structure:

import java.util.*;
public class PropDemo {
public static void main(String args[]) {
Properties capitals = new Properties();
Set states;
String str;
capitals.put("Illinois", "Springfield");
capitals.put("Missouri", "Jefferson City");
capitals.put("Washington", "Olympia");
capitals.put("California", "Sacramento");
capitals.put("Indiana", "Indianapolis");
states = capitals.keySet();
Iterator itr = states.iterator();
while(itr.hasNext()) {
str = (String) itr.next();
System.out.println("The capital of " +
str + " is " + capitals.getProperty(str) + ".");
}
System.out.println();
str = capitals.getProperty("Florida", "Not Found");
System.out.println("The capital of Florida is "
+ str + ".");
}
}

Data Structures(Hashtable) in Java

Example: Hashtable
The following program illustrates several of the methods supported by this data structure:

import java.util.*;
public class HashTableDemo {
public static void main(String args[]) {
Hashtable balance = new Hashtable();
Enumeration names;
String str;
double bal;
balance.put("Zara", new Double(3434.34));
balance.put("Mahnaz", new Double(123.22));
balance.put("Ayan", new Double(1378.00));
balance.put("Daisy", new Double(99.22));
balance.put("Qadir", new Double(-19.08));
// Show all balances in hash table.
names = balance.keys();
while(names.hasMoreElements()) {
str = (String) names.nextElement();
System.out.println(str + ": " +
balance.get(str));
}
System.out.println();
bal = ((Double)balance.get("Zara")).doubleValue();
balance.put("Zara", new Double(bal+1000));
System.out.println("Zara's new balance: " +
balance.get("Zara"));
}
}

Data Structures(Dictionary) in Java

Java Data Structures(Dictionary)
Map has its implementation in various classes like HashMap, Following is the example to explain map functionality:

import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
m1.put("Daisy", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}

Data Structures(Stack ) in Java

Example: Stack
The following program illustrates several of the methods supported by this collection:

import java.util.*;
public class StackDemo {
static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}

Data Structures (Vector) in Java

Example: Vector
The following program illustrates several of the methods supported by this collection:

import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}

Data Structures(BitSet) in Java

Example: BitSet
The following program illustrates several of the methods supported by this data structure:

import java.util.BitSet;
public class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
for(int i=0; i<16; i++) {
if((i%2) == 0) bits1.set(i);
if((i%5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}

Data Structures in Java

The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes:
  • Enumeration
  • BitSet
  • Vector
  • Stack
  • Dictionary
  • Hashtable
  • Properties

Example: Enumeration
Following is the example showing usage of Enumeration.

import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
}

Packages in Java

Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching, locating and usage of classes, interfaces, enumerations and annotations easier etc. A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.

Creating a package:
When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.

Example:
Let us look at an example that creates a package called animals. It is common practice to use lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:

/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now put an implementation in the same package animals:
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Interfaces in Java

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

Example:
Let us look at an example that depicts encapsulation:

/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:
An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

Methods in an interface are implicitly public.

Example:
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Encapsulation Method in Java

Encapsulation is one of the four fundamental OOP concepts in Java. The other three are inheritance, polymorphism, and abstraction. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface. The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code.

Example:
Let us look at an example that depicts encapsulation:

/* File name : EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}

The public methods are the access points to this class's fields from the outside java world. Normally these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters. The variables of the EncapTest class can be access as below:

/* File name : RunEncap.java */
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}
}

Polymorphism in Java

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Any java object that can pass more than one test is considered to be polymorphic. In Java, all java objects are polymorphic since any object will pass the test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared the type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

Virtual Methods:
In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.

We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.

/* File name : Employee.java */
public class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

Inheritance in Java

Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.

When we talk about inheritance the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

IS-A Relationship:
This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}

Example:public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

Creating Directories in Java

There are two useful File utility methods which can be used to create directories:

The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.

The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory:

import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}

Reading Directories
A directory is a File that contains a list of other files and directories. When you create a File object and it is a directory, the isDirectory( ) method will return true.

You can call list( ) on that object to extract the list of other files and directories inside. The program shown here illustrates how to use list( ) to examine the contents of a directory:

import java.io.File;
public class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}

File Writer Class in Java

This class inherits from the OutputStreamWriter class. The class is used for writing streams of characters.
This class has several constructors to create required objects.

Following syntax creates a FileWriter object given a File object.
FileWriter(File file)

Following syntax creates a FileWriter object given a File object.
FileWriter(File file, boolean append)

Following syntax creates a FileWriter object associated with a file descriptor.
FileWriter(FileDescriptor fd)

Following syntax creates a FileWriter object given a file name.
FileWriter(String fileName)

Following syntax creates a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
FileWriter(String fileName, boolean append)

Example:
Following is the example to demonstrate class:

import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
}
}

File Reader Class in Java

This class inherits from the InputStreamReader class. FileReader is used for reading streams of characters. This class has several constructors to create required objects.

Following syntax creates a new FileReader, given the File to read from.
FileReader(File file)

Following syntax creates a new FileReader, given the FileDescriptor to read from.
FileReader(FileDescriptor fd)

Following syntax creates a new FileReader, given the name of the file to read from.
FileReader(String fileName)

Once you have FileReader object in hand then there is a list of helper methods which can be used manipulate the files.


Example:
Following is the example to demonstrate class:
import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
}
}

File Output Stream in Java

FileOutputStream is used to create a file and write data into it.The stream would create a file, if it doesn't already exist, before opening it for output. Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file. First we create a file object using File() method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

DataOutputStream
The DataOutputStream stream let you write the primitives to an output source. Following is the constructor to create an DataOutputStream.
DataOutputStream out = DataOutputStream(OutputStream out);

Example:
Following is the example to demonstrate DataInputStream and DataInputStream. This example reads 5 lines given in a file test.txt and convert those lines into capital letters and finally copies them into another file test1.txt.
import java.io.*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream d = new DataInputStream(new
FileInputStream("test.txt"));
DataOutputStream out = new DataOutputStream(new
FileOutputStream("test1.txt"));
String count;
while((count = d.readLine()) != null){
String u = count.toUpperCase();
System.out.println(u);
out.writeBytes(u + " ,");
}
d.close();
out.close();
}
}

File inputStream in Java

As we discussed earlier, A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy of classes to deal with Input and Output streams.
The two important streams are FileInputStream and FileOutputStream which would be discussed in this tutorial:

FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the file:
InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

DataInputStream
The DataInputStream is used in the context of DataOutputStream and can be used to read primitives.
Following is the constructor to create an InputStream:
InputStream in = DataInputStream(InputStream in);

Example:
Following is the example to demonstrate DataInputStream. This example reads 5 lines given in a file test.txt and converts those lines into capital letters and finally copies them into another file test1.txt.

import java.io.*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream d = new DataInputStream(new
FileInputStream("test.txt"));
DataOutputStream out = new DataOutputStream(new
FileOutputStream("test1.txt"));
String count;
while((count = d.readLine()) != null){
String u = count.toUpperCase();
System.out.println(u);
out.writeBytes(u + " ,");
}
d.close();
out.close();
}
}

Friday, November 15, 2013

Date Formatting using printf in Java

Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table given below. For example:

import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
String str = String.format("Current Date/Time : %tc", date );
System.out.printf(str);
}
}

This would produce following result:
Current Date/Time : Sat Dec 15 16:37:57 MST 2012

It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted.
The index must immediately follow the %, and it must be terminated by a $. For example:

import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.printf("%1$s %2$tB %2$td, %2$tY",
"Due date:", date);
}
}

This would produce following result:
Due date: February 09, 2004

Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again. For example:

import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display formatted date
System.out.printf("%s %tB %<te, %<tY", "Due date:", date);
}
}

This would produce following result:
Due date: February 09, 2004

Parsing Strings into Dates in Java

The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string according to the format stored in the given SimpleDateFormat object. For example:

import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
String input = args.length == 0 ? "1818-11-11" : args[0];
System.out.print(input + " Parses as ");
Date t;
try {
t = ft.parse(input);
System.out.println(t);
} catch (ParseException e) {
System.out.println("Unparseable using " + ft);
}
}
}

A sample run of the above program would produce following result:

$ java DateDemo
1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818
$ java DateDemo 2007-12-01
2007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007

Using Methods in Java

A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println method, for example, the system actually executes several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.

Creating a Method:

In general, a method has the following syntax:

modifier returnValueType methodName(list of parameters) {
// Method body;
}

A method definition consists of a method header and a method body. Here are all the parts of a method:

Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.

Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.

Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.

Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

Method Body: The method body contains a collection of statements that define what the method does.

Example:
Here is the source code of the above defined method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two:

/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

Java Files and I/O

Java io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Java does provide strong, flexible support for I/O as it relates to files and networks but this tutorial covers very basic functionlity related to streams and I/O. We would see most commonly used example one by one:

Reading Console Input:
Java input console is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream.

Here is most common syntax to obtain BufferedReader:

BufferedReader br = new BufferedReader(new)
InputStreamReader(System.in));

Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( ) method to read a string from the console.

Reading Characters from Console:

To read a character from a BufferedReader, we would read( ) method whose sytax is as follows:

int read( ) throws IOException

Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns .1 when the end of the stream is encountered. As you can see, it can throw an IOException.

The following program demonstrates read( ) by reading characters from the console until the user types a "q":

// Use a BufferedReader to read characters from the console.
import java.io.*;
public class BRRead {
public static void main(String args[]) throws IOException
{
char c;
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}

Reading Strings from Console in Java

To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its general form is shown here:

String readLine( ) throws IOException

The following program demonstrates BufferedReader and the readLine( ) method. The program reads and displays lines of text until you enter the word "end":

// Read a string from console using a BufferedReader.

import java.io.*;
public class BRReadLines {
public static void main(String args[]) throws IOException
{
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("end"));
}
}


Here is a sample run:

Enter lines of text.

Enter 'end' to quit.

This is line one

This is line one

This is line two

This is line two

end

end

Writing Console Output in Java

Console output is most easily accomplished with print( ) and println( ), described earlier. These methods are defined by the class PrintStream which is the type of the object referenced bySystem.out. Even though System.out is a byte stream, using it for simple program output is still acceptable.

Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here:

void write(int byteval)

This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written.

Example:

Here is a short example that uses write( ) to output the character "A" followed by a newline to the screen:
import java.io.*;
// Demonstrate System.out.write().
public class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}

Arrays in Java

Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:

dataType[ ] arrayRefVar; // preferred way.
or
dataType arrayRefVar[ ]; // works but not preferred way.

Example:
The following code snippets are examples of this syntax:
double[ ] myList; // preferred way.
or
double myList[ ]; // works but not preferred way.

Arrays:When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Example:
Here is a complete example of showing how to create, initialize and process arrays:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

Nested if else Statement in Java

It is always legal to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement.
Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}

You can nest else if...else in the similar way as we have nested if statement.
Example:
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}

Decision making statements in Java

There are two types of decision making statements in Java. They are:
  1. if statements
  2. switch statements
if Statement: An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

If the boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement will be executed.

Example:
public class Test
{
public static void main(String args[])
{
int x = 10; if( x < 20 )
{
System.out.print("This is if statement");
}
}
}


if...else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax:
if(Boolean_expression)
{
//Executes when the Boolean expression is true
}
Else
{
//Executes when the Boolean expression is false
}

Example:
public class Test
{
public static void main(String args[])
{
int x = 30;
if( x < 20 )
{
System.out.print("This is if statement");
}
Else
{
System.out.print("This is else statement");
}
}
}

Thursday, November 14, 2013

For Loop in Java

For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated.

Syntax:
for(initialization; Boolean_expression; update)
{
//Statements
}

Here is the flow of control in a for loop:
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates.

Example:
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}


Enhanced for loop in Java
As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:
for(declaration : expression)
{
Statements;
}
Declaration : The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
Expression: This evaluate to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Example:
public class Test {
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"Ram", "Kailash", "Ankith", "John"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}


The 'break' Keyword
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.
Syntax:
break;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}


The continue Keyword
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax:
continue;

Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}

Looping Statements in Java

In a situation when we need to execute a number of statements in Java program to be executed several number of times, and this type of operation is referred to as a loop. Java has three looping statements to be used in Java programming the looping statements are given below:
  • while Loop
  • do...while Loop
  • for Loop
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:
while(Boolean_expression)
{
Statements
}

Example:
public class Test
{
public static void main(String args[])
{
int x = 10;
while( x < 20 )
{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:
do
{
Statements
}
while(Boolean_expression);

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Example:
public class Test {
public static void main(String args[])
{
int x = 10;
do
{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
while( x < 20 );
}
}

Basic Operators in Java

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
  • Arithmetic Operators
  • Relational Operators
  • Bitwise Operators
  • Logical Operators
  • Assignment Operators
Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:
OperatorDescription
+Addition
-Subtraction
*Multiplication
/Division
%Modulus
++Increment
--Decrement

The Relational Operators:

There are following relational operators supported by Java language
OperatorDescription
==Is equal
!=Not equal
>Greater than
<Less than
>=Greater than equal to
<=Less than equal to
The Bitwise Operators:

Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte.
OperatorDescription
&Binary AND Operator
|Binary OR Operator
^Binary XOR Operator
~Binary Ones Complement Operator
<<Binary Left Shift Operator.
>>Binary Right Shift Operator.
>>>Shift right zero fill operator.
Logical Operators:

The following table lists the logical operators:
OperatorDescription
&&Called Logical AND  operator
||Called Logical OR  operator.
!Called Logical NOT  operator.
The Assignment Operators:

There are following assignment operators supported by Java language:
OperatorDescription
=Simple assignment operator, Assigns values from right side operands to left side operand
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
<<=Left shift AND assignment operator
>>=Right shift AND assignment operator
&=Bitwise AND assignment operator
^=bitwise exclusive OR and assignment operator
|=bitwise inclusive OR and assignment operator

Modifiers Types in Java

Modifiers are keywords that you add to those definitions to change their meanings.
The Java language has a wide variety of modifiers, including the following:

1. Java Access Modifiers
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:
  • Visible to the package. the default. No modifiers are needed.
  • Visible to the class only (private).
  • Visible to the world (public).
  • Visible to the package and all subclasses (protected).
Default Access Modifier No keyword:
Default access modifier means we do not explicitly declare an access modifier for a class, field, method etc.
A variable or method declared without any access control modifier is available to any other class in the same package. The default modifier cannot be used for methods, fields in an interface.
Example:
String version = "1.5.1";
boolean processOrder() {
return true;
}

Private Access Modifier Private:
Methods, Variables and Constructors that are declared private can only be accessed within the declared lass itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in the class.

Example:
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}

Public Access Modifier Public:
A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the public class still need to be imported.

Example:
public static void main(String[] arguments) {
// ...
}

Protected Access Modifier Protected:
Variables, methods and constructors which are declared protected in a super class can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Example:
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
}
}

Access Control and Inheritance:
The following rules for inherited methods are enforced:
  • Methods declared public in a super class also must be public in all subclasses.
  • Methods declared protected in a super class must either be protected or public in subclasses; they cannot be private.
  • Methods declared without access control (no modifier was used) can be declared more private in subclasses.
  • Methods declared private are not inherited at all, so there is no rule for them.
2. Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement, as in the following examples (Italic ones):
public class className {
// ...
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main(String[] arguments) {
// body of method
}

Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:
  • Visible to the package. the default. No modifiers are needed.
  • Visible to the class only (private).
  • Visible to the world (public).
  • Visible to the package and all subclasses (protected).
Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality.
  • The static modifier for creating class methods and variables.
  • The final modifier for finalizing the implementations of classes, methods, and variables.
  • The abstract modifier for creating abstract classes and methods.
  • The synchronized and volatile modifiers, which are used for threads.

Variable types in Java

All variables must be declared before they can be used in Java programming,

The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;

The type is one of Java's datatypes. The identifier is the name of the variable. To declare more than one variable of the specified type, use a comma-separated list. Here are several examples of variable declarations of various types. Note that some include an initialization.

int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
This chapter will explain various variable types available in Java Language.

There are three kinds of variables in Java:
  1. Local variables
  2. Instance variables
  3. Class/static variables
Local variables:
  • Local variables are declared in methods, constructors, or blocks.
  • Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
  • Access modifiers cannot be used for local variables.
  • Local variables are visible only within the declared method, constructor or block.
  • Local variables are implemented at stack level internally.
  • There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
Example:
Here is a example for local variable age. This is defined inside pupAge() method and its scope is limited to this method only.

public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]){
Test test = new Test();
test.pupAge();
}
}

Instance variables:
  • Instance variables are declared in a class, but outside a method, constructor or any block.
  • When a space is allocated for an object in the heap a slot for each instance variable value is created.
  • Instance variables are created when an object is created with the use of the key word 'new' and destroyed when the object is destroyed.
  • Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object’s state that must be present through out the class.
  • Instance variables can be declared in class level before or after use.
  • Access modifiers can be given for instance variables.
  • The instance variables are visible for all methods, constructors and block in the class. Normally it is recommended to make these variables private (access level).However visibility for subclasses can be given for these variables with the use of access modifiers.
  • Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.
  • Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) the should be called using the fully qualified name .ObjectReference. VariableName.
Static Variables:
  • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
  • There would only be one copy of each class variable per class, regardless of how many objects are created from it.
  • Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.
  • Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.
  • Static variables are created when the program starts and destroyed when the program stops.
  • Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
  • Default values are same as instance variables. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor. Additionally values can be assigned in special static initializer blocks.
  • Static variables can be accessed by calling with the class name . ClassName.VariableName.
  • When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables.

Literals in Java

A literal is a source code representation of a fixed value. They are represented directly in the code without any computation. Literals can be assigned to any primitive type variable.

For example:
byte a = 68;
char a = 'A'

byte, int, long, and short can be expressed in decimal(base 10),hexadecimal(base 16) or octal(base 8) number systems as well.

Prefix 0 is used to indicates octal and prefix 0x indicates hexadecimal when using these number systems for literals.

For example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;

String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes.

Examples of string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters.
For example:
char a = '\u0001';
String a = "\u0001";
Java language supports few special escape sequences for String and char literals as well.
They are:

NotationCharacter represented
\nNewline (0x0a)
\rCarriage return (0x0d)
\fFormfeed (0x0c)
\bBackspace (0x08)
\sSpace (0x20)
\ttab
\"Double quote
\'Single quote
\\backslash
\dddOctal character (ddd)
\uxxxxHexadecimal UNICODE character (xxxx)

Introduction to Java OOPs

Java is an Object Oriented Language like C++. As a language that has the Object Oriented feature Java supports the following fundamental concepts:
  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
  • Classes
  • Objects
  • Instance
  • Method
  • Message Parsing
Now we will look into the concepts Objects and Classes:
Object: Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
Class: A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.

Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can find many objects around us, Cars, Dogs, Humans etc. All these objects have a state and behavior. If we consider a dog then its state is - name, breed, color, and the behavior is - barking, wagging, running If you compare the software object with a real world object, they have very similar characteristics. Software objects also have a state and behavior. A software object's state is stored in fields and behavior is shown via methods. So in software development methods operate on the internal state of an object and the object-to-object communication is done via methods.

Classes in Java:
A class is a blue print from which individual objects are created.
A sample of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}

A class can contain any of the following variable types:
Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method, with the static keyword.

A class can have any number of methods to access the value of various kind of methods. In the above example, barking(), hungry() and sleeping() are methods. Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java Language.

Constructors:
When discussing about classes one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class. Each time a new object is created at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.

Example of a constructor is given below:
public class Puppy{
public puppy(){
}
public puppy(String name){
}
}

Java also supports Singleton Classes where you would be able to create only one instance of a class.

Creating an Object:
As mentioned previously a class provides the blueprints for objects. So basically an object is created from a class. In java the new key word is used to create new objects.

There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The 'new' key word is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.