Sunday, August 24, 2008

HashSets, TreeSets, Array Lists, Comparable and Comparators

import java.util.*;

//This class is used to sort a collection in descending order of age and name
//A comparator class is usually written when a programmer usually does not have access to
//source code and then he can create his own custom sort using custom Comparator class as shown in
//Person class below
class Person implements Comparator
{
String name;
int age;
public Person(String name,int age)
{
this.name=name;
this.age=age;
}
public Person()
{
name="";
age=0;
}
public int compare(Person p1,Person p2)
{
if (p2.age>p1.age) return (p2.age-p1.age);
else if (p2.age < p1.age) return (p2.age-p1.age);
else
{
return (p2.name.compareTo(p1.name));
}
}

//Implementing equals method is optional. If implemented to over-ride, make sure the result is consistent with the compare method
public boolean equals(Object o)
{
Person p2 = (Person) o;
if (p2.age>this.age) return (true);
else if (p2.age < this.age) return (false);
else
{
if (p2.name.compareTo(this.name)>= 0)
return true;
else
return false;
}
}


//Over-ride from the object class.
public String toString()
{
return ("Name=" + this.name + ", age=" + this.age);
}
}

//This class sorts a collection in ascending order of age and name and implements comparable.
class PersonComparable implements Comparable {
String name;
int age;
public PersonComparable(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(PersonComparable p2)
{

if (this.age>p2.age) return (this.age-p2.age);
else if (this.age < p2.age) return (this.age-p2.age);
else
{
return (this.name.compareTo(p2.name));
}
}
//Implementing equals method is optional. If implemented to over-ride, make sure the result is consistent with the compareTo method
public boolean equals(Object o)
{
PersonComparable p2 = (PersonComparable) o;
if (this.age>p2.age) return (true);
else if (this.age < p2.age) return (false);
else
{
if (this.name.compareTo(p2.name)>= 0)
return true;
else
return false;
}
}

public String toString()
{
return ("Name=" + this.name + ", age=" + this.age);
}
}

public class CollectionsTest01
{

public static void main(String args[])
{
//hashset allows duplicate and null values. This set is created with Primitive class- string
//hash sets are not ordered by default
Set hs1 = new HashSet();
System.out.println("The original size of the hashset is="+ hs1.size());
hs1.add("temp");
hs1.add(Integer.toString(1));
hs1.add(Boolean.toString(true));
hs1.add("Dushyant");
hs1.add("temp");
hs1.add(null);
System.out.println("The current size of the hashset is="+ hs1.size());
System.out.println("The String hash set is="+hs1);

//hashset allows duplicate and null values. This set is created with Custom class- Person
//hash sets are not ordered by default even if you implement the comparator or comparable interfaces.
HashSet ps1 = new HashSet ();
ps1.add(new Person("Donde Estas",35));
ps1.add(new Person("Ronnie Baron",35));
ps1.add(new Person("Google froogle",31));
ps1.add(new Person("Simple simon",24));
ps1.add(new Person("Greg Bruno",3));
ps1.add(new Person("Ronnie Baron",35));

System.out.println("Iterating through Person hash set");
Iterator it = ps1.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
//When sorting a tree set pass the comparator in the the tree set constructor.
//Tree sets are sorted order sets and apply the compare method
TreeSet personTreeSet1 = new TreeSet(new Person());
personTreeSet1.add(new Person("Donde Estas",35));
personTreeSet1.add(new Person("Ronnie Baron",35));
personTreeSet1.add(new Person("Google froogle",31));
personTreeSet1.add(new Person("Simple simon",24));
personTreeSet1.add(new Person("Greg Bruno",3));
personTreeSet1.add(new Person("Ronnie Baron",35));

System.out.println("Iterating through Person Tree set");
it = personTreeSet1.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}

//Creating a tree set implementing Comparable.
//Tree sets are sorted order sets and apply the comparable interface. Use the compareTo method here to sort.
TreeSet ts1 = new TreeSet ();
ts1.add(new PersonComparable("Damini",35));
ts1.add(new PersonComparable("Gamini",35));
ts1.add(new PersonComparable("Kumari",31));
ts1.add(new PersonComparable("Tsunami",24));
ts1.add(new PersonComparable("Kumari",31));
Iterator it2 = ts1.iterator();
System.out.println("The size of the tree set is="+ts1.size());
System.out.println("Iterating through PersonComparable Tree set");
while(it2.hasNext())
{
System.out.println(it2.next());
}

//Example to apply the static collections method sort and reverseOrder. These static methods only apply on lists.
//The array list is created with Comparable constructor.
ArrayList lst1= new ArrayList();
lst1.add(new PersonComparable("Raj Kapoor",36));
lst1.add(new PersonComparable("Vinod Khanna",39));
lst1.add(new PersonComparable("Dilip Kumar",36));
lst1.add(new PersonComparable("Dilip Kumar",36));
System.out.println("Display the array list before sorting="+lst1);
Collections.sort(lst1);
System.out.println(lst1);

System.out.println("Display the array list after sorting="+lst1);
Collections.sort(lst1,Collections.reverseOrder());
System.out.println("Reverse order sorted list="+lst1);

//Example to apply the static collections method sort and reverseOrder. These static methods only apply on lists.
//The array list is created with Comparator constructor when applied later. In this example Person comparator is applied
ArrayList lstPerson = new ArrayList();
lstPerson.add(new Person("Robin Hood",36));
lstPerson.add(new Person("John Peter",39));
lstPerson.add(new Person("Dwight York",36));
lstPerson.add(new Person("Kevin Pieterson",36));
Collections.sort(lstPerson,new Person());
System.out.println("Applying comparator Person to sort the list="+lstPerson);

TreeSet lst2= new TreeSet();
lst2.add(new PersonComparable("Rajarshi",36));
lst2.add(new PersonComparable("JP",39));
lst2.add(new PersonComparable("Mangesh",36));
lst2.add(new PersonComparable("JP",39));
//Collections.sort(lst2); You cannot apply this Static method on a set. It only applies on a list.
System.out.println(lst2);

ArrayList c = new ArrayList();
c.add(1);c.add(2);
c.add(3);
ArrayList al = new ArrayList(c);
System.out.println("The current size of the collection is="+ al.size());

Set set = new HashSet();
set.add("zab");
set.add("one");
set.add("two");
set.add("three");
set.add("four");
set.add("one");
set.add("abc");
set.add(Integer.toString(3));
System.out.println(set);
Set sortedSet= new TreeSet(set);
System.out.println(sortedSet);
}
}

Sunday, July 27, 2008

PipedInput Stream and PipedOutputStream

import java.io.*;
// reads numbers from input stream and compute running average
class WriteToFile extends Thread
{
private DataInputStream in;
String msg;
private FileOutputStream out;
File f1=new File("C:\\Program Files\\Java\\jdk1.5.0_14\\test\\AJP","output.txt");



public WriteToFile(InputStream i)
{
in=new DataInputStream(i);
try
{
out = new FileOutputStream(f1);
}catch(FileNotFoundException e) { e.printStackTrace();}

}
public void run()
{
String CRLF = "\n";
try {
int count;
while (true)
{

byte buffer[] = new byte[50];

count=in.read(buffer,0,50);
if (count==-1) break;
// System.out.println("Available bytes to read : " + count);
msg = new String(buffer,0,count);


if (count==-1 ||msg.equalsIgnoreCase("EOI") ) { in.close(); break;}
if (count>0 && msg.equalsIgnoreCase("EOI")==false)
{

out.write(buffer,0,count);
if (in.available()==0)
out.write(CRLF.getBytes());
}
}
out.flush();
} catch (Exception e) { e.printStackTrace();}

}

}
class ReadFromCommandLine extends Thread {
private DataOutputStream out;
private BufferedReader buf;
String msg;
public ReadFromCommandLine(OutputStream o) {
out = new DataOutputStream(o);
buf = new BufferedReader(new InputStreamReader(System.in));

}
public void run() {


try {
System.out.println("Please enter the text in multiple lines to write to a file:");
while (true)
{
msg = buf.readLine();

byte b[]=msg.getBytes();
out.write(b);
out.flush();
// System.out.println(msg);
if (msg.equalsIgnoreCase("EOI"))
{
out.close();
break;
}

}


} catch (Exception e) { e.printStackTrace();}

}

}

class MainPP
{
public static void main(String[] args)
{

try {
PipedOutputStream inputreader =new PipedOutputStream();
PipedInputStream filewriter =new PipedInputStream(inputreader);

ReadFromCommandLine readCommandLine = new ReadFromCommandLine(inputreader);
WriteToFile writeFile = new WriteToFile(filewriter);
readCommandLine.setPriority(1);
readCommandLine.start();
writeFile.start();
} catch (IOException e) {e.printStackTrace();}
}
}

Thursday, July 24, 2008

BufferedInputStream,BufferedOutputStream,FileInputStream,FileOutputStream


import java.io.*;
class TestByteStreams{
public static void main(String args[]) throws IOException
{

File f1=new File("C:\\Program Files\\Java\\jdk1.5.0_14\\test\\AJP","BoxArray.java");

System.out.println("Path seperator=" + f1.pathSeparator);

System.out.println("seperator=" + f1.separator);

FileInputStream fInputStream = new FileInputStream(f1);
BufferedInputStream bInputStream = new BufferedInputStream(fInputStream);
byte byteInputArray [] = new byte[500];
FileOutputStream fOutputStream = new FileOutputStream (f1 + "_copy2.java");
BufferedOutputStream bOutputStream = new BufferedOutputStream(fOutputStream,1024);
int count;
while ((count = bInputStream.read(byteInputArray,0,500))>0)

{
//BufferedOutputStream data is written to file or out when the buffer size = 1024 specified in the bufferedoutputstream is reached.
bOutputStream.write(byteInputArray,0,count);

}
//Once reading is complete and byteInputArray filled size is less than 1024 buffered output stream size,
//the output will not be written unless flushed exclusively
bOutputStream.flush();

fInputStream.close();
fOutputStream.close();


/*ByteArrayOutputStream bo = new ByteArrayOutputStream();
String s1 = "Twinkle twinkle litte star";
String s2 = "How I wonder what you are";
byte b1[] = s1.getBytes();
byte b2[] = s2.getBytes();
bo.write(b1);
bo.write(b2);
bo.close();
byte b3[] = bo.toByteArray();
ByteArrayInputStream bi = new ByteArrayInputStream(b3);
int size = bi.available();
for (int i=0; i{
System.out.print((char) bi.read());
}
System.out.println();*/


}

}


Monday, July 14, 2008

Calendar Application

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class MyAdapter implements ActionListener
{

FrameCalendar fc;

public MyAdapter(FrameCalendar fc1)
{
fc=fc1;
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==fc.btnDisplay)
{
int month,year;
GregorianCalendar c = new GregorianCalendar();
try
{
month=Integer.parseInt(fc.tMonth.getText());
year=Integer.parseInt(fc.tYear.getText());
} catch (NumberFormatException e)
{ month=c.get(Calendar.MONTH)+1;
year=c.get(Calendar.YEAR);
}
c.set(Calendar.DATE,1);
c.set(Calendar.MONTH,month-1);
c.set(Calendar.YEAR,year);
printCalendar(c);
}
}

private void printCalendar(GregorianCalendar c)
{
String DAY_OF_WEEK[] = {"Su","Mo","Tu","We","Th","Fr","Sa"};
int monthLength[]={31,28,31,30,31,30,31,31,30,31,30,31};
int MonthArray[][]=new int[6][7];
int month,year,date;
for (int i=0;i<6;i++)
{
Arrays.fill(MonthArray[i],0);
}
c.set(Calendar.DATE,1);
date=c.get(Calendar.DATE);
month=c.get(Calendar.MONTH);
year=c.get(Calendar.YEAR);

int i;

for (i=0;i{
System.out.print(DAY_OF_WEEK[i]+"\t");
fc.ta.append(DAY_OF_WEEK[i]+"\t");
}
System.out.println();
if ((month==1) && (c.isLeapYear(year)))
monthLength[1]=29;
else
monthLength[1]=28;

for (i=1;i<=monthLength[month];i++)
{
MonthArray[c.get(Calendar.WEEK_OF_MONTH)-1][c.get(Calendar.DAY_OF_WEEK)-1]=i;
c.roll(Calendar.DATE,1);
}
for (i=0;i<6;i++)
{
System.out.println();
fc.ta.append("\n");
for (int j=0;j<7;j++)
{
if (MonthArray[i][j]==0)
{
System.out.print("\t");
fc.ta.append("\t");
}
else
{
System.out.print(MonthArray[i][j] + "\t");
fc.ta.append(MonthArray[i][j] + "\t");
}
}
}
}
}
public class FrameCalendar extends Frame
{
Frame f1;
Label l1;
Button btnDisplay;
Panel p1,p2;
TextField tMonth, tYear;
TextArea ta;

public FrameCalendar(){
f1=new Frame();
f1.setSize(400,400);
l1=new Label("Please enter Month and Year");
btnDisplay=new Button("Show");
tMonth=new TextField("Enter Month");
tYear=new TextField("Enter Year");
p1=new Panel();
p1.add(l1);
p1.add(btnDisplay);
p1.add(tMonth);
p1.add(tYear);
f1.add(p1);
p2=new Panel();
ta = new TextArea("",10,50,0);
p2.add(ta);
f1.add(p2);
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
p2.setLayout(new FlowLayout(FlowLayout.CENTER));
f1.setLayout(new GridLayout(2,1));
f1.setVisible(true);
p1.setVisible(true);
p2.setVisible(true);
btnDisplay.addActionListener(new MyAdapter(this));
}

public static void main(String args[])
{
FrameCalendar fc = new FrameCalendar();
}
}

Tuesday, July 8, 2008

Wrapper classes for primitive types

Constructors
Integer (int i)
Integer(String s)

Methods to Convert primitive integer type to Integer Object
public static Integer decode(String s)
public static Integer valueOf(String s) => The string format can be number, leading 0 for octal, # or 0x for Hexadecimal
public static Integer valueOf(String s, int radix)

Methods to convert Integer Object to different primitive types
public byte byteValue()
public double doubleValue()
public float floatValue()
public int intValue()
public long longValue()
public short shortValue()

Methods for converting a String to primtive type
public int parseInt(String s)
public int parseInt(String s, int radix)

Methods for converting a primitive type to String
public static String toString(int i)
public static String toBinaryString(int i)
public static String toHexString(int i)
public static String toOctalString(int i)

Methods to compare Integer Object
public boolean equals(Object x)
public int compareTo(Integer x)

Integer.MIN_VALUE and Integer.MAX_VALUE fields to compare max and min values for a particular Object type.

This is similar for Short, byte, boolean, long, double, float.

Saturday, June 7, 2008

File Class, InputStream and OutputStream

  1. File
Although most of the classes defined in java.io operate on streams, File class does not.
It deals directly with files and the filesystem and does not specify how information is retrieved or stored in a file. It however provides properties of the file.
File ConstructorsFile (String DirectoryPath)
File (String DirectoryPath, String Filename)
File(File dirObj, String Filename)
File (URI uriObj)

File Methods
getName()
getpath()
getAbsolutePath()
getParent()
boolean canWrite()
boolean canRead()
boolean isHidden()
boolean isFile()
long length()
boolean isDirectory()
boolean setReadOnly()
It is a file that contains a list of other files and directories.

Methodslist()


The listFiles( ) AlternativeFile[ ] listFiles( )
File[ ] listFiles(FilenameFilter FFObj)
File[ ] listFiles(FileFilter FObj)

Directory

These methods return the file list as an array of File objects instead of strings.

The third version of listFiles( ) returns those files with path names that satisfy the
specified FileFilter. FileFilter defines only a single method, accept( ), which is called
once for each file in a list. Its general form is given here:
boolean accept(File path)

FilenameFilter InterfaceThe lists can implement interface to return file lists of certain extension. It implements the accept method.
public class File01 implements FilenameFilter
{
public boolean accept(File dir,String name){ return (name.endsWith("exe") name.endsWith("java")); }

public static void main(String args[])
{
File01 ff = new File01();
File f1 = new File("C:\\Program Files\\Java\\jdk1.5.0_14\\abc");
String s[]=f1.list(ff);
________________________________________________________
FileInputStreamThe FileInputStream class creates an InputStream that you can use to read bytes from
a file. Its two most common constructors are shown here:
FileInputStream(String filepath)
FileInputStream(File fileObj)
Either can throw a FileNotFoundException

FileOutputStreamFileOutputStream creates an OutputStream that you can use to write bytes to a file. Its
most commonly used constructors are shown here:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
They can throw a FileNotFoundException or a SecurityException
________________________________________________________
ByteArrayStreams

ByteArrayInputStream
byte buff[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buff);

A ByteArrayInputStream implements both mark() and reset().
If mark is not called, then reset points to start of buffer.

ByteArrayOutputStreamByteArrayOutputStream is an implementation of outputStream that uses byte array as destination
ByteArrayOutputStream()
ByteArrayOutputStream(int numBytes)
String s ="This is a test";
byte buff[] = s.getBytes();
OutputStream f2 = new FileOutputStream("test.txt");
ByteArrayOutputStream f = new ByteArrayOutputStream();
//Method#1
f.write(buff);
f.writeTo(f2);

//Method#2
f2.write(buff);
________________________________________________________
Filtered Byte StreamsWrapper classes of InputStream and Output streams.
Constructors are
FilterOutputStream(OutputStream os)
FilterInputStream(OutputStream os)

Buffered Byte Streams useful in I/O performance optimization.
BufferedInputStream
Constructors
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufsize)

mark and reset() are supported

BufferedOutputStream
Constructors
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream,int bufsize)
Example:
String s="test";
byte buf[]=s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
BufferedInputStream bufStream = new BufferedInputStream(in);
bufStream.read()
BufferedOutputStream outStream = new BufferedOutputStream(buf);
outStream.flush(); //Recommended to use flush than write to reduce I/O
________________________________________________________

Sunday, May 11, 2008

Abstract Class and Interfaces

Abstract Classes and Interfaces allows you to create dynamic methods that act as per the object type generated at run time.

Abstract Class
  • Any class that contains one or more abstract methods needs to be declared as abstract.
  • There can be no objects for an abstract class
  • Abstract constructor or abstract static methods cannot be declared in a abstract class. You can construct regular constructor.
  • Any sub-class of an abstract class must implement all the abstract methods of the super calls or itself be declared abstract.

Interface

  • They lack instance variable, and their methods are declared without bodies.
  • Format

access interface name {

return-type method1 (param-list);
return-type method2 (param-list);
type final-var1=value;
type final-var2=value;

}

  • Each class that implements an interface must implement all of the methods defined under the interface.
  • Interface methods implemented by the class are always public.
  • A class that only implements an interface methods partially must be declared as an abstract class and all the rules of abstract class apply to it.

Example

abstract class Shape
{
//Static variable numObjects to keep count of Shape objects created
protected static int numObjects=0;

//Shape constructor
Shape()
{
++numObjects;
}
//define abstract method for area
abstract double area();

//static function to return number of shapes
protected static int numShapes()
{
return numObjects;
}

}

//Define interface for drawing
interface Drawable {
void draw();
}

//Class Circle is a sub class of Shape
class Circle extends Shape
{
protected int radius;
protected static int numberCircles=0;
Circle(int radius)
{
super(); //execute super class constructor first before initializing circle class instance variable - radius
this.radius=radius;
++numberCircles;
}

//return area of circle as double. This is the implementation for abstract method area defined in Shape
protected double area()
{
return Math.PI * radius * radius;
}

//static method to return number of circle objects created
protected static int numCircles()
{
return numberCircles;
}
}

//Class Rectangle is a sub class of Shape
class Rectangle extends Shape
{
protected int length,width;
protected static int numberRectangles=0;
Rectangle(int length, int width)
{
super(); //execute super class constructor first before initializing rectangle class instance variables length and width
this.length=length;
this.width=width;
++numberRectangles;
}

//return area of rectangle as double. This is the implementation for abstract method area defined in Shape
protected double area()
{
return length * width;
}

//static method to return number of rectangle objects created
protected static int numRectangles()
{
return numberRectangles;
}
}

//Graphic circle inherits circle class and implements interface Drawable
class GraphicCircle extends Circle
implements Drawable
{
protected int color;

GraphicCircle(int radius,int color)
{
super(radius);
this.color=color;

}
//interface implementation of draw method. method access should always be public for interface method implementation
public void draw()
{
System.out.println("Circle drawn using color:" + color);
}
}
//Graphic Rectangle inherits Rectangle class and implements interface Drawable
class GraphicRectangle extends Rectangle
implements Drawable
{
protected int color;


GraphicRectangle(int len,int wid,int color)
{
super(len,wid);
this.color=color;

}

//interface implementation of draw method. method access should always be public for interface method implementation
public void draw()
{
System.out.println("Rectangle drawn using color:" + color);
}
}

Friday, May 9, 2008

Java Terms Explained

I started learning java and I thought it would be a good idea to help the user community of this wonderful language from a beginner's perspective.
http://java.sun.com/developer/onlineTraining/new2java/programming/learn/unravelingjava.html

What is the difference between SDK and JDK.
Java 2 SDK is by popular user opinion has been reverted back to JDK where JDK stands for J2SE Development Kit. J2RE has been reverted to JRE.
http://java.sun.com/javase/namechange.html

Another thing to note is that there is no difference between 1.5.0 and 5.0 version. The leading 1. was dropped and the new 5.0 numbering format has been adopted by Sun. The latest release of Java is version 6.0 and instead of referring it by J2SE 6.0, Sun prefers to call the new version Java SE 6.0. They have dropped the 2 altogether.
http://java.sun.com/j2se/versioning_naming.html

I would blame the Sun Marketing people of confusing people with the versioning. I hope the above links would help simplify things for the beginner.