You are on page 1of 45

FRIDAY, MARCH 16, 2012

Assginment - Week 1
1. Create one class to get familiar with class creation structure. 2. Create another class with 6 different addition operations of 8 variables each. For example --a + b ++ + --b - --c - ++d + c-- + f-- + --f
Posted by Shahzad at 12:12 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: assignment, class 1, class 2

Test Variable
package class1; public class TestVariable { public enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; public static void main(String[] args) { Day monday = Day.Monday; Day m = Day.valueOf("Monday") ; System.out.println(m); // int $1 ; // float f = 10.0f ; // long l = 234234434234l ; // double d = 10.2 ; // boolean b = false ; // char c = 2 ; // short s = 2 ; // int a = 0 ; // float b = 1.0f ; // long c = 1 ; // double d = 1.0 ; // short c1, c2 ; // c1 = c2 = 12 ; // // c1 = (short) (c1 + c2) ; // c = a + (int)b ; // d = c + b ; // // a = a + 1 ; // a += 1 ; // a ++ ; // ++ a ; // // a = a -1 ; // a -= 1 ; // a -- ; int a, b, c, d, e, f;

a = b = c = d = e = f = 1; // f = a++ + b ++ + a ++ ; // f = a++ + b++ + c++ + d++ + ++d + ++c + f++ ; // f = --a + b ++ + --b - --c - ++d + c-- + f-- + --f ; // f = --a - --a - ++d - d++ - a -- - b -- + c-- + f -- + 1 ; // // System.out.println(f); // f = (a + b + c + d + e) % 5; f /= a % b / (a + b); System.out.println(f); // (), [], post fix ++, -// previx ++, --, +, - (right) // new, (type) // *, /, % // +, // <<, >>, >>> // <, <=, >, >= // ==, != // & // ^ // | // && // || // =, +=, -=, >>>= (right) } }
Posted by Shahzad at 11:51 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: cardinality, class 2, enum, expression, primitives

First Class
package class1; public class FirstClass { public static void main(String[] args) { System.out.println("This is my first program "); } }

Assginment - Week 1
1. Create one class to get familiar with class creation structure. 2. Create another class with 6 different addition operations of 8 variables each. For example --a + b ++ + --b - --c - ++d + c-- + f-- + --f
Posted by Shahzad at 12:12 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: assignment, class 1, class 2

WEDNESDAY, MARCH 21, 2012

Test String
package class4; public class TestString { public static void main(String[] args) { char[] name = { 's', 'h', 'a', 'h', 'z', 'a', 'd' }; String n = "shahzad"; String n1 = "shahzad"; String n2 = new String("shahzad"); n2 = "shahzad" ; System.out.println(n == n2 ? "True" : "False"); System.out.println(n.equals(n2) ? "True" : "False"); n = n + " masud" ; n2 = " masud" ; n1 = "" + 1 + 1 + "shahzad" ; n1 = "shahzad" + 1 + 1 ; } }
Posted by Shahzad at 1:16 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: by ref, by value, class 4, concatenation, String

Test Array
package class4; import java.util.Arrays; public class TestArray { public static void main(String[] args) { // int a, b, c, d, e, f, g, h, i, j, k, l; int[] prime = new int[10]; // 1. int[] p1 = null; // declare p1 = new int[10]; // init p1[0] = 1; // assignment // 2. int[] p2 = new int[10]; // declare + init p2[0] = 1; // assignment

// 3. int[] p3 = { 1, 2, 3, 4, 5, 6, 7 }; // declare + init + assignment p3 = new int[] { 1, 2, 3, 4 }; for (int i = 0; i < p3.length; i++) { p3[i] = 10; } Arrays.fill(p2, 10); int val = 0; for (int i = 0; i < p3.length; i++) { val = p3[i]; System.out.println(val); } for (int val1 : p3) { System.out.println(val1); } float[][] t; t = new float[10][20]; t = new float[10][]; for (int i = 0; i < t.length; i++) { t[i] = new float[i * 2 + 1]; } for (float[] f : t) { for (float f1 : f) { System.out.println(f1); } } t = new float[][] { { 1, 3 }, { 2, 3, 4, 5, 5 }, { 4, 4, 4, 4, 5 } }; } }
Posted by Shahzad at 1:15 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: array, Arrays, class 4

Power Calc
package class4; public class PowerCalc { public static void main(String[] args) { System.out.println("5.0 to the power 4 is " + power(5.0, 4)); System.out.println("7.5 to the power 5 is " + power(7.5, 5)); System.out.println("7.5 to the power 0 is " + power(7.5, 0)); System.out.println("10 to the power -2 is " + power(10, -2)); }

public static double power(double x, long y) { if (y > 1) { return x * power(x, y - 1); } else if (y < 0) { return 1.0 / power(x, -y); } else { return y == 0 ? 1.0 : x; } } }
Posted by Shahzad at 1:14 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 4, recursion

Letter Check
package class3; import static java.lang.Character.isLowerCase; import static java.lang.Character.isUpperCase; public class LetterCheck { public static void main(String[] args) { char symbol = 'A'; if (isUpperCase(symbol)) { System.out.println("This is capital letter"); } else if (isLowerCase(symbol)) { System.out.println("This is small letter"); } // if ( boolean expression ) { // true statement(s) // } // else if ( boolean ) { // false statement(s) // } int i = 0, j = 0; if (i > 1) { j = i + 1; } else { j = 1; } j = i > 1 ? i + 1 : 1; j = i > 1 ? (i > 2 ? j + 1 : 2) : 3; System.out.println(i > 1 ? (i > 2 ? j + 1 : 2) : 3); if (i == 0) { System.out.println("Zero"); } else if (i == 1) { System.out.println("one");

} else if (i == 2) { System.out.println("two"); } else { System.out.println("Other"); } switch (i) { case 0: System.out.println("Zero"); break; case 1: System.out.println("One"); break; case 2: System.out.println("Two"); break; default: System.out.println("Other"); break; } System.out.println(i == 0 ? "Zero" : i == 1 ? "One" : i == 2 ? "Two" : "Unknown"); // // 1. While // int a = 0;// initialization // while (a < 10) { // condition / expression // System.out.println(a);// statements // a = a + 1; // iteration operation // } // // // 2. do while // int b = 0; // init // do { // System.out.println(b); // stmt // b++; // inc // } while (b < 10); // condition // // // 3. for loop // for ( int c = 0 ; c < 10 ; c ++ ) { // System.out.println(c); // stmt // } // break ; loop termination statement // continue ; loop1: for (int a = 0; a < 3; a++) { loop2: for (int b = 0; b < 5; b++) { loop3: for (int c = b; c < 2; c++) { if (a == c) { continue loop2; } if (a == b) { break loop1; } System.out.println(a + ":" + b + ":" + c);

} } } } }
Posted by Shahzad at 1:13 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: break, class 3, continue, for, if, loop, switch, ternary, while, wrapper

Assignment - Week 2
1. Create a two dimensional array. float f = new float[10][10] ; add random values (Random r = new Random()) ; in all indexes there should be different values. sort whole array as ascending, it should be ascending in all directions. 2. Find string from another string using String.indexOf a quick brown fox jumps over the lazy dog

MONDAY, MARCH 26, 2012

Assignment - Week 3
1. Extend example of Point, Line, and Rectangle. Create a class of Skewed Rectangle. Create a method to find point of intersection in Skewed Rectangle. [Hint]:Create two lines of diagonals and then find its point of intersection as this guidelines on this Link. 2. [Optional] Create a hierarchy and complete set of classes for Tree Inheritance. Understand this description and then write - Tree is parent of all (Tree age, and type) - Tree has two childs (Palm Tree, and Date Tree with properties of color) - Date Tree has two childern (Ajwa, Irani Date Tree) - Create one class which can create objects of all inheritance classes and demonstrate polymorphism.
Posted by Shahzad at 11:58 PM 2 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: assignment, class 5, class 6

Second Interface
package class6; public interface SecondInterface { public void second(); }
Posted by Shahzad at 11:38 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 6, Interface, Multiple Inheritance, Object Oriented

First Interface
package class6; public interface FirstInterface { public void first(); }
Posted by Shahzad at 11:38 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 6, Interface, Multiple Inheritance, Object Oriented

BullDog
package class6; public class BullDog extends Dog { public BullDog() { super("BullDog"); } }

MONDAY, MARCH 26, 2012

Dog
package class6; public class Dog extends Animal { String breed; public Dog() { } public Dog(String breed) { super("Dog"); this.breed = breed; } public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } public void speak() { System.out.println("Baaark ... "); }

@Override public String toString() { return "Dog [breed=" + breed + "]" + super.toString(); } public static void main(String[] args) { Cat c = new Cat("abc"); Dog d = new Dog("bcd"); Animal a = new Dog("Testing1"); // new Animal(); Animal b = new Cat("Testing"); Animal e = new BullDog(); // Animal[] ar = { a, b, c, d, e }; // // System.out.println(c); // // System.out.println(d); // // System.out.println(a); // // System.out.println(b); // for (Animal aa : ar) { // aa.speak(); // } SecondInterface[] ar = { a, b, c, d, e }; for (SecondInterface f : ar) { f.second(); } if (a.getClass() == Cat.class) { } /** * class * public x * protected D * default() x * private D */ }

method variable x x x x x x x x x x x D

constructor

@Override public void first() { System.out.println("This is first of dog"); } @Override public void second() { System.out.println("This is second of dog"); } }
Posted by Shahzad at 11:36 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 6, Inheritance, Interface, Multiple Inheritance, Object Oriented

Cat

/** * */ package class6; /** * @author shahzad * */ public class Cat extends Animal { String breed; public Cat() { super("Cat"); } public Cat(String breed) { super("Cat"); this.breed = breed; } public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } public void speak() { System.out.println("Meeeuuuuoooowwww "); } @Override public String toString() { return "Cat [breed=" + breed + "]" + super.toString(); } @Override public void first() { speak(); } @Override public void second() { System.out.println("Second implementation"); } }
Posted by Shahzad at 11:35 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 6, Inheritance, Interface, Multiple Inheritance, Object Oriented

Animal

package class6; public abstract class Animal implements FirstInterface, SecondInterface{ String type; // Default public Animal() { type = "Unknown"; } // public Animal(String type) { this.type = type; } public String getType() { return type; } public void setType(String type) { this.type = type; } public abstract void speak() ; // { // System.out.println("Animal Say Hello"); // } public String toString() { return "Animal [type=" + type + "]"; } }
Posted by Shahzad at 11:34 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: Abstract, class 6, Inheritance, Interface, Multiple Inheritance, Object Oriented

Rectangle
package class5; public class Rectangle { Line width, height; Rectangle(final Point start1, final Point end1, final Point start2, final Point end2) { width = new Line(start1, end1); height = new Line(start2, end2); } Rectangle(final Line width, final Line height) { this.width = new Line(width); this.height = new Line(height);

} Rectangle(final Rectangle rec) { this.width = new Line(rec.width); this.height = new Line(rec.height); } double area() { return width.length() * height.length(); } @Override public String toString() { return "Rectangle [width=" + width + ", height=" + height + "]"; } public static void main(String[] args) { Rectangle rec = new Rectangle(new Point(0, 0), new Point(0, 10), new Point(10, 0), new Point(10, 10)); System.out.println(rec); } // Assignment 2 // Draw an object of Skewed Rectangle // Find Point of Intersection in it. }
Posted by Shahzad at 11:33 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 5, Composition, Object Oriented

Line
package class5; public class Line { // double x1, y1, x2, y2; Point start, end; Line(double x1, double y1, double x2, double y2) { // this.x1 = x1; // this.x2 = x2; // this.y1 = y1; // this.y2 = y2; start = new Point(x1, y1); end = new Point(x2, y2); } Line(Point start, Point end) { this.start = new Point(start); this.end = new Point(end); } Line(final Line line) { this(line.start, line.end);

} double length() { return start.distance(end); } @Override public String toString() { return "Line [start=" + start + ", end=" + end + ", distance=" + length() + "]"; } public static void main(String[] args) { Line line = new Line(10, 10, 20, 20); Line line2 = new Line(line); System.out.println(line); System.out.println(line2); } }
Posted by Shahzad at 11:33 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 5, Composition, Object Oriented

Point
package class5; public class Point { // <datatype> <variablename> = <valuetoassign> double x; double y; Point( /* No Argument */) { // Default Constructor } Point(double x, double y) { this.x = x; this.y = y; } // Copy Constructor Point(final Point p) { this.x = p.x; this.y = p.y; } // <returndatatype> <propertyname> (<propertyargument>){ // <methodbody> // } double getX() { return x;

} void setX(double x) { this.x = x; } double getY() { return y; } void setY(double newY) { y = newY; } int setY(int newY) { return newY + 20; } @Override public String toString() { return "Point [x=" + x + ", y=" + y + "]"; } double distance(Point p) { return Math.sqrt((p.getY() - getY()) * (p.getY() - getY()) + (p.getX() - getX()) * (p.getX() - getX())); } public static void main(String[] args) { Point p;// Declaration new Point();// Init p = new Point(); // Assignment // Point p1 = new Point(); Point p1 = new Point(10.0, 20.0); p.setX(10.0); // System.out.println(p.x); // System.out.println(p.y); System.out.println(p.setY(20)); System.out.println(p); System.out.println(p1); } }
Posted by Shahzad at 11:32 PM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 5, Composition, Object Oriented

MONDAY, APRIL 2, 2012

Assignment - Week 4

1. Implement data structure of linked list using inner classes or anonymous class. Please also write down reason for using either. Please remember to write equals & hashcode functions in this class. [Hint: Alt+Shift+S --> Implement Hash&Equals + toString] 2. MyArrayIndexOutOfBound, and MyNegativeArraySizeException using custom logic. Implement complete exception classes and throw mechanism. Roll # 4,5,6 will be presenting some topic in break of each hour. Assignment should be emailed before Sunday (At max 23:59:59 Saturday). Good Luck !!
Posted by Shahzad at 8:00 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: assignment, class 7, class 8, Exception, Inner Classes

Test Exception
package class8; public class TestException { public static void main(String[] args) { int a = 0; String b = "f10"; try { // Exception generatable code System.out.println("Before parseInt"); a = getInt(b); System.out.println("After parse Int"); // } catch (MyNumberFormatException mnfe) { // mnfe.printStackTrace(); } catch (NumberFormatException nfe) { nfe.printStackTrace(); // } catch (Exception e) { // // when exception happen, statement(s) // System.out.println("inside exception block ... "); // e.printStackTrace(); } finally { // clean up System.out.println("Finally block ... "); } System.out.println("Final number:" + a); } public static int getInt(String b) throws MyNumberFormatException { try { return Integer.parseInt(b); } catch (NumberFormatException e) { throw new MyNumberFormatException(e); } } }

MONDAY, APRIL 2, 2012

Test Primitive
package class8; public class TestPrimitive { public static void main(String[] args) { int[] i = { 1, 2, 3, 4, 5, 6, 7 }; Integer[] iw = new Integer[i.length]; // AutoBox for (int j = 0; j < i.length; j++) { iw[j] = toInteger(i[j]); } // AutoUnbox for (Integer j : iw) { System.out.println(toInt(j)); } } private static Integer toInteger(Integer i) { return i; } private static int toInt(int i) { return i; } }
Posted by Shahzad at 7:55 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: auto-unbox, autobox, class 8, wrapper

Inner Test Class


package class7; public interface InnerTestInterface { public class InnerClassInInterface { } }
Posted by Shahzad at 7:54 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 7, Inner Classes, Inner Interface

Test Inner
package class7;

import class6.Animal; public class TestInner { public class InnerClass { // It can access all outter class variables & methods (static & non-static) } public static class InnerStaticClass { // It can access all static methods & variables } public interface InnerInterface { public void testing(); } public static void main(String[] args) { TestInner ti = new TestInner(); InnerClass i = ti.new InnerClass(); InnerClass i2 = new TestInner().new InnerClass(); InnerStaticClass isc = new TestInner.InnerStaticClass(); InnerTestInterface.InnerClassInInterface ici = new InnerTestInterface.InnerClassInInterface() ; final InnerInterface ii1 = new InnerInterface() { @Override public void testing() { // Anonymous Classes System.out.println("This is customized code ... "); } }; ii1.testing() ; Animal an = new Animal() { // Access all final variable @Override public void second() { System.out.println(ii1); } @Override public void first() { } @Override public void speak() { } }; } }
Posted by Shahzad at 7:53 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: Anonymous Classes, class 7, Inner Classes, Inner Interface, Object Oriented, static vs non-static

SUNDAY, APRIL 8, 2012

Assignment - Week 5
1. Create a simple client/server application with 1-1 capability. (i.e. Server = Recieve only, Client = Send only). User will be sending his information of assignment submission in the form of a text to server, and server will keep track of it (print to console or save to file). Submission Text would be OBJAVA35 | Your Name | Week # | Assignment # Server will send message to you, if you already submitted your assignment for a repeat assignment submission (optional for rest, mandatory for penality holders) 2. Extend above example to start sending assignment file a) Enter File name (complete file name or simple file name, if user give simple file name, then search it from whole hard disk and get verification from user if found file is correct one or not). b) Send File verification, that file has been sent properly. c) Store that file with following schema on server (objava35-yourname-week#-assignment#) Note: You are free to use serialization or plain method for sending data on network. Note: Assignment .

SUNDAY, APRIL 8, 2012

Test Object
package class10; import java.io.Serializable; public class TestObject implements Serializable { private static final long serialVersionUID = -3292725379720903715L; private Integer id; private String name; private Boolean testing = false; public TestObject(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; }

public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "TestObject [id=" + id + ", name=" + name + ", testing=" + testing + "]"; } }
Posted by Shahzad at 4:26 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 10, Serialization

Test File
package class10; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.RandomAccessFile; import java.net.URI; import java.net.URISyntaxException; public class TestFile { public static void main(String[] args) { // File myFile = new File("d:/abc.txt"); // File myDir = new File("d:/abc"); // File myDirFile = new File(myDir, "File.java"); // File myDirFile1 = new File("d:/abc", "File.java"); // // // try { // // File remoteFile = new File(new // URI("http://www.yahoo.com/abc.html")); // // } catch (URISyntaxException e) { // // e.printStackTrace(); // // } // // File[] root = File.listRoots(); // for (File r : root) { // for (File s : r.listFiles()) { // System.out.println(s.getAbsolutePath() + ":" // + (s.isFile() ? "File" : "Dir")); // }

// } // // String userDir = System.getProperty("user.dir"); // System.setProperty("user.dir", "d:/"); // // try { // BufferedOutputStream out = new BufferedOutputStream( // new FileOutputStream(myFile, true)); // out.write("this is first file writing practise".getBytes()); // out.close(); // } catch (Exception e) { // } // // try { // RandomAccessFile file = new RandomAccessFile(myFile, "rw"); // file.writeUTF("This is randomaccessfile"); // file.close(); // } catch (Exception e) { // } // // try { // Process p = Runtime.getRuntime().exec("ping 192.168.0.1"); // } catch (IOException e) { // e.printStackTrace(); // } ObjectOutputStream fout = null; try { fout = new ObjectOutputStream(new FileOutputStream("c:/abc.txt")); fout.writeObject(new TestObject(1, "One")); } catch (Exception e) { e.printStackTrace(); } finally { if (fout != null) { try { fout.close(); } catch (IOException e) { e.printStackTrace(); } } } ObjectInputStream fin = null; try { fin = new ObjectInputStream(new FileInputStream("c:/abc.txt")); Object obj = fin.readObject(); if (obj instanceof TestObject) { TestObject testObj = (TestObject) obj; System.out.println(testObj); } } catch (Exception e) { e.printStackTrace(); } finally { if (fin != null) { try { fin.close();

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


Posted by Shahzad at 4:26 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: BufferedOutputStream, class 10, File, FileOutputStream, InputStream, List, ObjectInputStream, ObjectOutputStream, OutputStream, RandomAccessFile, Roots, Serialization, System.getProperty

Chat Server
package class9; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; public class ChatServer { public static void main(String[] args) { try { ServerSocket server = new ServerSocket(6666); System.out.println("Server is running: " + server); Socket client = server.accept(); System.out.println("New Client: " + client); BufferedInputStream in = new BufferedInputStream( client.getInputStream()); byte[] b = new byte[1024]; while (true) { int readBytes = in.read(b); System.out.println("Client [" + new Date(System.currentTimeMillis()) + "]: " + new String(b, 0, readBytes)); } } catch (IOException e) { e.printStackTrace(); } } }
Posted by Shahzad at 4:23 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 9, InputStream, OutputStream, Server Socket, Socket, Stream

Chat Client
package class9;

import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class ChatClient { public static void main(String[] args) { try { Socket clientSocket = new Socket("127.0.0.1", 6666); BufferedOutputStream out = new BufferedOutputStream( clientSocket.getOutputStream()); BufferedInputStream in = new BufferedInputStream(System.in); System.out.println("Connection Established, " + "Please enter message below "); byte[] key = new byte[1024]; while (true) { System.out.print("Input:"); int readBytes = in.read(key); out.write(key, 0, readBytes); out.flush(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Posted by Shahzad at 4:23 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 9, InputStream, OutputStream, Socket, Stream

Try Stream
package class9; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; public class TryStream { // BufferedInputStream = Memory Buffer (Array Buffer) // DataInputStream = Primitive Type (Read/Write) // CheckedInputStream = Checksum Maintanance // CipherInputStream = Encrypt - Decrypt // DigestInputStream = One way encryption - Digest // InflatorInputStream = Compression (Text=91-97%, Image=4-9%, Video=1-3%) // LineNumberInputStream = Read data and keep track of Line# // ProgressMonitorInputStream = Keep track of progress // PushBackInputStream = Send it to deignated Source.

public static void main(String[] args) { // BufferedInputStream buf = new BufferedInputStream(System.in); // try { // byte[] b = new byte[100]; // int readBytes = buf.read(b); // String str = new String(b, 0, readBytes); // System.out.println("Input:" + str); // } catch (Exception e) { // e.printStackTrace(); // } BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); try { char[] b = new char[100]; int readBytes = reader.read(b); String str = new String(b, 0, readBytes); System.out.println("Reader: " + str); } catch (Exception e) { // TODO: handle exception } } }
Posted by Shahzad at 4:21 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 9, InputStream, OutputStream, Reader, Stream

SUNDAY, APRIL 15, 2012

Assignment - Week 6
Address Book 1. Name, Email, Phone, Address, Batch (35) Functions: 1. Add/Update/ Delete/ View Person 2. Search (Name, Email, Phone, Address, Batch) 3. Pagination (5 per page) 4. Load on startup, and save on exit Constraints: - Object serialization - Composition / Inheritance / Abstraction - GUI (Option for other, Mandatory for Penality Holders)

Additional or extra Client / Server Implementation Assignment Due: 22-April-2012 Assignment with Extra: 29-April-2012
Posted by Shahzad at 4:56 AM 4 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: assignment, class 11, class 12

Test Collections
package class12; import java.sql.Time; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Vector; public class TestCollection { public static void main(String[] args) { // ------ Sorted ----- Duplicate ----- Ordered // Set --- No -------- Yes ----------- No // List -- No / Yes -- Yes ----------- Yes // Map --- Yes ------- No ------------ Yes // Set --> HashSet, LinkedHashSet, TreeSet, EnumSet // List --> Vector, Stack, LinkedList, ArrayList, Queue // Map --> Hashtable, HashMap, LinkedHashMap, WeakHashMap, // IdentityHashMap Vector<Person> vec = new Vector<Person>(); vec.add(new Person(21, "Twenty One")); vec.add(new Person(11, "Eleven")); vec.add(new Person(7, "Seven")); System.out.println(vec); Person p = new Person(11, "Eleven"); // System.out.println(vec.indexOf(p)); // System.out.println(String.valueOf(vec.contains(p))); Collections.sort(vec); System.out.println(vec); Collections.reverse(vec); System.out.println(vec); Collections.sort(vec, new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { return o1.getName().compareTo(o2.getName()); }

}); System.out.println(vec); java.util.Date date = new Date(System.currentTimeMillis()); Time time = new Time(System.currentTimeMillis()); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); SimpleDateFormat sdf = new SimpleDateFormat(); // Calendar Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()) ; } }
Posted by Shahzad at 4:54 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: Calendar, class 12, Comparator, compareable, Date, SimpleDateFormat, Sorting, System.currentTimeMillis(), Time, Time Travelling, Timestamp, Vector

Person
package class12; import sun.misc.Compare; public class Person implements Comparable<Person> { private Integer id; private String name; public Person(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + "]"; } public String getName() { return name; } public void setName(String name) { this.name = name;

} @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public int compareTo(Person o) { // small = -1 // equal = 0 // greater = 1 int idx = getId().compareTo(o.getId()); return idx == 0 ? getName().compareTo(o.getName()) : idx; } }
Posted by Shahzad at 4:53 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 12, collections, compareable, equals

Try Linked List


package class11; import java.io.Serializable; import class6.Dog;

public class TryLinkedList { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.addItem("first"); list.addItem("Second"); list.addItem("third"); System.out.println(list); LinkedList<Integer> intList = new LinkedList<Integer>(); LinkedList<Dog> dogList = new LinkedList<Dog>(); LinkedList<LinkedList<LinkedList<LinkedList<String>>>> lst = new LinkedList<LinkedList<LinkedList<LinkedList<String>>>>(); Pair<String, Integer> pair = new Pair<String, Integer>(); LinkedList<Pair<String, Integer>> pairList = new LinkedList<Pair<String, Integer>>(); pairList.addItem(new Pair<String, Integer>("one", 1)); LinkedList<?>[] listArray = { list, intList, dogList, lst, pairList }; LinkedList<?> wildArray = new LinkedList<String>(); } public static void print(LinkedList<? extends Serializable> list) { StringBuffer buf = new StringBuffer(); for (Object item = list.getFirst(); item != null; item = list.getNext()) { buf.append(item); buf.append(','); } System.out.println(buf.toString()); } }
Posted by Shahzad at 4:53 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 11, Generics, Templates

Pair (Generics)
package class11; public class Pair<KeyType, ValueType> { private KeyType key; private ValueType value; public Pair() { } public Pair(KeyType key, ValueType value) { this.key = key;

this.value = value; } public KeyType getKey() { return key; } public void setKey(KeyType key) { this.key = key; } public ValueType getValue() { return value; } public void setValue(ValueType value) { this.value = value; } @Override public String toString() { return "Pair [key=" + key + ", value=" + value + "]"; } }
Posted by Shahzad at 4:52 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 11, Generics, KeyType, Pair, ValueType

Linked List
package class11;

//public class LinkedList<T extends Animal & FirstInterface & Serializable> { public class LinkedList<T> { private ListItem start, current, end; public LinkedList() { } public LinkedList(T item) { addItem(item); } public void addItem(T[] items) { for (T item : items) { addItem(item); }

} public void addItem(T item) { ListItem it = new ListItem(item); if (start == null) { start = end = it; } else { end.next = it; end = it; } } public boolean remove(T toRemove) { for (ListItem item = start, prev = null; item != null; item = item.next) { if (item.item.equals(toRemove)) { if (item == start) { start = item.next; } else { prev.next = item.next; } item.next = null; return true; } prev = item; } return false; } public T getFirst() { current = start; return current == null ? null : start.item; } public T getNext() { if (current != null) { current = current.next; } return current == null ? null : current.item; } public String toString() { StringBuffer buf = new StringBuffer(); for (T item = getFirst(); item != null; item = getNext()) { buf.append(item); buf.append(','); }

return buf.toString(); } private class ListItem { T item; ListItem next; public ListItem(T item) { this.item = item; } @Override public String toString() { return "ListItem [item=" + item + "]"; } } }
Posted by Shahzad at 4:50 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 11, Generics, Inner Classes, LinkedList, StringBuffer, Templates

Assignment Submission System [Note] This is a combination of Two earlier assignment - Register/Add, Update, Delete Student - Register/Add, Update, Delete Teacher - Login Student / Teacher Teacher - Define Deadline (Start one Assignment for Submission) - Meta Data: Name, Deadline, Penality - Modify Deadline (Change its deadline date) - Finish Deadline (Finish this assignment) - Search Student, Search Who have submitted, Search Who haven't submitted. Student - Submit Assignment - View Deadline - Change Assignment or Remove Assignment - Search Other Students and Submission of Assignment MUST BE IN ASSIGNMENT: + Serialization + Thread

+ Collection Framework + GUI is optional, but good to have. + Use of JTable would be appreciated, but not must + Client Server Architecture is required. All processing and data keeping would be done on server, and client will be using things on client side. Deadline: 05-May-2012

SUNDAY, APRIL 22, 2012

Test Bank
package class14; import java.util.Random; public class TestBank { private static double initialBalance = 1000; private static double totalCredits = 0; private static double totalDebits = 0; private static int totalTransactions = 100; public static void main(String[] args) { Bank bank = new Bank(); Account account = new Account(1111, initialBalance); Clerk c1 = new Clerk(bank); Clerk c2 = new Clerk(bank); Thread t1 = new Thread(c1, "Clerk1"); Thread t2 = new Thread(c2, "Clerk2"); t1.start(); t2.start(); Random rand = new Random(); Double amount = 0.0; Transaction trans = null; for (int i = 0; i < totalTransactions; i++) { // Credit amount = 50.0 + rand.nextInt(50); trans = new Transaction(account, TransactionType.CREDIT, amount); c1.doTransaction(trans); totalCredits += amount; // Debit amount = 40.0 + rand.nextInt(50); trans = new Transaction(account, TransactionType.DEBIT, amount); c2.doTransaction(trans); totalDebits += amount;

} while (c1.isBusy() || c2.isBusy()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Initial Amount: " + initialBalance); System.out.println("Total Credits:" + totalCredits); System.out.println("Total Debits: " + totalDebits); System.out.println("Current Balance: " + account.getBalance()); System.out.println("Actual Balance: " + (initialBalance + totalCredits - totalDebits)); } }
Posted by Shahzad at 4:07 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 14, synchronization, Thread

Clerk
package class14; public class Clerk implements Runnable { private Bank bank; private Transaction inTray; public Clerk(Bank bank) { this.bank = bank; } public void doTransaction(Transaction trans) { while (isBusy()) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } this.inTray = trans; } public boolean isBusy() { return inTray != null; } public void run() { while (true) { while (isBusy() == false) { try { Thread.sleep(10); } catch (InterruptedException e) {

e.printStackTrace(); } } bank.doTrans(inTray); inTray = null; } } }


Posted by Shahzad at 4:06 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 14, synchronization, Thread

Bank
package class14; public class Bank { public void doTrans(Transaction transaction) { System.out.println(transaction); switch (transaction.getType()) { case CREDIT: synchronized (transaction.getAccount()) { transaction.getAccount().setBalance( transaction.getAccount().getBalance() + transaction.getAmount()); } break; case DEBIT: synchronized (transaction.getAccount()) { transaction.getAccount().setBalance( transaction.getAccount().getBalance() - transaction.getAmount()); } break; default: break; } } // public synchronized void doTrans(Transaction transaction) { // System.out.println(transaction); // Double balance = transaction.getAccount().getBalance(); // switch (transaction.getType()) { // case CREDIT: // balance += transaction.getAmount(); // break; // case DEBIT: // balance -= transaction.getAmount(); // break; // default: // break; // } // transaction.getAccount().setBalance(balance);

// } }
Posted by Shahzad at 4:04 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 14, synchronization, Thread

Account
package class14; public class Account { private Integer accNo; private Double balance; public Account(Integer accNo, Double balance) { this.accNo = accNo; this.balance = balance; } public Integer getAccNo() { return accNo; } public void setAccNo(Integer accNo) { this.accNo = accNo; } public Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } public String toString() { return "Account [accNo=" + accNo + ", balance=" + balance + "]"; } }
Posted by Shahzad at 4:04 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 14, synchronization, Thread

Transaction Type
package class14; public enum TransactionType { CREDIT, // Plus in Amount DEBIT; // Negative in Amount }

Posted by Shahzad at 4:03 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 14, synchronization, Thread

Try Runnable
package class13; public class TryRunnable implements Runnable { private String firstName; private String lastName; private Long delay; public TryRunnable(String firstName, String lastName, Long delay) { this.firstName = firstName; this.lastName = lastName; this.delay = delay; } public void run() { while (true) { System.out.println(firstName); try { Thread.sleep(this.delay); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(lastName); } } public static void main(String[] args) { // Thread first = new TryThread("Asif", "Sajjad", 2000L); // Thread second = new TryThread("Shahzad", "Masud", 3000L); // Thread third = new TryThread("Kamran", "Ahmed", 5000L); // // first.start(); // second.start(); // third.start();y for (int i = 0; i < 50; i++) { Thread t = new Thread(new TryRunnable("First-" + i, "Second-" + i, 500L), "FirstLastNameThread-" + i); t.start(); } } }
Posted by Shahzad at 4:03 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 13, Runnable, sleep, Thread

Try Thread

package class13; public class TryThread extends Thread { private String firstName; private String lastName; private Long delay; public TryThread(String firstName, String lastName, Long delay) { this.firstName = firstName; this.lastName = lastName; this.delay = delay; } public void run() { super.run(); while (true) { System.out.println(firstName); try { sleep(this.delay); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(lastName); } } public static void main(String[] args) { // Thread first = new TryThread("Asif", "Sajjad", 2000L); // Thread second = new TryThread("Shahzad", "Masud", 3000L); // Thread third = new TryThread("Kamran", "Ahmed", 5000L); // // first.start(); // second.start(); // third.start();y for (int i = 0; i < 50; i++) { Thread t = new TryThread("First-" + i, "Second-" + i, 500L); t.setName("FirstLastNameThread-" + i); t.start(); } } }

SUNDAY, MAY 6, 2012

Assignment - Week 8

Create a complete work flow of login, logout, and home page view cycle. Please make sure that you complete that in labs today. Complete assignment will contain a full fledged style with some attractive characteristics of site. Note: J2SE final assignment's dead line is now 12-May-2012. This assignment's dead line is 12-May-2012.
Posted by Shahzad at 4:13 AM 1 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: assignment, class 15, class 16

Logout Servlet
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package class16; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author shahzad */ @WebServlet(name = "LogoutServlet", urlPatterns = {"/LogoutServlet"}) public class LogoutServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().removeAttribute("user"); response.sendRedirect("LoginServlet"); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */

@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Posted by Shahzad at 4:09 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 16, Cookie, JEE, Login, SendRedirect, Servlet, Session, WebServlet

Home Servlet
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package class16; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author shahzad */ @WebServlet(name = "HomeServlet", urlPatterns = {"/HomeServlet"}) public class HomeServlet extends HttpServlet {

/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = (String) request.getSession().getAttribute("user") ; if ( username == null ) { response.sendRedirect("LoginServlet?error=loginfirst"); return ; } response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet HomeServlet</title>"); out.println("</head>"); out.println("<body>"); out.println(" Welcome user [" + username + "] ... <br />"); out.println(" <a href=\"LogoutServlet\">logout</a>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Posted by Shahzad at 4:09 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 16, Cookie, JEE, Login, SendRedirect, Servlet, Session, WebServlet

Login Servlet
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package class16; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author shahzad */ @WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"}) public class LoginServlet extends HttpServlet { private String message; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try {

/* TODO output your page here out.println("<html>"); out.println("<head>"); out.println("<title>Servlet LoginServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet LoginServlet at " + request.getContextPath () + "</h1>"); out.println("</body>"); out.println("</html>"); */ } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("error") != null) { message = "Please login first ... "; } response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet LoginServlet</title>"); out.println("</head>"); out.println("<body>"); if (message != null) { out.println("<font color=RED>" + message + "</font>"); message = null; } Cookie[] cookies = request.getCookies(); String username = ""; for (Cookie c : cookies) { if ("username".equals(c.getName())) { username = c.getValue(); break; } } out.println("<form action=\"LoginServlet\" method=\"POST\">"); out.println("Login: <input type=\"text\" name=\"loginname\" value=\"" + username + "\" /> <br />"); out.println("Password: <input type=\"password\" name=\"loginpass\" /> <br />"); out.println("<input type=\"submit\" name=\"btnlogin\" value=\"Login\" /> &nbsp;");

out.println("<input type=\"reset\" name=\"btnReset\" value=\"Reset\" />"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String loginname = request.getParameter("loginname"); String loginpass = request.getParameter("loginpass"); if (null != loginname && null != loginpass && loginname.trim().length() > 0 && loginpass.trim().length() > 0) { // Verification if ("admin".equals(loginname) && "admin".equals(loginpass)) { // Success , this is a valid user response.addCookie(new Cookie("username", loginname)); request.getSession().setAttribute("user", loginname); response.sendRedirect("HomeServlet"); return; } else { message = "Invalid combination ... "; } } else { message = "Please provide a valid combination ... "; } doGet(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Posted by Shahzad at 4:08 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 16, Cookie, JEE, Login, SendRedirect, Servlet, Session, WebServlet

First Servlet
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package class15; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author shahzad */ @WebServlet(name = "FirstServlet", urlPatterns = {"/FirstServlet"}) public class FirstServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet FirstServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet FirstServlet at " + request.getContextPath() + "</h1>" + new Date(System.currentTimeMillis())); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request

* @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Posted by Shahzad at 4:07 AM 0 comments Email ThisBlogThis!Share to TwitterShare to Facebook Labels: class 15, JEE, Servlet

index.jsp
<%-Document : index Created on : May 6, 2012, 2:13:17 PM Author : shahzad --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> </body> </html>

You might also like