solved sample programs
Post on 04-Nov-2014
207 Views
Preview:
DESCRIPTION
TRANSCRIPT
HCL STRUCTURE OF JAVA LANGUAGE AND JAVA CLASSES
//program to display hello world
class prg1{ public static void main(String s[]) { System.out.println("hello world!"); System.out.println("this is our \n first class"); System.out.println("we want to \tlearn java"); System.out.print("java"); System.out.print("india"); }}
//program to create object and calling a method through created object
class first{ void show() { System.out.println("hello world!"); }}
class apple{ public static void main(String s1[]) { first f=new first(); f.show(); }}
//program to calling a method without using object but static
class first
HCL{ static void show() { System.out.println("hello world!"); }}
class apple{ public static void main(String s1[]) { first.show(); }}
//demo program to declare and initializing variables
class first{ void show() { int a=10,x=12; float b=4567.393f; double c=123.45; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(a+x); System.out.println("the addition value is "+(a+x)); }}
class apple{ public static void main(String s1[]) { first f=new first(); f.show(); }}
HCL
// program to print variables without initialization which throughs exceptions.//in this context java differs from c++
class first{ int k; void show() { int a; float b; char c; String s; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(s); System.out.println(k); }}
class apple{ public static void main(String s1[]) { first f=new first(); f.show(); }}
//program to print default intial values of different data types
class first{ int k; float f1; char c1;
HCL String s1; void show() { System.out.println(k); System.out.println(f1); System.out.println(c1); System.out.println(s1); }}
class apple{ public static void main(String s1[]) { first f=new first(); f.show(); }}
//demo to print default values of access modifiers
class first{ int a1; public int a2; private int a3; protected int a4; static int a5; public static int a6; private static int a7; protected static int a8;
void show() { System.out.println("value of a1 is "+a1); System.out.println(a1+","+a2+","+a3); }}
class prg3{
HCL public static void main(String s1[]) { first f=new first(); f.show(); }}
//program to show scope of acess modifiers
class first{ int a1=1; public int a2=2; private int a3=3; protected int a4=4; static int a5=5; public static int a6=6; private static int a7=7; protected static int a8=8;}class prg4{ public static void main(String s1[]) { first f=new first(); System.out.println(f.a1); System.out.println(f.a2); System.out.println(f.a3); System.out.println(f.a4); System.out.println(f.a5); System.out.println(f.a7);
}}
// demo program to call a function before its definition.//this program it won’t work in c and c++ but in java
class xyz
HCL{ void show() { disp(); System.out.println("i am show function"); } void disp() { System.out.println("i am disp function"); }}
class prg5{ public static void main(String s1[]) { xyz x=new xyz(); x.show(); }}
// demo program to call a function before its definition
class prg6{ public static void main(String s1[]) { show(); }static void show() { System.out.println("i am show fun"); }}
//program for function overloading
HCLclass test{ void show() { System.out.println("i am show fun in test class "); }
void show(char a) { System.out.println(a); }
void show(int a) { System.out.println(a); }
void show(int a,int b) { System.out.println(a+b+"abc"); }
void show(int a,char b) { System.out.println(a+b+"abc"); } }
class prg7 { public static void main(String s1[]) { test t=new test(); t.show(); t.show(5); t.show('a'); t.show(5,6); t.show(10,'A'); } }
Command Line Arguments
HCL//program that display command line arguments
public class prg1{ public static void main(String x[]) { System.out.println(x[0]); System.out.println(x[1]); System.out.println(x[2]); System.out.println(x[3]); }}
//program to add 2 numbers passed in command prompt
class first{ public static void main(String x[]) { int a,b,c; a=Integer.parseInt(x[0]); //Wrapper class for type casting b=Integer.parseInt(x[1]); c=a+b; System.out.println(c); }}
//main method overloading
public class prg1 { public static void main(int[] args) { System.out.println("int"); }
public static void main(String[] args) { System.out.println("string");
HCL }
public static void main(float[] args) { System.out.println("float"); }}
//program that uses main in each class in a single file
class first{ public static void main(String args[]) { System.out.println(“i am main method in first class”); }}
class second{ public static void main(String args[]) { System.out.println(“i am main method in second class”); }}
class third{ public static void main(String args[]) { System.out.println(“i am main method in third class”); }}
class fourth{ public static void main(String args[]) { System.out.println(“i am main method in fourth class”); }}
HCL
//program to show that local variable cannot be static and public
class first{ void show() { static int a=5; public int b=6; System.out.println(a); System.out.println(b); }}
class prg2{ public static void main(String[] args) { first f=new first(); f.show(); }}
//demo program to show scope of class level variable between methods
class first{ int a=10; void show() { System.out.println(a); a++; } void disp() { System.out.println(a); a=a+5; }}
HCLclass prg3{ public static void main(String[] args) { first f=new first(); f.show(); f.disp(); f.show(); f.show(); }}
//program that uses inner classe
class outerClass{ private int i=10; private void method1() { System.out.println("i am Private "); }
class innerClass { void method() { System.out.println("Private "+i); method1(); } }}
class innerClassExample{ public static void main(String []ohm) { outerClass obj1=new outerClass(); outerClass.innerClass obj2=obj1.new innerClass(); obj2.method(); }
HCL}
//program that uses private Method
class PrivateMethod{ private int a=10; private String method(){ System.out.println("I am private"); return "hai"; } String callPrivate(){ return method(); }}class PrivateMethodExample{ public static void main(String []arg){ PrivateMethod obj=new PrivateMethod(); System.out.println("main:"+obj.callPrivate()); }}
//program that is using array object
class arr {public static void main(String[] args) {
int[] ia = new int[101];for (int i = 0; i < ia.length; i++)
ia[i] = i;int sum = 0;for (int i = 0; i < ia.length; i++)
sum += ia[i];System.out.println(sum);
}}
//program uses 2D array
HCLclass Test {
public static void main(String[] args) {int ia[][] = { {1, 2}, {3,4} };for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)System.out.println(ia[i][j]);
}}
String class and StringBuffer class
//program that uses few String class methods
import java.lang.String;
public class prg1{ public static void main(String srg[]) { String str1; String str2=new String(); String str3=new String("welcome"); String str4; str1="india"; str2="japan"; str3="raju"; System.out.println(str1); System.out.println(str2); System.out.println(str3); str4="today is monday and yesterday is sunday"; System.out.println(str4.length()); System.out.println("sudha".length()); System.out.println(str4.charAt(4)); System.out.println("india".equals("INDIA")); System.out.println("india".equalsIgnoreCase("INDIA")); System.out.println(str4.substring(8)); System.out.println(str4.substring(8,15)); System.out.println(str4.concat(str2)); System.out.println(str4.replace('a','*')); System.out.println(str4.toUpperCase());
HCL String str5="hello"; System.out.println(str5); System.out.println(str5.trim()); }}
//program that uses few StringBuffer class methods
import java.lang.StringBuffer;
public class prg2{ public static void main(String srg[]) { StringBuffer s1=new StringBuffer(); StringBuffer s2=new StringBuffer(20); StringBuffer s3=new StringBuffer("welcome"); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s1.length()); System.out.println(s1.capacity()); s1.append("sd f f a aFA fasdfasdg8034ty8035 rg sg asdg as g asdg asdgoasdgasdg"); System.out.println(s1.length()); System.out.println(s1.capacity()); s1.setLength(5); System.out.println(s1.length()); System.out.println(s1.capacity()); System.out.println(s1); System.out.println(s1.reverse()); }}
INHERITANCE
//single Inheritance
HCLclass Person{
String name;int age;void getPerInfo(String str,int ag){
name=str;age=ag;
}void putPerInfo(){
System.out.println("Name:"+name);System.out.println("Age:"+age);
}}class Student extends Person{
int total;char grade;void getStuInfo(String n,int ag,int tot,char gr){
getPerInfo(n,ag);total=tot;grade=gr;
}void putStuInfo(){
putPerInfo();System.out.println("Total:"+total);System.out.println("Grade:"+grade);
}
}
class single_inheritance{public static void main(String args[]){
Student s=new Student();s.getStuInfo("Honey",22,98,'A');s.putStuInfo();
}}
//multi level inheritance
class grand_father{
HCL void show1() { System.out.println("i am show function in grand_father class"); }}
class father extends grand_father{ void show2() { System.out.println("i am show function in father class"); }}
class son extends father{ void show3() { System.out.println("i am show function in son class"); }}
class grand_son extends son{ void show4() { System.out.println("i am show function in grand_son class"); }}
class multi{ public static void main(String args[]) { grand_son gs=new grand_son(); gs.show4(); gs.show3(); gs.show2(); gs.show1(); }}
HCL
//hieararchial inheritance
class parents{ void show() { System.out.println("we are parnts"); }}
class son extends parents{ void disp() { System.out.println("i am son class"); }}
class daughter extends parents{ void disp() { System.out.println("i am daughter class"); }}
public class hie{ public static void main(String args[]) { son s=new son(); daughter d=new daughter(); s.show(); d.show(); s.disp(); d.disp(); }}
HCL
//Scope of Access specifiers
class Simple{private int pri;int def;protected int pro;public int pub;
Simple(){pri=10;def=20;pro=30;pub=40;
} }
class Inherit extends Simple{
Inherit() {//pri = 100; // can't access privatedef = 200;pro = 300;pub = 400;
}
public static void main(String[] args) {Inherit i = new Inherit();
// can't access private//System.out.println(i.pri)System.out.println(i.def);System.out.println(i.pro);System.out.println(i.pub);
}}
//Overloading Example1
HCLclass FirstClass { public void Show() { System.out.println("FirstClass: Show function"); }}
class SecondClass extends FirstClass { public void Show(int a) { System.out.println("SecondClass: Show function(overloaded)"); }}
class FirstSecond { public static void main(String[] args) { SecondClass c = new SecondClass(); c.Show(); c.Show(1); }}
//Overriding Example2
class ClassFirst { public void display() { System.out.println("Class First: display"); }
public void show() { System.out.println("Class First: show"); }}
class ClassSecond extends ClassFirst { // Overriden method display() public void display() { System.out.println("Class Second: display"); }
// Cannot override with different access specifier
HCL /* protected void show() { System.out.println("Class Second: show"); } */ }
class UseFirstSecond { public static void main(String[] args) { ClassSecond cs = new ClassSecond(); cs.display(); cs.show(); }}
//Dynamic Method Dispatch Example
class Dynamic { public void show() { System.out.println("Dynamic:show()"); }}
class SubDynamic extends Dynamic { public void show() { System.out.println("SubDynamic:show()"); }}
class UseDynamic { public static void main(String[] args) { Dynamic d = new SubDynamic(); d.show(); }
}
INTERFACE
HCL//simple interface
interface Inter1{ public void fun1(); }class InterImple implements Inter1{ public void fun1(){ System.out.println("Interface 1"); } }class mainClassForInter{ public static void main(String []arg){ InterImple obj1=new InterImple(); Inter1 obj2=obj1;//=new InterImple(); obj2.fun1(); }}
//Extended interface Example
interface Inter1{ public void fun1(); } interface Inter2 extends Inter1{ public void fun2();//all method inside interface should be public } class InterImple implements Inter1,Inter2{ public void fun1(){ System.out.println("Interface 1"); } public void fun2(){ System.out.println("Interface 2"); } } class mainClassForInterface{ public static void main(String []arg){ InterImple obj=new InterImple(); Inter2 obj2=obj; //=new InterImple();
HCL //obj.fun(); obj2.fun1(); obj2.fun2(); }}
//Example for implementing interface in more than one class
interface int1{void show();}
class A implements int1{public void show(){System.out.println("Show");}}
class B implements int1{public void show(){System.out.println("Show");}}
class InterfaceMain{public static void main(String s[]){int1 i=new A();i.show();int1 i=new B();i.show();}}
PACKAGE
//Simple PackageExample
package PackEx;
HCLclass Student{ String name; int age;
Student(String name, int age) { this.name = name; this.age = age; }
void show() { System.out.println("Name:"+name); System.out.println("Age :"+age); }} class PackMain { public static void main(String args[]) { Student stu[] = new Student[3];
stu[0] = new Student("Darshini", 7); stu[1] = new Student("Sanjay", 6); stu[2] = new Student("Praveen", 13);
for(int i=0; i<3; i++) stu[i].show(); }}
//package Example 2
package Example;
public class Pack{ int def=10; private int pri=20; protected int pro=30; public int pub=40; public Pack(){ System.out.println("default"+def); System.out.println("private data"+pri); System.out.println("protected data"+pro); System.out.println("public data"+pub);
HCL } }
class PackExt extends Pack{ PackExt(){ System.out.println("default"+def); System.out.println("private data"+pri); System.out.println("protected data"+pro); System.out.println("public data"+pub);
} public static void main(String args[]){ PackExt P=new PackExt(); }}
//java Example.PackExt
package Example;class Pack1 extends Example.Pack{ public static void main(String args[]){ Pack P=new Pack(); }}
//package Example 3
//sub2.java in folder sub1/sub2package sub1.sub2; public class sub2{ public void mul() { int a=10;int b=a*a; System.out.println("mul from sub2 "+b); } }//subp.java in folder sub1
HCLpackage sub1; public class subp{ public void add(){ int a=20,b=30;int c=a+b; System.out.println("addition in sub1"+c); }}
//mainpack.javaimport sub1.*; import sub1.sub2.*; public class mainpack{ public static void main(String er[]) { subp obj =new subp(); sub2 ob=new sub2(); obj.add(); ob.mul(); }}
ABSTRACT CLASS
//abstract method and abstract class example
abstract class ABC{ abstract void absmethod(); void normmethod(){ System.out.println("This is the normal method"); } void normmethod1(){ System.out.println("This is the method which has definition in the abstract class\n and not overridden in the class which inherit it"); }
HCL}class AbsInh extends ABC{ void absmethod(){ System.out.println("this is a complete abstract method"); } void normmethod(){ System.out.println("this is a normal method overridden in this class"); }
public static void main(String args[]){ AbsInh AI=new AbsInh(); AI.absmethod(); AI.normmethod(); AI.normmethod1(); }
}
COLLECTION CLASSES
//Set usage example
import java.util.*;public class SetExample {
public static void main(String args[]) {Set set = new HashSet();set.add("Bernadine");set.add("Elizabeth");set.add("Gene");set.add("Elizabeth");set.add("Clara");System.out.println(set);Set sortedSet = new TreeSet(set);System.out.println(sortedSet);
}}
//List usage example
HCLimport java.util.*;public class ListExample {
public static void main(String args[]) {List list = new ArrayList();list.add("Bernadine");list.add("Elizabeth");list.add("Gene");list.add("Elizabeth");list.add("Clara");System.out.println(list);System.out.println("2: " + list.get(2));System.out.println("0: " + list.get(0));LinkedList queue = new LinkedList();queue.addFirst("Bernadine");queue.addFirst("Elizabeth");queue.addFirst("Gene");queue.addFirst("Elizabeth");queue.addFirst("Clara");System.out.println(queue);queue.removeLast();queue.removeLast();System.out.println(queue);
}}
//Map usage example
import java.util.*;public class MapExample {
public static void main(String args[]) {Map map = new HashMap();Integer ONE = new Integer(1);for (int i=0, n=args.length; i<n; i++) {
String key = args[i];Integer frequency = (Integer) map.get(key);if (frequency == null) {
frequency = ONE;} else {
int value = frequency.intValue();frequency = new Integer(value + 1);
}
HCLmap.put(key, frequency);
}System.out.println(map);Map sortedMap = new TreeMap(map);System.out.println(sortedMap);
}}
//HasMap Example
//mapping is done acording to the key value//does not accept the duplicate keyimport java.util.*;class ex16{public static void main(String args[]){HashMap h = new HashMap();h.put("roy", new Integer(90));h.put("shelly", new Integer(80));h.put("keats", new Integer(95));h.put("charles", new Integer(38));Set s =h.entrySet();Iterator i = s.iterator();System.out.println("the following are the marks : ");System.out.println("names\t\tmarks ");while(i.hasNext()){Map.Entry e= (Map.Entry)i.next();System.out.println(e.getKey() + "\t\t" + e.getValue());}h.put("macbeth", new Integer(58));
i = s.iterator();System.out.println("the hash map after modification is : ");System.out.println("names\t\tmarks ");while(i.hasNext()){
HCLMap.Entry e= (Map.Entry)i.next();System.out.println(e.getKey() + "\t\t" + e.getValue());}}}
//HashSet usage example
import java.util.*;public class FindDups {
public static void main(String args[]){Set s = new HashSet();for (int i = 0; i < args.length; i++){
if (!s.add(args[i]))System.out.println("Duplicate detected: "
+ args[i]);}System.out.println(s.size() +
" distinct words detected: " +s);}
}
//ArrrayList usage example
import java.util.*;public class Shuffle {
public static void main(String args[]) {List l = new ArrayList();for (int i = 0; i < args.length; i++)
l.add(args[i]);Collections.shuffle(l, new Random());System.out.println(l);
}}
//LinkedList usage example
import java.util.*;public class MyStack {
HCLprivate LinkedList list = new LinkedList();public void push(Object o){
list.addFirst(o);}
public Object top(){return list.getFirst();
}
public Object pop(){return list.removeFirst();
}
public static void main(String args[]) {Car myCar;MyStack s = new MyStack();s.push (new Car());myCar = (Car)s.pop();
}}
//TreeMap Example
//usage of tree map, it willbe in ascending key oder//mapping is done acording to the key value// does no accept the duplicate keyimport java.util.*;class ex17{public static void main(String args[]){TreeMap t = new TreeMap();t.put("roy", new Integer(90));t.put("shelly", new Integer(80));t.put("keats", new Integer(95));t.put("charles", new Integer(38));Set s =t.entrySet();Iterator i = s.iterator();System.out.println("the following are the marks : ");System.out.println("names\t\tmarks ");
HCLwhile(i.hasNext()){Map.Entry e= (Map.Entry)i.next();System.out.println(e.getKey() + "\t\t" + e.getValue());}if (t.containsKey("roy"))System.out.println(" Map contains the entry 'roy'");elseSystem.out.println(" Map doenot contains the entry 'roy'");
t.put("macbeth", new Integer(58));
i = s.iterator();System.out.println("the tree map after modification is : ");System.out.println("names\t\tmarks ");while(i.hasNext()){Map.Entry e= (Map.Entry)i.next();System.out.println(e.getKey() + "\t\t" + e.getValue());}}}
//Enumeration Example using Vector class
import java.util.*;class VectorProg{ public static void main(String []ohm){ Vector a=new Vector(); a.addElement("Sun"); a.addElement("iTech"); a.addElement("T Nagar"); a.addElement("Chennai"); a.addElement("Sun"); a.addElement("iTech"); a.addElement("T Nagar"); a.addElement("Chennai");
HCL a.addElement("Sun"); a.addElement("iTech"); a.addElement("T Nagar"); a.addElement("Chennai"); System.out.println("All Data:"+a); System.out.println("First:"+a.firstElement()); System.out.println("Last:"+a.lastElement());
System.out.println(a.capacity());
Enumeration en=a.elements(); while(en.hasMoreElements())
{ System.out.println(en.nextElement()); }
} }
EXCEPTION HANDLING
//using try catch
class ex3{public static void main(String arg[]){try{int d=2;int a=42/d;System.out.println(" print");System.out.println(a);}catch(ArithmeticException e){System.out.println("Division by zero " +e);
HCL}System.out.println("after catch");}}
//using multiple catch statement class ex4{public static void main(String arg[]){try{int a=arg.length;System.out.println("a = " +a);
int b=10/a;int c[]={ 1};c[20]=45;}catch(ArithmeticException e){System.out.println("Division by zero ");}catch(ArrayIndexOutOfBoundsException e){System.out.println("array out of bounderror " + e);}System.out.println("after catch");}}
//nested try statements
class ex6{public static void main(String arg[]){try{int a=arg.length;int b=10/a;System.out.println(" a = " + a);try{// if one command line arg is used then exception divide by zero
HCLif(a==1) a =a /(a-a);//if twocommand line arg is used array bound errorif(a==2){int c[]={1};c[10]=45;}}catch(ArrayIndexOutOfBoundsException e){ System.out.println("array error " + e);}}catch(ArithmeticException e){System.out.println("arithmetic exception " + e);}System.out.println("after catch");}}
//Finally
class finally_ex{ public static void fin() throws Exception { try {
int arr[]={1,2,3};arr[10]=10;
} catch (ArrayIndexOutOfBoundsException x) { System.out.println("array Exception : " + x); } finally {
HCL System.out.println("finally!"); }
System.out.println("last statement"); }
public static void main(String[] args) { try { fin(); } catch(Exception x) {} }}
//usage of Throws
class Throws{ static void throwsFun() throws IllegalAccessException{ System.out.println("From Throws"); throw new IllegalAccessException(); }
public static void main(String arg[]){ try{ throwsFun(); }catch(IllegalAccessException e){ System.out.println("Caught the Exception"+e); } }}
//user defined exceptions
class ownex extends Exception{int x;
HCLownex(int a){x=a;}public String toString(){return " user defined Exception[ " + x + " ] ";}}class ownexp{static void show(int a) throws ownex{System.out.println("called show(" + a + ")");if(a>10)throw new ownex(a);System.out.println("exit");}public static void main(String args[]){try{System.out.println("first");show(8);show(20);}catch(ownex e){System.out.println("Caught " + e);}}}
JAVA I/O
//Program demonstrates the usage of file classes
import java.io.File;class File_ex{public static void main(String args[]){
HCLFile f1 = new File("in.txt");System.out.println("File name is : " + f1.getName());System.out.println(" path is : " + f1.getPath());System.out.println("Absolute path : " + f1.getAbsolutePath());System.out.println(f1.exists() ? "file exists " : "filedoesnot exist");System.out.println(f1.isDirectory() ? " file is a directory " : "not a dir " );System.out.println(f1.isFile() ? "file is an ordinary file " : "not an ordinaty ifle");System.out.println("the file was last modified at " + f1.lastModified() );
if(f1.canRead())System.out.println("we can read from thefile");
elseSystem.out.println(" we cannot read from the file");
if(f1.canWrite())System.out.println("we can write");
elseSystem.out.println("we cannot write ");
}}
//File Input Stream and File Output Stream
import java.io.*;
class FileStreamsTest { public static void main(String args[]) {
try { FileInputStream fis = new FileInputStream("in.txt"); FileOutputStream fos = new FileOutputStream("out.txt"); int c;
while ((c = fis.read()) != -1) { fos.write(c); }
fis.close(); fos.close();} catch (FileNotFoundException e) { System.err.println("FileStreamsTest: " + e);
HCL} catch (IOException e) { System.err.println("FileStreamsTest: " + e);}
}}
//demonstrate file input/ output stream and spliting of files
import java.io.*;public class split_ex{public static void main (String args[])throws Exception{int size;InputStream f= new FileInputStream("in.txt");System.out.println( "total Bytes : " + (size = f.available()));int n = size/4;System.out.println( "First " + n + "bytes of the file reads at a time");for (int i=0;i< n;i++){System.out.println( (char)f.read());}System.out.println( "Still available : " + f.available() );f.skip(2);System.out.println( "Still available after skipping : " + f.available() );f.close();
String source = " Welcome to java \n"+ " good morning \n" + " bye";byte buf[]= source.getBytes();OutputStream fos= new FileOutputStream("a1.txt");for (int i=0;i<buf.length ;i=i++){fos.write(buf[i]);}fos.close();
OutputStream f1= new FileOutputStream("a2.txt");f1.write(buf);
HCLf1.close();
OutputStream f2= new FileOutputStream("a3.txt");f2.write(buf,buf.length-buf.length/4,buf.length/4);f2.close();
}}
//program that demonstrate the Data I/O Streams
import java.io.*;class DataIOTest {public static void main(String args[]) { // writing parttry { DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt")); double prices[] = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int units[] = { 12, 8, 13, 29, 50 }; String descs[] = { "Java Beans", "Java Applet", "Java Server Pages", "java AWT
Components", "Java Swing"}; for (int i = 0; i < prices.length; i ++) {
dos.writeDouble(prices[i]); dos.writeChar('\t'); dos.writeInt(units[i]); dos.writeChar('\t'); dos.writeChars(descs[i]); dos.writeChar('\n'); } dos.close();} catch (IOException e) { System.out.println("DataIOTest: " + e);} // reading parttry { DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
double price; int unit; String desc; boolean EOF = false;
HCL double total = 0.0; while (!EOF) { try { price = dis.readDouble(); dis.readChar(); unit = dis.readInt(); dis.readChar(); desc = dis.readLine(); System.out.println("You've ordered " + unit + " units of " + desc + " at Rs. " +
price); total = total + unit * price;
} catch(EOFException e) { EOF = true;
} } System.out.println("For a TOTAL of: Rs." + total); dis.close();} catch (FileNotFoundException e) { System.out.println("DataIOTest: " + e);} catch (IOException e) { System.out.println("DataIOTest: " + e);}
}}
//program reads the data from fileStream and write to Buffered Stream
import java.io.*; class str { public static void main(String s[]){ byte b[]; byte p; FileInputStream is; BufferedOutputStream os; File f; for (int i=0; i < s.length;i++){ try{ f=new File(s[i]); b=new byte[(int)f.length()]; is = new FileInputStream(f); is.read(b); is.close();
HCL os = new BufferedOutputStream( new FileOutputStream(s[i]),b.length); p='?'; for(int j=0; j < b.length; j++){ if((p!='\r')&&(b[j]=='\n')) os.write('\r'); p=b[j]; os.write(p); } os.flush(); os.close(); }catch(IOException e){ System.err.println(e.toString()); } } } }
/* Program that converts into uppercase and lowercase using ByteArray and write the content into fileoutputstream*/
//reset() sets the stream pointer to the start of the streamimport java.io.*;class bytearray_ex{public static void main (String args[]) throws IOException{String str ="hai welcome";byte b[]=str.getBytes();ByteArrayInputStream in = new ByteArrayInputStream(b);for(int i = 0; i<2;i++){ int c; while((c=in.read())!=-1) { if(i==0) { System.out.println((char)c);
} else {
HCL System.out.println(Character.toUpperCase((char)c)); } }in.reset();}
// Byte Array output stream
ByteArrayOutputStream bf = new ByteArrayOutputStream();bf.write(b);System.out.println("the String is");System.out.println(bf.toString());System.out.println("adding into an array");byte ba[] = bf.toByteArray();
for(int i = 0; i<ba.length;i++){ System.out.println((char)ba[i]);}//to an output stream System.out.println("writing to outputstream");OutputStream os = new FileOutputStream("test.txt");bf.writeTo(os);os.close();}}
//program to write into a file ie copying a file
import java.io.*;class file_copy{public static void main(String args[]) throws IOException{int i;FileInputStream fi;FileOutputStream fo;try{// open the input file
HCL try{ fi = new FileInputStream(args[0]); }catch(FileNotFoundException e) {System.out.println("Input File not found"); return; }}catch(ArrayIndexOutOfBoundsException e) {System.out.println("copy a file error"); return; }
//open output file try{ fo=new FileOutputStream(args[1]); }catch(FileNotFoundException e) {System.out.println("Error in opening a file"); return; }//copy filetry{do{i=fi.read();if ( i!= -1)fo.write(i);}while(i != -1);
}catch (IOException e){ System.out.println("file error");}fi.close();fo.close();}
}
//Progrma displays the contents of specified directory
import java.io.*;public class File_dir implements FilenameFilter
HCL{String w;public File_dir(String w){this.w="." + w;}public boolean accept(File dir,String name){return name.endsWith(w);}public static void main (String args[])throws IOException{for (int i=0;i<args.length;i++){File f1=new File("d:/stream");FilenameFilter only = new File_dir(args[i]);String s[] = f1.list(only);System.out.println( "printing files with " + args[i] + " extension in the " + f1.getPath() + "
directory");for(int ii = 0;ii<=s.length;ii++)System.out.println(s[i]);}}}
//Filereader and FileWriter
import java.io.*;import java.io.File;class file_read_write{public static void main(String args[]) throws IOException{String s = "abcdefghijklmnopqrstuvwxyz";char buf[]=new char[s.length()];s.getChars(0,s.length(),buf,0);FileWriter fw = new FileWriter("f11.txt");for(int i=0;i<buf.length;i=i+2){fw.write(buf[i]);}
HCLfw.close();
FileWriter fw1 = new FileWriter("f21.txt");fw1.write(buf);fw1.close();
FileReader fr= new FileReader("f21.txt");BufferedReader br = new BufferedReader(fr);while((s=br.readLine()) !=null){System.out.println(s);}fr.close();}}
//program demonstrates the usage of StringReader
import java.util.*;import java.io.*;import java.io.File; class UppercaseConvertor extends FilterReader { public UppercaseConvertor(Reader in) { super(in); } public int read() throws IOException { int c = super.read(); return (c == -1 ? c : Character.toUpperCase((char)c)); } public int read(char[] buf, int offset, int count) throws IOException { int nread = super.read(buf, offset, count); int last = offset + nread; for (int i = offset; i < last; i++) buf[i] = Character.toUpperCase(buf[i]); return nread; }}
HCLclass file_case{public static void main(String[] args) throws IOException{ StringReader src = new StringReader(args[0]); FilterReader f = new UppercaseConvertor(src); int c; while ((c = f.read()) != -1) System.out.print((char)c); System.out.println();}}
//using printwriter class
import java.io.*;class exf10{public static void main(String args[]) throws IOException{PrintWriter pw = new PrintWriter(System.out, true);pw.println("hai");int i = 100;pw.write(i);double d=6.7e-5;pw.println(d);}}
Threads and Thread Synchronisation
Simple thread example
class MyThread extends Thread { private String name, msg; public MyThread(String name, String msg) { this.name = name; this.msg = msg; }
HCL public void run() { System.out.println(name + " starts its execution"); for (int i = 0; i < 5; i++) { System.out.println(name + " says: " + msg); try { Thread.sleep(500);
} catch (InterruptedException ie) {} } System.out.println(name + " finished execution"); }}
public class prg1 { public static void main(String[] args) { MyThread mt1 = new MyThread("thread1", "ping"); MyThread mt2 = new MyThread("thread2", "pong"); mt2.setPriority(Thread.NORM_PRIORITY); mt2.setPriority(Thread.MIN_PRIORITY); mt2.setPriority(Thread.MAX_PRIORITY); mt1.start(); mt2.start(); for(int k=1;k<=10;k++) System.out.println("ok"); System.out.println("ok"); System.out.println("ok"); System.out.println("ok"); System.out.println("ok"); System.out.println("ok");
}}
//Basic Thread example
class BasicThread extends Thread{ char c; BasicThread(char c) { this.c = c;
HCL }
// override run() method in inherited by Thread via // the Runnable interface public void run() { for(int i=0; i<100; i++) { System.out.print(c); try{ sleep((int)(Math.random() * 10)); } catch( InterruptedException e ) { System.out.println("Interrupted Exception “ +
“ caught"); } } }
public static void main(String[] args) { BasicThread bt = new BasicThread('!'); BasicThread bt1 = new BasicThread('*');
bt.start(); bt1.start(); }
}
//Setting Priority to thread
class LowPriority { public static void main(String[] args) { MyThread t1 = new MyThread(1); MyThread t2 = new MyThread(2); t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); t1.start(); t2.start(); }
HCL} class MyThread extends Thread { int id; MyThread(int id) { this.id = id; } public void run(){ for(int i=0; i<10; i++) System.out.println("My id is: " + id); }}
//using wait method
class Waiting { public static void main(String[] args) { MyThread t1 = new MyThread(1); MyThread t2 = new MyThread(2); t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); t1.start(); t2.start(); }}
class MyThread extends Thread { int id; MyThread(int id) { this.id = id; } public synchronized void run(){ for(int i=0; i<10; i++) { if( id==1 && i==5 ) { try{ wait(1000); }catch(InterruptedException e) {}
HCL } System.out.println("My id is: " + id); } }}
//Yielding in threads
class Yielding { public static void main(String[] args) { MyThread t1 = new MyThread(1); MyThread t2 = new MyThread(2); t1.setPriority(Thread.NORM_PRIORITY);
// won't yield() for lower priority t2.setPriority(Thread.NORM_PRIORITY); t1.start(); t2.start(); }}
class MyThread extends Thread { int id; MyThread(int id) { this.id = id; } public synchronized void run(){ for(int i=0; i<100; i++) { if( id==1 && i==30 ) { yield(); } System.out.println("My id is: " + id); } }}
//using sleep methods in java
HCLclass Sleeping { public static void main(String[] args) { MyThread t1 = new MyThread(1); MyThread t2 = new MyThread(2); t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); t1.start(); t2.start(); }}
class MyThread extends Thread { int id; MyThread(int id) { this.id = id; } public void run(){ for(int i=0; i<10; i++) { if( id==1 && i==5 ) { try{ sleep(1000); }catch(InterruptedException e) {} } System.out.println("My id is: " + id); } }}
//program for using isAlive method
public class xyz implements Runnable {
private int countDown = 5; public xyz() { System.out.println("\nThread constructor...\n"); } public void run() {
HCL while(true) {System.out.println(" - Thread ( Current Countdown = " + countDown + " )");
for (int j = 0; j < 300000000; j++) { // This is a test... } if (--countDown == 0) { System.out.println("\nEnding thread...\n"); return; } } }
private static void doThreadTest() throws java.lang.InterruptedException {
int checkCount = 0;
Thread th = new Thread(new xyz()); th.start();
while (th.isAlive()) { Thread.sleep(500);System.out.println("Thread is still alive. Count = " + ++checkCount); }System.out.println("\n<< Finished running and checking thread!!! >>\n");}
public static void main(String[] args) throws java.lang.InterruptedException {
System.out.println("\n<< MAIN METHOD (Begin) >>"); doThreadTest(); System.out.println("<< MAIN METHOD (End) >>\n");
}
HCL}
//example program for thread join
public class join1 implements Runnable {
private int currentThread = 0; private int countDown = 5; public join1(int curThread) { this.currentThread = curThread; System.out.println("\nConstructing thread (" + curThread + ")...\n"); }
public void run() {
System.out.println("[ Starting New Thread ] : The name of this thread is " + Thread.currentThread().getName()); System.out.println("=========================================="); System.out.println();
if (currentThread == 1) {
while (true) {
System.out.println(" - Thread " + currentThread + " ( Current Countdown = " + countDown + " )"); for (int j = 0; j < 300000000; j++) { // This is a test... }
if (--countDown == 0) { System.out.println("\nEnding thread " + currentThread + "...\n"); break; } } return; }
HCL if (currentThread == 2) {
while (true) {
System.out.println(" - Thread " + currentThread + " ( Current Countdown = " + countDown + " )"); for (int j = 0; j < 100000000; j++) { // This is a test... }
if (--countDown == 0) { System.out.println("\nEnding thread " + currentThread + "...\n"); break; } } return; }
}
private static void doThreadTest() throws java.lang.InterruptedException {
//Start the first thread of control and name it "Thread //1". Thread th1 = new Thread(new join1(1)); th1.setName("gopi krishnaji"); th1.start();
// Lets take a little break... Thread.sleep(1000);
// Create a second thread of control and name it "Thread 2". Thread th2 = new Thread(new join1(2)); th2.setName("alagappan"); th2.start();
System.out.println(); System.out.println("Both threads have been started....");System.out.println("Will now wait until both threads are completed...");
HCL System.out.println();
// th1.join();// th2.join();
System.out.println("All working threads are complete...\n");
}
public static void main(String[] args) throws java.lang.InterruptedException {
System.out.println("\n<< MAIN METHOD (Begin) >>");
doThreadTest(); System.out.println("<< MAIN METHOD (End) >>\n");
}
}
//Synchronization Example 1
public class SyncExample {private static lockObject = new Object();private static class Thread1 extends Thread {
public void run() {synchronized (lockObject) {
x = y = 0;System.out.println(x);
}}
}
private static class Thread2 extends Thread {public void run() {
synchronized (lockObject) {x = y = 1;System.out.println(y);
HCL}
}}
public static void main(String[] args) {new Thread1().run();new Thread2().run();
}}
//Synchronization Example 2
import java.io.*;
class Account { int balance=1000;
public synchronized void deposit( ) {try{
int deposit_amount; String s;int n;BufferedReader in=new BufferedReader(
new InputStreamReader(System.in));deposit_amount=Integer.parseInt(
in.readLine()); balance += deposit_amount;
}catch(java.io.IOException ioe) {
ioe.printStackTrace(); }
}
public synchronized void withdraw( ) {try{
int deposit_amount; String s;int n;BufferedReader in =new BufferedReader(new
InputStreamReader(System.in));deposit_amount=Integer.parseInt(
in.readLine());
HCLbalance -= deposit_amount;
}catch(java.io.IOException ioe) {
ioe.printStackTrace(); }
}
public synchronized void enquire( ) {System.out.println(balance);
}}
class MyThread implements Runnable {Account account;
public MyThread (Account s) {account = s;} public void run() {
account.deposit(); }
} // end class MyThread class YourThread implements Runnable {
Account account; public YourThread (Account s) { account = s;} public void run() { account.withdraw(); }} // end class YourThread
class HerThread implements Runnable {Account account;
public HerThread (Account s) { account = s; } public void run() {account.enquire(); }} // end class HerThread
class InternetBankingSystem1 {public static void main(String [] args ) {
Account accountObject = new Account (); Thread t1 = new Thread(new
MyThread(accountObject)); Thread t2 = new Thread(new
YourThread(accountObject));Thread t3 = new Thread(new
HerThread(accountObject)); t1.start();
HCL t2.start(); t3.start();
// DO some other operation} // end main()
}
APPLET
//Program that displays button
import java.applet.*;import java.awt.*;
public class prg1 extends Applet{ public void init() { Button b1=new Button(); Button b2=new Button("india"); Button b3=new Button(); Button b4=new Button();
b2.getText(); b3.setLabel("welcome"); b4.setLabel(b2.getLabel());
add(b1); add(b2); add(b3); add(b4); }}
//<applet code="prg1.class" width=600 height=400> </applet>
//program that uses button class methods
import java.applet.*;import java.awt.*;
public class prg1 extends Applet
HCL{ public void init() { Button b1=new Button(); Button b2=new Button("india"); Button b3=new Button(); Button b4=new Button();
b1.setBackground( Color.RED ); b2.setBackground(Color.green); b2.getText(); b3.setLabel("welcome"); String s; s=b2.getLabel(); b4.setLabel(s); add(b1); add(b2); add(b3); add(b4); }}
//<applet code="prg1.class" width=600 height=400> </applet>
//using Color class to change background color
import java.applet.*;import java.awt.*;
public class prg3 extends Applet{ public void init() { Button b=new Button("welcome to colors");
Color c=new Color(157,197,134);
b.setBackground(c);
add(b); }}
HCL//<applet code="prg3" width=600 height=400> </applet>
//demo program for Label class
import java.applet.*;import java.awt.*;
public class prg4 extends Applet{ public void init() { Label l=new Label(); // or Label l=new Label("click this button");
Button b=new Button("happy");
l.setAlignment(Label.LEFT); // or l.setAlignment(Label.CENTER); or l.setAlignment(Label.RIGHT);
l.setBackground(Color.red); l.setText("welcome");
setBackground(Color.green); add(l); add(b); }}
//<applet code="prg4" width=700 height=750> </applet>
//using Label class methods
import java.applet.*;import java.awt.*;public class label extends Applet{ public void init() { Label l=new Label(); // or Label l=new Label("enter your name");
HCL Label l1=new Label("enter your name",Label.LEFT); Label l2=new Label("enter your name",Label.CENTER ); Label l3=new Label("enter your name",Label.RIGHT);
l.setAlignment(Label.RIGHT); l.setBackground(Color.red);l.setForeground(Color.WHITE);
add(l); add(l1); add(l2); add(l3);
}}
//<applet code="label.class" width=600 height=400></applet>
//program that uses TextField class
import java.applet.*;import java.awt.*;
public class prg5 extends Applet{ public void init() { TextField t1=new TextField();//or TextField t1=new TextField("enter your name");
TextField t2=new TextField(20); TextField t3=new TextField(20); TextField t4=new TextField(20);
t1.setColumns(25); t1.setBackground(Color.cyan);
t2.setEchoChar('!');
t3.setText("india"); t4.setText(t3.getText());
t4.setEditable(false);
t3.setVisible(false); //or t3.hide();
HCL add(l); add(t1); add(t2); add(t3); add(t4); }}
//<applet code="prg5" width=700 height=750> </applet>
//program to use TextArea class
import java.applet.*;import java.awt.*;
public class prg6 extends Applet{ public void init() {String s="zslzs \nsn sdg asdg asdg asd g\nasdff asdg asdg asd g\n \n";
TextArea ta=new TextArea();//or TextArea ta=new TextArea("hello");or TextArea ta=new TextArea(s);
TextArea ta2=new TextArea(4,4); TextArea ta3=new TextArea(s,5,6); TextArea ta4=new TextArea(s,5,6,TextArea.SCROLLBARS_NONE); ta.insert("welcome to java",24); ta.replaceRange("happy birthday",2,4); add(ta); add(ta2);add(ta3);add(ta4); }}
//<applet code="prg6" width=700 height=750> </applet>
//program for using TextArea class methods
import java.applet.*;import java.awt.*;
public class prg7 extends Applet{ public void init()
HCL { TextArea ta=new TextArea("welcome to textarea",10,40); ta.setEditable(false);// or ta.setEditable(true); ta.setEnabled(false); // or ta.setEnabled(true); add(ta); add(t); }}
//<applet code="prg7" width=700 height=750> </applet>
//using Font class in TextField
import java.awt.*;import java.applet.*;public class ta extends Applet{ public void init() { TextField t=new TextField(); TextArea ta=new TextArea("apple",10,30,TextArea.SCROLLBARS_NONE);ta.setForeground(Color.red);
Font f=new Font("Comic Sans MS",Font.HANGING_BASELINE,20);ta.setFont(f);t.setForeground(ta.getForeground());add(ta); add(t); }}//<applet code="ta.class" width=600 height=400></applet>
//demo program that uses checkbox
import java.applet.*;import java.awt.*;
public class checkbox extends Applet{ public void init() { Checkbox c1=new Checkbox(); Checkbox c2=new Checkbox("soccer");
HCL Checkbox c3=new Checkbox("cricket",true); add(c1); add(c2); add(c3); }}
//<applet code="checkbox.class" width=600 height=500></applet>
//using radio button
import java.applet.*;import java.awt.*;
public class radio extends Applet{ public void init() { CheckboxGroup cbg1=new CheckboxGroup(); CheckboxGroup cbg2=new CheckboxGroup();
Checkbox c1=new Checkbox("male",false,cbg1); Checkbox c2=new Checkbox("female",false,cbg1);
Checkbox c3=new Checkbox("pass",true,cbg2); Checkbox c4=new Checkbox("fail",true,cbg2);
add(c1); add(c2); add(c3); add(c4);
}}//<applet code="radio.class" width=600 height=500></applet>
//using choice control
import java.applet.*;import java.awt.*;public class choice extends Applet{ public void init() { Choice l=new Choice();
HCL l.add("red"); l.add("green"); l.add("blue"); l.add("orange"); l.add("white"); l.add("black"); l.add("light orange"); l.add("light white"); l.add("light black"); l.add("light red"); l.add("light green"); l.add("light blue"); l.select(5); add(l); }}//<applet code="choice.class" width=900 height=700></applet>
//program that uses List class
import java.applet.*;import java.awt.*;public class list extends Applet{ public void init() { List l=new List(); //or List l=new List(8); or List l=new List(8,true); l.add("red"); l.add("green"); l.add("blue"); l.add("orange"); l.add("white"); l.add("black"); l.add("light orange"); l.add("light white"); l.add("light black"); l.add("light red"); l.add("light green"); l.add("light blue"); l.select(5); add(l);
HCL }}
//<applet code="list.class" width=900 height=700></applet>
//using scrollbar-Type I
import java.applet.*;import java.awt.*;public class scroll extends Applet{ public void init() { setLayout(null); Scrollbar s=new Scrollbar();//or Scrollbar s=new Scrollbar(Scrollbar.VERTICAL); s.setBounds(0,0,50,1000); add(s); }}
//<applet code="scroll.class" width=900 height=700></applet>
//using scrollbar-Type II
import java.applet.*;import java.awt.*;public class scroll extends Applet{ public void init() { setLayout(null); Scrollbar sb=new Scrollbar(Scrollbar.VERTICAL,150,20,1,300); //orientation, init val , thumbsize ,min, max,
sb.setBounds(0,0,50,1000); add(sb); }}
//<applet code="scroll.class" width=900 height=700></applet>
HCL
//following programs shows the different method in Graphics class //prg1
import java.applet.*;import java.awt.*;public class paint extends Applet{ public void paint(Graphics g) { Font f=new Font(“Arial”,Font.BOLD,30); g.setFont(f); g.setColor(Color.red); g.drawString("happy friday",300,200);}}//<applet code="paint.class" width=900 height=700></applet>
//prg2
import java.applet.*;import java.awt.*;public class paint extends Applet{ public void paint(Graphics g) { g.drawLine(50,50,100,100); g.drawRect(150,150,50,75); //or g.drawRoundRect(150,150,50,75,5,5); }}//<applet code="paint.class" width=900 height=700></applet>
//prg3
import java.applet.*;
HCLimport java.awt.*;public class paint extends Applet{ public void paint(Graphics g) { g.fillRect(250,250,100,75); //or g.fillRoundRect(250,250,100,75,5,5);
g.clearRect(260,260,10,10);
g.copyArea(270,270,10,100,300,300);
g.drawOval(100,500,150,100);
}}//<applet code="paint.class" width=900 height=1000></applet>
//prg4
import java.applet.*;import java.awt.*;public class paint extends Applet{ public void paint(Graphics g) { g.drawOval(100,100,150,100); // or g.fillOval(100,100,150,100); }}//<applet code="paint.class" width=900 height=1000></applet>
//prg5
import java.applet.*;import java.awt.*;public class paint extends Applet{ public void paint(Graphics g) { g.drawArc(20,50,80,80,0,85); // or g.fillArc(20,50,80,80,0,85);
HCL }}//<applet code="paint.class" width=900 height=1000></applet>
//prg6
import java.applet.*;import java.awt.*;public class img extends Applet{ Image img; public void init() { img=getImage(getCodeBase(),"xyz.jpg"); } public void paint(Graphics g) { g.drawImage(img,100,100,this); }}
//<applet code="img.java" width=700 height=600></applet>
//prg7
/*<applet code ="a13" height = 300 width = 500></applet>*///drawing linesimport java.applet.*;import java.awt.*;
public class a13 extends Applet {
int width, height;
public void init() { width = getSize().width;
HCL height = getSize().height; setBackground( Color.black ); }
public void paint( Graphics g ) { g.setColor( Color.green ); for ( int i = 0; i < 10; ++i ) { g.drawLine( width, height, i * width / 10, 0 ); } }}
//prg8
/*<applet code = "a21" height = 600 width = 300></applet>*/import java.applet.*;import java.awt.*;
public class a21 extends Applet implements Runnable {
int width, height; int i = 0; Thread t = null; boolean threadSuspended;
// Executed when the applet is first created. public void init() { System.out.println("init(): begin"); width = getSize().width; height = getSize().height; setBackground( Color.black ); System.out.println("init(): end"); }
// Executed when the applet is destroyed. public void destroy() { System.out.println("destroy()"); }
// Executed after the applet is created; and also whenever // the browser returns to the page containing the applet. public void start() { System.out.println("start(): begin");
HCL if ( t == null ) { System.out.println("start(): creating thread"); t = new Thread( this ); System.out.println("start(): starting thread"); threadSuspended = false; t.start(); } else { if ( threadSuspended ) { threadSuspended = false; System.out.println("start(): notifying thread"); synchronized( this ) { notify(); } } } System.out.println("start(): end"); }
// Executed whenever the browser leaves the page containing the applet. public void stop() { System.out.println("stop(): begin"); threadSuspended = true; }
// Executed within the thread that this applet created. public void run() { System.out.println("run(): begin"); try { while (true) { System.out.println("run(): awake");
// Here's where the thread does some work ++i; // this is shorthand for "i = i+1;" if ( i == 10 ) { i = 0; } showStatus( "i is " + i );
// Now the thread checks to see if it should suspend itself if ( threadSuspended ) { synchronized( this ) {
HCL while ( threadSuspended ) { System.out.println("run(): waiting"); wait(); } } } System.out.println("run(): requesting repaint"); repaint(); System.out.println("run(): sleeping"); t.sleep( 1000 ); // interval given in milliseconds } } catch (InterruptedException e) { } System.out.println("run(): end"); }
// Executed whenever the applet is asked to redraw itself. public void paint( Graphics g ) { System.out.println("paint()"); g.setColor( Color.green ); g.drawLine( width, height, i * width / 10, 0 ); }}
EVENTS AND LISTENER
//demo program1 for ActionListener using Button
import java.applet.*;import java.awt.*;import java.awt.event.*;
public class button extends Applet implements ActionListener{
Button b; public void init(){
b=new Button("click me");b.addActionListener(this);add(b);
HCL}
public void actionPerformed(ActionEvent ae){
showStatus("you pressed the button");}
}
//<applet code="button" width=700 height=600></applet>
//demo program2 for ActionListener using Button and TextField
import java.applet.*;import java.awt.*;import java.awt.event.*;
public class button2 extends Applet implements ActionListener{
Button b1,b2,b3,b4;TextField t1,t2,t3; public void init(){
t1=new TextField(10);t2=new TextField(10);t3=new TextField(10);
b1=new Button("+");b1.addActionListener(this);
b2=new Button("-");b2.addActionListener(this);
b3=new Button("*");b3.addActionListener(this);
b4=new Button("/");b4.addActionListener(this);
add(t1);add(t2);add(b1);add(b2);add(b3);add(b4);
HCLadd(t3);
}
public void actionPerformed(ActionEvent ae){
String s;int a,b,c;s=ae.getActionCommand();if(s.equals("+")){
a=Integer.parseInt(t1.getText());b=Integer.parseInt(t2.getText());c=a+b;t3.setText(String.valueOf(c));
}else if(s.equals("-")){
a=Integer.parseInt(t1.getText());b=Integer.parseInt(t2.getText());c=a-b;t3.setText(String.valueOf(c));
}else if(s.equals("*")){
a=Integer.parseInt(t1.getText());b=Integer.parseInt(t2.getText());c=a*b;t3.setText(String.valueOf(c));
}else{
a=Integer.parseInt(t1.getText());b=Integer.parseInt(t2.getText());c=a/b;t3.setText(String.valueOf(c));
}}
}
//<applet code="button2" width=700 height=600></applet>
HCL//demo program3 for ActionListener using Button and TextField
/*<applet code ="a8" height = 600 width = 300></applet>*/import java.applet.Applet;import java.awt.*;import java.awt.event.*;public class a8 extends Applet implements ActionListener{TextField t;Button b;public void init(){t= new TextField(20);add(t);b=new Button("click me");add (b);b.addActionListener(this);}public void actionPerformed(ActionEvent e){String msg=new String("Welcome to USA");if(e.getSource() == b){t.setText(msg);}
}}
//demo program for FocusListener using TextField
import java.applet.*;import java.awt.*;import java.awt.event.*;
public class focus extends Applet implements FocusListener{
TextField t1,t2,t3;
HCL public void init(){
t1=new TextField(10);t2=new TextField(10);t3=new TextField(10);
add(t1);add(t2);add(t3);t3.addFocusListener(this);
}
public void focusGained(FocusEvent ae){
int a,b,c;a=Integer.parseInt(t1.getText());b=Integer.parseInt(t2.getText());c=a+b;t3.setText(String.valueOf(c));
}
public void focusLost(FocusEvent ae){}
}
//<applet code="focus" width=700 height=600></applet>
//demo program for MouseListener and MouseMotionListener
/*<applet code = "a18" height = 600 width = 300></applet>*/import java.applet.*;import java.awt.*;import java.awt.event.*;
public class a18 extends Applet implements MouseListener, MouseMotionListener {
HCL int width, height; int mx, my; // the mouse coordinates boolean isButtonPressed = false;
public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black );
mx = width/2; my = height/2;
addMouseListener( this ); addMouseMotionListener( this ); }
public void mouseEntered( MouseEvent e ) { // called when the pointer enters the applet's rectangular area showStatus("mouse entered"); } public void mouseExited( MouseEvent e ) { // called when the pointer leaves the applet's rectangular area showStatus("mouse exited"); } public void mouseClicked( MouseEvent e ) { // called after a press and release of a mouse button // with no motion in between // (If the user presses, drags, and then releases, there will be // no click event generated.) showStatus("mouse clicked"); } public void mousePressed( MouseEvent e ) { // called after a button is pressed down isButtonPressed = true; setBackground( Color.gray ); repaint(); // "Consume" the event so it won't be processed in the // default manner by the source which generated it. e.consume(); } public void mouseReleased( MouseEvent e ) { // called after a button is released isButtonPressed = false; setBackground( Color.black );
HCL repaint(); e.consume(); } public void mouseMoved( MouseEvent e ) { // called during motion when no buttons are down mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); repaint(); e.consume(); } public void mouseDragged( MouseEvent e ) { // called during motion with buttons down mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); repaint(); e.consume(); }
public void paint( Graphics g ) { if ( isButtonPressed ) { g.setColor( Color.black ); } else { g.setColor( Color.gray ); } g.fillRect( mx-20, my-20, 40, 40 ); }}
//demo program for KeyListener
/*<applet code = "ab" height = 500 width = 500 ></applet>*//*press a key to see the display on the screen*/import java.awt.*;import java.awt.event.*; import java.applet.*;public class ab extends Applet implements KeyListener{
HCLint i;String s="";String s1="";public void init(){addKeyListener(this);requestFocus();}public void keyPressed(KeyEvent e){i=e.getKeyCode();s=e.getKeyText(i);repaint();}public void keyReleased(KeyEvent e){i = e.getKeyCode();s =e.getKeyText(i);repaint();}public void keyTyped(KeyEvent e){}public void paint(Graphics g){g.drawString(s,30,10);g.drawString(s1,60,10);}}
//demo program to combine KeyListener and MouseListener
//keyboard Event/*<applet code = "a19" height = 600 width = 300></applet>*/import java.applet.*;import java.awt.*;import java.awt.event.*;
HCLpublic class a19 extends Applet implements KeyListener, MouseListener {
int width, height; int x, y; String s = "";
public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black );
x = width/2; y = height/2;
addKeyListener( this ); addMouseListener( this ); }
public void keyPressed( KeyEvent e ) {
showStatus("key pressed");}
public void keyReleased( KeyEvent e ) {
showStatus("key released"); }
public void keyTyped( KeyEvent e ) { char c = e.getKeyChar(); if ( c != KeyEvent.CHAR_UNDEFINED ) { s = s + c; repaint(); e.consume(); } }
public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mousePressed( MouseEvent e ) { } public void mouseReleased( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { x = e.getX();
HCL y = e.getY(); s = ""; repaint(); e.consume(); }
public void paint( Graphics g ) { g.setColor( Color.gray ); g.drawLine( x, y, x, y-10 ); g.drawLine( x, y, x+10, y ); g.setColor( Color.green ); g.drawString( s, x, y ); }}
//program for AdjustmentListener
import java.awt.*;import java.applet.*;import java.awt.event.*;public class xyz extends Applet implements AdjustmentListener{ Scrollbar sb1,sb2,sb3;
public void init() { setLayout(null); sb1=new Scrollbar(Scrollbar.VERTICAL,1,10,0,255); sb2=new Scrollbar(Scrollbar.VERTICAL,1,10,0,255); sb3=new Scrollbar(Scrollbar.VERTICAL,1,10,0,255);
sb1.setBounds(300,50,50,300); sb2.setBounds(400,50,50,300); sb3.setBounds(500,50,50,300);
sb1.addAdjustmentListener(this); sb2.addAdjustmentListener(this); sb3.addAdjustmentListener(this);
add(sb1); add(sb2); add(sb3);
HCL } public void adjustmentValueChanged(AdjustmentEvent ae) { repaint(); } public void paint(Graphics g) { int x,y,z; x=sb1.getValue(); y=sb2.getValue(); z=sb3.getValue(); Color c=new Color(x,y,z); setBackground(c); }}//<applet code="xyz.class" width=700 height=700></applet>
//program for ItemListener using Checkbox
import java.awt.*;import java.applet.*;import java.awt.event.*;public class xyz2 extends Applet implements ItemListener{ Checkbox c1,c2,c3; public void init() { c1=new Checkbox("red"); c2=new Checkbox("green"); c3=new Checkbox("blue");
c1.addItemListener(this); c2.addItemListener(this); c2.addItemListener(this);
add(c1); add(c2); add(c3);
HCL } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { showStatus("red= "+c1.getState()+" green= "+c2.getState()+" blue=" +c3.getState()); }}//<applet code="xyz2.class" width=700 height=700></applet>
//program for ItemListener using CheckboxGroup-radio button
import java.awt.*;import java.applet.*;import java.awt.event.*;public class xyz3 extends Applet implements ItemListener{ Checkbox c1,c2,c3; CheckboxGroup cbg; public void init() { cbg=new CheckboxGroup();
c1=new Checkbox("red",false,cbg); c2=new Checkbox("green",false,cbg); c3=new Checkbox("blue",false,cbg);
c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this);
add(c1); add(c2); add(c3); } public void itemStateChanged(ItemEvent ie) {
HCL if(cbg.getSelectedCheckbox().getLabel().equals("red")) setBackground(Color.red); else if(cbg.getSelectedCheckbox().getLabel().equals("green")) setBackground(Color.green); else setBackground(Color.blue); }}//<applet code="xyz3.class" width=700 height=500></applet>
//program for ItemListener using Choice and TextField
import java.awt.*;import java.applet.*;import java.awt.event.*;public class xyz3 extends Applet implements ItemListener{ Choice c1; TextField t; public void init() { c1=new Choice(); t=new TextField(20); c1.add("india"); c1.add("japan"); c1.add("canada"); c1.add("usa"); c1.add("srilanka"); c1.addItemListener(this); add(t); add(c1); } public void itemStateChanged(ItemEvent ie) { t.setText(c1.getSelectedItem()); }}//<applet code="xyz3.class" width=700 height=500></applet>
HCL//program for ActionListener using List
import java.awt.*;import java.applet.*;import java.awt.event.*;public class xyz4 extends Applet implements ActionListener{ List l1; public void init() { l1=new List();
l1.add("red"); l1.add("green"); l1.add("blue"); l1.add("cyan"); l1.add("black");
l1.addActionListener(this); add(l1); } public void actionPerformed(ActionEvent ae) { String s=l1.getSelectedItem(); if(s.equals("red")) setBackground(Color.red); else if(s.equals("green")) setBackground(Color.green); else if(s.equals("blue")) setBackground(Color.blue); else if(s.equals("cyan")) setBackground(Color.blue); else if(s.equals("black")) setBackground(Color.black); }}//<applet code="xyz4.class" width=700 height=500></applet>
HCLLAYOUT
//program for FlowLayout
/*<applet code = "app2b.class" HEIGHT = 300 WIDTH = 300></applet>*/import java.awt.*;import java.applet.*; import java.awt.event.*;import java.lang.*;public class app2b extends Applet implements ItemListener{String s = "";Checkbox c1, c2, c3;public void init(){setLayout(new FlowLayout(FlowLayout.LEFT)); c1 = new Checkbox("apple", null, true); c2= new Checkbox("Orange"); c3= new Checkbox("Grapes");add(c1);add(c2);add(c3);
c1.addItemListener(this);c2.addItemListener(this);c3.addItemListener(this);}public void itemStateChanged(ItemEvent e){repaint();}public void paint(Graphics g){s = " apple is : " + c1.getState();g.drawString(s, 6,80);s= "Orange is :" + c2.getState();g.drawString(s, 6,100);s="Grapes : " +c3.getState();g.drawString(s, 6,120);//g.drawString(c4.getState(), 6,140);}
HCL}
// program for BorderLayout
/*<applet code = "app2a.class" HEIGHT = 300 WIDTH = 300></applet>*/import java.awt.*;import java.applet.*; import java.util.*;public class app2a extends Applet {public void init(){setLayout(new BorderLayout());add(new Button("This is on the top"),BorderLayout.NORTH);add(new Label("Footer"),BorderLayout.SOUTH);add(new Button("RIGHT"),BorderLayout.EAST);add(new Button("LEFT"),BorderLayout.WEST);add(new Button("six"));}}
// program for GridLayout
/*<applet code = "app2c.class" HEIGHT = 300 WIDTH = 300></applet>*/import java.awt.*;import java.applet.*; import java.awt.event.*;public class app2c extends Applet {static final int n = 4;public void init(){setLayout(new GridLayout(n, n));setFont(new Font("sansSerif", Font.BOLD, 24));for(int i = 0; i<n;i++){for(int j=0; j < n ; j++){int k = i * n + j ;
HCLif( k > 0)add(new Button("" + k));}}}}
// program for CardLayout
import java.awt.*;import java.applet.Applet;import java.awt.event.*;
/* This applet demonstrates using the CardLayout manager.Pressing one of three buttons will cause a different "card" to bedisplayed.*///<applet code=card1 width=600 height=500></applet>public class card1 extends Applet implements ActionListener{ Panel cardPanel; // the container that will hold the various "cards" Panel firstP, secondP, thirdP; // each of these panels will constitute the "cards" Panel buttonP; // panel to hold three buttons Button first, second, third; // the three buttons CardLayout ourLayout; // the card layout object public void init() { //create cardPanel which is the panel that will contain the three "cards" cardPanel = new Panel(); //create the CardLayout object ourLayout = new CardLayout(); //set card Panel's layout to be our Card Layout cardPanel.setLayout (ourLayout); //create three dummy panels (the "cards") to show firstP = new Panel(); firstP.setBackground(Color.blue); secondP = new Panel(); secondP.setBackground(Color.yellow);
HCL thirdP = new Panel(); thirdP.setBackground(Color.green); //create three buttons and add ActionListener first = new Button("First"); first.addActionListener(this); second = new Button("Second"); second.addActionListener(this); third = new Button("Third"); third.addActionListener(this); //create Panel for the buttons and add the buttons to it buttonP = new Panel(); // Panel's default Layout manager is FlowLayout buttonP.add(first); buttonP.add(second); buttonP.add(third); //setLayout for applet to be BorderLayout this.setLayout(new BorderLayout()); //button Panel goes South, card panels go Center this.add(buttonP, BorderLayout.SOUTH); this.add(cardPanel, BorderLayout.CENTER); // add the three card panels to the card panel container // method takes 1.) an Object (the card) 2.) an identifying String // first one added is the visible one when applet appears cardPanel.add(firstP, "First"); //blue cardPanel.add(secondP, "Second"); //yellow cardPanel.add(thirdP, "Third"); //green } //------------------------------------ // respond to Button clicks by showing the so named Panel // note use of the CardLayout method show(Container, "identifying string") public void actionPerformed(ActionEvent e) { if (e.getSource() == first)
HCL ourLayout.show(cardPanel, "First"); if (e.getSource() == second) ourLayout.show(cardPanel, "Second"); if (e.getSource() == third) ourLayout.show(cardPanel, "Third"); }} // end class
FRAME//simple Frame
import java.awt.*;import java.awt.event.*;
public class frame2 extends Frame { public frame2() { setSize(300,300); show(); }} public static void main(String args[]) { frame2 d=new frame2(); }}
//sample Frame
import java.awt.*;
public class frame2 extends Frame { public frame2(String s) { super(s);
HCL setSize(300,300); show(); } public static void main(String args[]) { frame2 d=new frame2("welcome to java"); }}
//Events and Listeners using Frame
import java.awt.*;import java.awt.event.*;
class xyz extends Frame implements ActionListener{ Button b; public xyz() { setLayout(new FlowLayout()); b=new Button("dispose"); b.addActionListener(this); add(b); setBounds(200,200,300,300); show(); } public void actionPerformed(ActionEvent ae) { dispose(); } }
public class frame1 extends Frame implements ActionListener{ Button b1,b2; xyz x; public frame1() { setLayout(new FlowLayout()); b1=new Button("create");
HCL b2=new Button("dispose"); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); setSize(300,300); show(); }
public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand().equals("create")) x=new xyz(); else if(ae.getActionCommand().equals("dispose")) { dispose(); System.exit(0); } } public static void main(String args[]) { frame1 d=new frame1(); }}
//using Frame in Applet
import java.applet.*;import java.awt.*;
public class frames extends Applet{ Frame window = new Frame("This is the Frame's Title Bar!"); Button btn = new Button("Create a new Frame");
public void init() { add(new Label("Hit this button to")); add(btn); add(new Label("."));
HCL add(new Label("The new Frame is independent of the applet.")); add(new Label("You can maximize and minimize it by using")); add(new Label("the buttons on the top right or the control icon.")); add(new Label("on the top left. You will not be able to close it.")); add(new Label("You must use the applet's button to do that.")); add(new Label("In order to handle Frame events you need to ")); add(new Label("create a separate class for it.")); window.setLayout(new FlowLayout()); window.add(new Label("This is the Frame.")); window.add(new Label("You can resize it, move it")); window.add(new Label("and perform other Windows operations."));
}
public boolean action(Event evt, Object whatAction) { if((evt.target instanceof Button)) {
String buttonLabel = (String) whatAction;if (buttonLabel == "Destroy the Frame") {
window.hide(); window.dispose();
btn.setLabel("Create a new Frame"); return true; }if (buttonLabel == "Create a new Frame") { window.resize(300,200); window.show();
btn.setLabel("Destroy the Frame"); return true; }
} return false; }}
/*<applet code="frames.class" height = 300 width=500></applet>*/
HCL//using window object in Frame
import java.applet.*;import java.awt.*;
public class frames2 extends Applet
{ Frame window = new demoframe("This is the first frame.");
public void init() { window.show(); add(new Label("Hit this button to")); add(new Button("Create another Frame")); }
public boolean action(Event evt, Object whatAction) { if((evt.target instanceof Button)) {
String buttonLabel = (String) whatAction;if (buttonLabel == "Create another Frame") {
Frame window = new demoframe("This is another frame."); window.show();
} } return false; }}class demoframe extends Frame{
demoframe(String title) { super(title); MenuBar topbar = new MenuBar(); setLayout(new FlowLayout()); setMenuBar(topbar); Menu fileMenu = new Menu("File");
HCL topbar.add(fileMenu); fileMenu.add("Quit"); add(new Label("Use the File menu to close this Window.")); resize(300,100); } public boolean action(Event evt, Object whatAction) { if (evt.target instanceof MenuItem) { if ((String)whatAction == "Quit") { hide(); dispose(); return true; } } return false; } public boolean handleEvent(Event evt) { if (evt.id == Event.WINDOW_DESTROY) {
hide(); dispose();
return true; } return super.handleEvent(evt); } }/*<applet code="frames2.class" height=500 width=500></applet>*/
//Menu using Frame
import java.awt.*;import java.awt.event.*;public class menu extends Frame implements ActionListener{ public menu(String s) { super(s);
HCL MenuBar mb=new MenuBar(); setMenuBar(mb); Menu file=new Menu("File"); Menu edit=new Menu("Edit"); Menu format=new Menu("Format");
MenuItem New=new MenuItem("New"); MenuItem Open=new MenuItem("Open..."); MenuItem Save=new MenuItem("Save"); MenuItem Save_As=new MenuItem("Save As..."); MenuItem hyphen1=new MenuItem("-"); MenuItem page_setup=new MenuItem("Page Setup"); MenuItem print=new MenuItem("Print"); MenuItem hyphen2=new MenuItem("-"); MenuItem exit=new MenuItem("exit");
exit.addActionListener(this);
file.add(New); file.add(Open); file.add(Save); file.add(Save_As); file.add(hyphen1); file.add(page_setup);file.add(print); file.add(hyphen2); file.add(exit);
mb.add(file); mb.add(edit); mb.add(format);
setBounds(10,10,400,300); setVisible(true); }
public void actionPerformed(ActionEvent ae) { dispose(); System.exit(0); } public static void main(String args[]) { menu m=new menu("our own menu"); } }
HCL
JDBC
//program to connect with database
import java.sql.*;
public class ConnectionTest { public static void main(String args[]) { Connection c;
try { // LOAD THE DRIVER HERE AT RUNTIME Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { // THIS EXCEPTION SHOULD BE CAUGHT DEFINITELY System.out.println("Driver not found"); }
try { System.out.println("Connecting to database"); c = DriverManager.getConnection("jdbc:odbc:sun"); System.out.println("Connected successfully"); c.close(); System.out.println("Connection closed"); } catch(SQLException e) { System.out.println("Error in connecting to database"); } }}
//demo program for using sql query
import java.sql.*;
public class PreparedStatementTest { public static void main(String args[]) {
HCL Connection c; PreparedStatement p; ResultSet r; String stuid, stuname; Date dob; double avg, cavg=0;
if(args.length < 1) { System.out.println("Enter avg range"); System.exit(0); } else { cavg = Double.parseDouble(args[0]); }
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.out.println("Driver not found"); }
try { c = DriverManager.getConnection("jdbc:odbc:Student", "", ""); p = c.prepareCall("SELECT STUID, STUNAME, DOB, AVG " + "FROM STUDENTS WHERE AVG < ?"); p.setDouble(1, cavg); r = p.executeQuery(); while(r.next()) { stuid = r.getString(1); stuname = r.getString(2); dob = r.getDate(3); avg = r.getDouble(4); System.out.println(stuid + ", " + stuname + ", " + dob + ", " + avg); } p.close(); c.close(); } catch(SQLException e) {
HCL System.out.println("SQL Error:\n" + e); } }}
//program1 that uses resultset
import java.sql.*;
public class ScrollResultSetTest { public static void main(String args[]) { Connection c; Statement s; ResultSet r; String stuid, stuname; Date dob; double avg;
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.out.println("Driver not found"); }
try { c = DriverManager.getConnection("jdbc:odbc:Student", "Admin", ""); s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); r = s.executeQuery("SELECT STUID, STUNAME, DOB, AVG " + "FROM STUDENTS"); System.out.println("\nFirst Record to Last Record:"); while(r.next()) { stuid = r.getString(1); stuname = r.getString(2); dob = r.getDate(3); avg = r.getDouble(4); System.out.println(stuid + ", " + stuname + ", " + dob + ", " + avg);
HCL }
System.out.println("\nLast Record to First Record:"); while(r.previous()) { stuid = r.getString(1); stuname = r.getString(2); dob = r.getDate(3); avg = r.getDouble(4); System.out.println(stuid + ", " + stuname + ", " + dob + ", " + avg); } s.close(); c.close(); } catch(SQLException e) { System.out.println("SQL Error:\n" + e); } }}
//program2 that uses resultset
import java.sql.*;
public class StatementTest { public static void main(String args[]) { Connection c; Statement s; ResultSet r; String stuid, stuname; Date dob; double avg;
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }
HCL catch(ClassNotFoundException e) { System.out.println("Driver not found"); }
try { c = DriverManager.getConnection("jdbc:odbc:Student", "Admin", ""); s = c.createStatement(); r = s.executeQuery("SELECT STUID, STUNAME, DOB, AVG " + "FROM STUDENTS"); while(r.next()) { stuid = r.getString(1); stuname = r.getString(2); dob = r.getDate(3); avg = r.getDouble(4); System.out.println(stuid + ", " + stuname + ", " + dob + ", " + avg); } s.close(); c.close(); } catch(SQLException e) { System.out.println("SQL Error:\n" + e); } }}
//program1 to do the transactions using sql query
import java.sql.*;
public class Transaction1 { public static void main(String args[]) { Connection c; Statement s;
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }
HCL catch(ClassNotFoundException e) { System.out.println("Driver not found"); }
try { c = DriverManager.getConnection("jdbc:odbc:Student", "Admin", "");
c.setAutoCommit(false); s = c.createStatement(); s.execute("DELETE FROM STUDENTS WHERE STUID = '1000'"); c.commit(); System.out.println("DELETE Committed");
c.close(); } catch(SQLException e) { System.out.println("SQL Error:\n" + e); } }}
//program2 to do the transactions using sql query
import java.sql.*;
public class Transaction2 { public static void main(String args[]) { Connection c; Statement s;
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.out.println("Driver not found"); }
try { c = DriverManager.getConnection("jdbc:odbc:Student", "Admin", "");
HCL c.setAutoCommit(false); s = c.createStatement(); s.execute("DELETE FROM STUDENTS WHERE STUID = '1000'"); c.rollback();
System.out.println("DELETE Rolled Back"); s.execute("DELETE FROM STUDENTS WHERE STUID = '1003'"); c.commit();
System.out.println("One Row Deleted"); c.close(); } catch(SQLException e) { System.out.println("SQL Error:\n" + e); } }}
//program1 for updating the database
import java.sql.*;
public class UpdatableResultSetTest { public static void main(String args[]) { Connection c; Statement s; ResultSet r; String stuid, stuname; Date dob; double avg;
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.out.println("Driver not found"); }
try { c = DriverManager.getConnection("jdbc:odbc:Student", "Admin", "");
s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
HCL r = s.executeQuery("SELECT STUID, STUNAME, DOB, AVG " + "FROM STUDENTS");
r.last(); r.updateString(1, "1000"); r.updateString(2, "SCOTT"); r.updateDate(3, new Date(1986, 4, 8)); r.updateDouble(4, 90.54); r.insertRow();
r.first(); do { stuid = r.getString(1); stuname = r.getString(2); dob = r.getDate(3); avg = r.getDouble(4); System.out.println(stuid + ", " + stuname + ", " + dob + ", " + avg); } while(r.next()); s.close(); c.close(); } catch(SQLException e) { System.out.println("SQL Error:\n" + e); } }}
//program2 for updating the database
import java.sql.*;
// run: java UpdatableResultSetTest2 1000
public class UpdatableResultSetTest2 { public static void main(String args[]) { Connection c;
HCL Statement s; ResultSet r; String stuid, sstuid=null;
if(args.length == 0) { System.out.println("Enter Student ID"); System.exit(0); } else sstuid = args[0];
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.out.println("Driver not found"); }
try { c = DriverManager.getConnection("jdbc:odbc:Student", "Admin", "");
s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
r = s.executeQuery("SELECT STUID, STUNAME, DOB, AVG " + "FROM STUDENTS");
r.first(); do { stuid = r.getString(1); if(stuid.equals(sstuid)) { r.deleteRow(); System.out.println("Row deleted"); }
} while(r.next()); s.close(); c.close(); } catch(SQLException e) { System.out.println("SQL Error:\n" + e);
HCL } }}
//program3 for updating the database
import java.sql.*;
public class UpdatableResultSetTest3 { public static void main(String args[]) { Connection c; Statement s; ResultSet r; String stuid=null, sstuid=null; String nname=null;
if(args.length < 2) { System.out.println("Enter Student ID, Name"); System.exit(0); } else { sstuid = args[0]; nname = args[1]; }
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.out.println("Driver not found"); }
try { c = DriverManager.getConnection("jdbc:odbc:Student", "Admin", "");
s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
HCL r = s.executeQuery("SELECT STUID, STUNAME, DOB, AVG " + "FROM STUDENTS");
r.first(); do { stuid = r.getString(1); if(stuid.equals(sstuid)) { r.updateString(2, nname); r.updateRow(); System.out.println("Row updated"); }
} while(r.next()); s.close(); c.close(); } catch(SQLException e) { System.out.println("SQL Error:\n" + e); } }}
top related