42
1 MCSL 025 Java lab manual solved Session 1: Data types, variables and operators Exercise 1: Write a program in Java to implement the formula (Area = Height × Width) to find the area of a rectangle. Where Height and Width are the rectangle’s height and width. //java program to find area of rectangle class AreaOfRectangle { public static void main(String args[]) { double h=12.0,w=5.0; double area=(h*w); System.out.println("The area of a rectangle is" +area); } } Exercise 2: Write a program in Java to find the result of following expression (Assume a = 10, b = 5) i) (a < < 2) + (b > > 2) ii) (a) | | (b > 0) iii) (a + b 100) / 10 iv) a & b //Java program to show arthemetic, logic & relational operations class expessionresult { public static void main(String args[]) { int a=10, b=5; System.out.println("the result of expression 1 is:"+((a < < 2) + (b > > 2))); System.out.println("the result of expression 2 is:"+((a) | | (b > 0))); System.out.println(("the result of expression 3 is:"+(a + b *100) / 10)); System.out.println("the result of expression 4 is:"+(a & b)); } } Exercise 3: Write a program in Java to explain the use of break and continue statements.

(Java MCSL 025 Solved)

Embed Size (px)

Citation preview

Page 1: (Java MCSL 025 Solved)

1

MCSL 025

Java lab manual solved

Session 1:Data types, variables and operators

Exercise 1: Write a program in Java to implement the formula (Area = Height × Width) to find the area of a rectangle. Where Height and Width are the rectangle’s height and width.

//java program to find area of rectangle

class AreaOfRectangle{public static void main(String args[]){double h=12.0,w=5.0;double area=(h*w);System.out.println("The area of a rectangle is" +area);}}

Exercise 2: Write a program in Java to find the result of following expression (Assume a = 10, b = 5)i) (a < < 2) + (b > > 2)ii) (a) | | (b > 0)iii) (a + b �100) / 10iv) a & b

//Java program to show arthemetic, logic & relational operations

class expessionresult {public static void main(String args[]) { int a=10, b=5;System.out.println("the result of expression 1 is:"+((a < < 2) + (b > > 2)));System.out.println("the result of expression 2 is:"+((a) | | (b > 0)));System.out.println(("the result of expression 3 is:"+(a + b *100) / 10));System.out.println("the result of expression 4 is:"+(a & b));}}Exercise 3: Write a program in Java to explain the use of break and continue statements.

Page 2: (Java MCSL 025 Solved)

2

//Java program to explain break and continue statements

class BreakContinue {public static void main(String args[]){int i=0;System.out.println("This is to illustrate break statement");while(i<100){if(i==10) break;System.out.println("i:"+i);i++;}System.out.println("Loop complete"); System.out.println("This is to illustrate continue statement");outer: for(i=0;i<10;i++){for(int j=0;j<10;j++){if (j>i){System.out.println();continue outer;} System.out.println(" "+(i*j));}}System.out.println();}}

Exercise 4: Write a program in Java to find the average of marks you obtained in your 10+2 class.

//Java program to find average marks

class Avg{public static void main (String args[]){int i, j, marks, total, sumofmarks=0, sumoftotal=0;System.out.println("enter marks of i's year:");for(i=0;i<8;i++){System.out.println("enter marks obainted for subject" +i)integer.parse(marks);sumofmarks=sumofmarks+marks;System.out.println("enter total marks for subject" +i)integer.parse(total);sumoftotal=sumoftotal+total;}

Page 3: (Java MCSL 025 Solved)

3

System.out.println("enter marks of 2nd year:");for(j=0;j<8;j++){System.out.println("enter marks obainted for subject" +j)integer.parse(marks);sumofmarks=sumofmarks+marks;System.out.println("enter total marks for subject" +j)integer.parse(total);sumoftotal=sumoftotal+total;}int avg=sumofmarks/sumoftotal * 100;System.out.println("The average of four subjects:"+avg);}

Session 2: Statements and array

Exercise1: Write a program in Java to find A×B where A is a matrix of 3×3 and B is a matrix of 3×4. Take the values in matrixes A and B from the user.

//Java program to find multiplication of matrices

import java.io.*;public class Matrixmultiplication{public static int readInt() throws IOException{BufferedReader b =new BufferedReader(new InputStreamReader(System.in));int i=Integer.parseInt(b.readLine());return i;}public static void main(String args[]) throws IOException{int m1[][]=new int[2][3];int m2[][]=new int[3][2]; int m3[][]=new int[2][2];System.out.println("Enter the 6 numbers");for(int i=0;i<2;i++)for(int j=0;j<3;j++)m1[i][j]=readInt();for(int i=0;i<2;i++){for(int j=0;j<3;j++){System.out.print("\t "+m1[i][j]);}System.out.println();}

Page 4: (Java MCSL 025 Solved)

4

System.out.println("Enter the 6 numbers");for(int i=0;i<3;i++)for(int j=0;j<2;j++)m2[i][j]=readInt();for(int i=0;i<3;i++){for(int j=0;j<2;j++){System.out.print("\t "+m2[i][j]);}System.out.println();}for(int i=0;i<2;i++){for(int j=0;j<2;j++){m3[i][j]=0;for(int k=0;k<3;k++) m3[i][j]=m3[i][j]+m1[i][k]*m2[k][j];}}System.out.println("The product of two matrices is:");for(int i=0;i<2;i++){for(int j=0;j<2;j++){ System.out.print("\t "+m3[i][j]);}System.out.println();}}}

Exercise 2: Write a program in Java to compute the sum of the digits of a given integer. Remember, your integer should not be less than the five digits. (e.g., if input is 23451 then sum of the digits of 23451will be 15)

//Java program to find sum of digits of integer

iimport java.io.*;class Sumdigits{public static void main(String args[])throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String str;int num,rem;int sum=0;System.out.println("Enter a 5 digit number");str=br.readLine();

Page 5: (Java MCSL 025 Solved)

5

num=Integer.parseInt(str);while(num>0){rem=num%10;sum=sum+rem;num=num/10;}System.out.println("The sum of the digits"+sum);}}Session 3: Class and Objects

Exercise 1: Write a program in Java with class Rectangle with the data fields width, length, area and colour. The length, width and area are of double type and colour is of string type .The methods are set_ length () , set_width (), set_ colour(), and find_ area (). Create two object of Rectangle and compare their area and colour. If area andcolor both are the same for the objects then display “Matching Rectangles”, otherwise display “Non matching Rectangle”.

//Java program to create objects of a class

class Rect{double width,length,area;String colour;void set_length(double x){length=x;}void set_width(double y){width=y;}String set_colour(String z){colour=z;return colour;}double find_area(){area=length*width;System.out.println("Area of rectangle="+area);return area;}}

class Rectangle

Page 6: (Java MCSL 025 Solved)

6

{public static void main(String args[]){double area1, area2;String st1,st2;Rect r1=new Rect();Rect r2=new Rect();r1.set_length(5.0);r1.set_width(6.0); st1=r1.set_colour("blue");area1=r1.find_area();r2.set_length(5.0);r2.set_width(6.0); st2=r2.set_colour("green");area2=r2.find_area();if ((area1==area2) && st1.equals(st2)){System.out.println("Matching rectangles");}else{System.out.println("Non matching rectangles");}}Exercise 2: Create a class Account with two overloaded constructors. The first constructor is used for initializing, the name of account holder, the account number and the initial amount in the account. The second constructor is used for initializing the name of the account holder, the account number, the addresses, the type of account and the current balance. The Account class is having methods Deposit (), Withdraw (), and Get_Balance(). Make the necessary assumption for data members and return types of the methods. Create objects of Account class and use themExercise 3: Write a program in Java to create a stack class of variable size with push() and pop () methods. Create two objects of stack with 10 data items in both. Compare the top elements of both stack and print the comparison result.>

Session 4: Inheritance and polymorphism

Exercise 1: Write a Java program to show that private member of a super class cannot be accessed from derived classes.

/Java program to show private member of super class

//create a super classclass A{

Page 7: (Java MCSL 025 Solved)

7

int i;private int j;void setij(int x,int y){i=x;j=y;}}

//sub classclass B extends A{int total;void sum(){total=i+j;}}Exercise 2: Write a program in Java to create a Player class. Inherit the classes Cricket _Player, Football _Player and Hockey_ Player from Player class.

//Java program to show inheritance

//class foot ball paler and class cricket player inerited from player class

class Player{String name;Player(String nm){name=nm;}}class Cricket_player extends Player{Cricket_player(String nm){super(nm);}void play(){ System.out.println("play cricket:"+name);}}class Football_player extends Player{Football_player(String nm){

Page 8: (Java MCSL 025 Solved)

8

super(nm);}void play(){System.out.println("play Football:"+name);}}class Hockey_player extends Player{Hockey_player(String nm){super(nm);}void play(){System.out.println("play hockey:"+name);}} class Player1{public static void main(String args[]){Cricket_player c=new Cricket_player("sachin tendulkar");Football_player f=new Football_player("peley");Hockey_player h=new Hockey_player("Helen mary");c.play();f.play();h.play();}}Exercise 3: Write a class Worker and derive classes DailyWorker and SalariedWorker from it. Every worker has a name and a salary rate. Write method ComPay (int hours) to compute the week pay of every worker. A Daily Worker is paid on the basis of the number of days s/he works. The Salaried Worker gets paid the wage for 40 hours a week no matter what the actual hours are. Test this program to calculate the pay of workers. You are expected to use the concept of polymorphism to write this program.

//Java program to show polymorphism

abstract class worker{String name;double sal_rate;worker(String nm,double sr);{name=nm;

Page 9: (Java MCSL 025 Solved)

9

sal_rate=sr;}abstract void compay()}

class Daily_worker extends worker{int days_worked;Daily_worker(String nm,double sr,int dw){super(nm,sr);days_worked=dw;}void compay(){double pay=(days_worked*sal_rate)System.out.println("\t Name:"+name+ "\tsalary per day"+sal_rate+"\tpay per week"+pay);}}

class Salaried_worker extends worker{Daily_worker(String nm,double sr){super(nm,sr);}void compay(){double pay=(40*sal_rate)System.out.println("\t Name:"+name+ "\tsalary per hour"+sal_rate+"\tpay per week"+pay);}}Exercise 4: Consider the trunk calls of a telephone exchange. A trunk call can be ordinary, urgent or lightning. The charges depend on the duration and the type of the call. Writ a program using the concept of polymorphism in Java to calculate the charges.

//Java program to show implementation of interface

import java.io.*; interface student { void disp_grade(); void disp_attendance();

Page 10: (Java MCSL 025 Solved)

10

}class pg_stud implements student {String name,grade; int reg,m1,m2,m3,att;void read()throws Exception{DataInputStream in= new DataInputStream(System.in);System.out.println("enter the register no : ");reg=Integer.parseInt(in.readLine());System.out.println("enter the name : ");name=in.readLine();System.out.println("enter attendance : ");att=Integer.parseInt(in.readLine());System.out.println("enter mark1 : ");m1=Integer.parseInt(in.readLine());System.out.println("enter mark2 : ");m2=Integer.parseInt(in.readLine());System.out.println("enter mark3 : ");m3=Integer.parseInt(in.readLine());}public void disp_grade() {int tt=m1+m2+m3; if(tt>=250) grade="A";else if(tt>=200) grade="B";else if(tt>=150) grade="C";else if(tt>=100) grade="D";else grade="E";System.out.println("Grade:"+grade); }public void disp_attendance() {System.out.println("Attendance:"+att); }void disp(){System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println(" MARK LIST OF PG STUDENTS");System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("Register No :"+reg);System.out.println("Name:"+name); System.out.println("Mark1 :"+m1); System.out.println("Mark2:"+m2); System.out.println("Mark3 :"+m3);disp_grade();disp_attendance();} }class ug_stud implements student {String name,grade;

Page 11: (Java MCSL 025 Solved)

11

int reg,m1,m2,m3,att;void read()throws Exception{DataInputStream in= new DataInputStream(System.in);System.out.println("enter the register no : ");reg=Integer.parseInt(in.readLine());System.out.println("enter the name : ");name=in.readLine();System.out.println("enter attendance : ");att=Integer.parseInt(in.readLine());System.out.println("enter mark1 : ");m1=Integer.parseInt(in.readLine());System.out.println("enter mark2 : ");m2=Integer.parseInt(in.readLine());System.out.println("enter mark3 : ");m3=Integer.parseInt(in.readLine());}public void disp_grade() {int tt=m1+m2+m3; if(tt>=250) grade="A";else if(tt>=200) grade="B";else if(tt>=150) grade="C";else if(tt>=100) grade="D";else grade="E";System.out.println("Grade:"+grade); }public void disp_attendance() {System.out.println("Attendance :"+att); }void disp(){System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println(" MARK LIST OF UG STUDENTS");System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("Register No :"+reg);System.out.println("Name:"+name); System.out.println("Mark1 :"+m1); System.out.println("Mark2 :"+m2); System.out.println("Mark3 :"+m3);disp_grade();disp_attendance();} }class studentInterface{public static void main(String args[])throws Exception {pg_stud pg=new pg_stud();pg.read();

Page 12: (Java MCSL 025 Solved)

12

pg.disp();ug_stud ug=new ug_stud();ug.read();ug.disp();}}

Session 5: Package and Interface

Exercise 1: Write a program to make a package Balance in which has Account class with Display_Balance method in it. Import Balance package in another program to access Display_Balance method of Account class.

//Java program to import package to access method in it

class AccessPackMethod{ public static void main(String ar[]){try{balance.account a=new balance.account();a.read();a.disp();}catch(Exception e){ System.out.println(e); }}}package balance;import java.io.*;public class account{ long acc,bal;String name;public void read()throws Exception{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter the name :");name=in.readLine();System.out.println("Enter the account number:");acc=Long.parseLong(in.readLine());System.out.println("Enter the account balance:");bal=Long.parseLong(in.readLine());}public void disp()

Page 13: (Java MCSL 025 Solved)

13

{System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("--- Account Details ---");System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("Name :"+name);System.out.println("Account number :"+acc);System.out.println("Balance :"+bal);}}

Exercise 2: Write a program in Java to show the usefulness of Interfaces as a place to keep constant value of the program.

//Java program to show usefulness of interfaces

interface area { static final float pi=3.142f; float compute(float x,float y); }

class rectangle implements area{ public float compute(float x,float y){return(x*y);} }

class circle implements area {public float compute(float x,float y) {return(pi*x*x);} }

class Iterfaceusefulness{public static void main(String args[]){rectangle rect=new rectangle(); circle cr=new circle();area ar;ar=rect;System.out.println("Area of the rectangle= "+ar.compute(10,20));

Page 14: (Java MCSL 025 Solved)

14

ar=cr;System.out.println("Area of the circle= "+ar.compute(10,0));}}

Exercise 3: Create an Interface having two methods division and modules. Create a class, which overrides these methods.

//Java program to show implementation of interface

import java.io.*; interface student { void disp_grade(); void disp_attendance(); }class pg_stud implements student {String name,grade; int reg,m1,m2,m3,att;void read()throws Exception{DataInputStream in= new DataInputStream(System.in);System.out.println("enter the register no : ");reg=Integer.parseInt(in.readLine());System.out.println("enter the name : ");name=in.readLine();System.out.println("enter attendance : ");att=Integer.parseInt(in.readLine());System.out.println("enter mark1 : ");m1=Integer.parseInt(in.readLine());System.out.println("enter mark2 : ");m2=Integer.parseInt(in.readLine());System.out.println("enter mark3 : ");m3=Integer.parseInt(in.readLine());}public void disp_grade() {int tt=m1+m2+m3; if(tt>=250) grade="A";else if(tt>=200) grade="B";else if(tt>=150) grade="C";else if(tt>=100) grade="D";else grade="E";System.out.println("Grade:"+grade); }public void disp_attendance() {System.out.println("Attendance:"+att);

Page 15: (Java MCSL 025 Solved)

15

}void disp(){System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println(" MARK LIST OF PG STUDENTS");System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("Register No :"+reg);System.out.println("Name:"+name); System.out.println("Mark1 :"+m1); System.out.println("Mark2:"+m2); System.out.println("Mark3 :"+m3);disp_grade();disp_attendance();} }class ug_stud implements student {String name,grade; int reg,m1,m2,m3,att;void read()throws Exception{DataInputStream in= new DataInputStream(System.in);System.out.println("enter the register no : ");reg=Integer.parseInt(in.readLine());System.out.println("enter the name : ");name=in.readLine();System.out.println("enter attendance : ");att=Integer.parseInt(in.readLine());System.out.println("enter mark1 : ");m1=Integer.parseInt(in.readLine());System.out.println("enter mark2 : ");m2=Integer.parseInt(in.readLine());System.out.println("enter mark3 : ");m3=Integer.parseInt(in.readLine());}public void disp_grade() {int tt=m1+m2+m3; if(tt>=250) grade="A";else if(tt>=200) grade="B";else if(tt>=150) grade="C";else if(tt>=100) grade="D";else grade="E";System.out.println("Grade:"+grade); }public void disp_attendance() {System.out.println("Attendance :"+att); }void disp(){System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

Page 16: (Java MCSL 025 Solved)

16

System.out.println(" MARK LIST OF UG STUDENTS");System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("Register No :"+reg);System.out.println("Name:"+name); System.out.println("Mark1 :"+m1); System.out.println("Mark2 :"+m2); System.out.println("Mark3 :"+m3);disp_grade();disp_attendance();} }class studentInterface{public static void main(String args[])throws Exception {pg_stud pg=new pg_stud();pg.read();pg.disp();ug_stud ug=new ug_stud();ug.read();ug.disp();}}

Exercise 4: Write a program in Java which implements interface Student which has two methods Display_Grade and Atrendance for PG_Students and UG_Students (PG_Students and UG_Students are two different classes for Post Graduate and Under Graduate students respectively).

//Java program to show implementation of interface

import java.io.*; interface student { void disp_grade(); void disp_attendance(); }class pg_stud implements student {String name,grade; int reg,m1,m2,m3,att;void read()throws Exception{DataInputStream in= new DataInputStream(System.in);System.out.println("enter the register no : ");reg=Integer.parseInt(in.readLine());System.out.println("enter the name : ");name=in.readLine();System.out.println("enter attendance : ");

Page 17: (Java MCSL 025 Solved)

17

att=Integer.parseInt(in.readLine());System.out.println("enter mark1 : ");m1=Integer.parseInt(in.readLine());System.out.println("enter mark2 : ");m2=Integer.parseInt(in.readLine());System.out.println("enter mark3 : ");m3=Integer.parseInt(in.readLine());}public void disp_grade() {int tt=m1+m2+m3; if(tt>=250) grade="A";else if(tt>=200) grade="B";else if(tt>=150) grade="C";else if(tt>=100) grade="D";else grade="E";System.out.println("Grade:"+grade); }public void disp_attendance() {System.out.println("Attendance:"+att); }void disp(){System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println(" MARK LIST OF PG STUDENTS");System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("Register No :"+reg);System.out.println("Name:"+name); System.out.println("Mark1 :"+m1); System.out.println("Mark2:"+m2); System.out.println("Mark3 :"+m3);disp_grade();disp_attendance();} }class ug_stud implements student {String name,grade; int reg,m1,m2,m3,att;void read()throws Exception{DataInputStream in= new DataInputStream(System.in);System.out.println("enter the register no : ");reg=Integer.parseInt(in.readLine());System.out.println("enter the name : ");name=in.readLine();System.out.println("enter attendance : ");att=Integer.parseInt(in.readLine());System.out.println("enter mark1 : ");m1=Integer.parseInt(in.readLine());System.out.println("enter mark2 : ");

Page 18: (Java MCSL 025 Solved)

18

m2=Integer.parseInt(in.readLine());System.out.println("enter mark3 : ");m3=Integer.parseInt(in.readLine());}public void disp_grade() {int tt=m1+m2+m3; if(tt>=250) grade="A";else if(tt>=200) grade="B";else if(tt>=150) grade="C";else if(tt>=100) grade="D";else grade="E";System.out.println("Grade:"+grade); }public void disp_attendance() {System.out.println("Attendance :"+att); }void disp(){System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println(" MARK LIST OF UG STUDENTS");System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("Register No :"+reg);System.out.println("Name:"+name); System.out.println("Mark1 :"+m1); System.out.println("Mark2 :"+m2); System.out.println("Mark3 :"+m3);disp_grade();disp_attendance();} }class studentInterface{public static void main(String args[])throws Exception {pg_stud pg=new pg_stud();pg.read();pg.disp();ug_stud ug=new ug_stud();ug.read();ug.disp();}}

Session 6: Exception Handling

Exercise 1: Write a program in Java to display the names and roll numbers of students. Initialize respective array variables for

Page 19: (Java MCSL 025 Solved)

19

10 students. Handle ArrayIndexOutOfBoundsExeption, so that any such problem doesn’t cause illegal termination of program.

//Java program to show ArrayIndexOutOfBound excepion

class student{String name,grade;int reg,m1,m2,m3;void read()throws Exception{DataInputStream in= new DataInputStream(System.in);System.out.println("enter the register no : ");reg=Integer.parseInt(in.readLine());System.out.println("enter the name : ");name=in.readLine();System.out.println("enter mark1 : ");m1=Integer.parseInt(in.readLine());System.out.println("enter mark2 : ");m2=Integer.parseInt(in.readLine());System.out.println("enter mark3: ");m3=Integer.parseInt(in.readLine());}public void disp_grade(){int tt=m1+m2+m3;if(tt>=250) grade="A";else if(tt>=200) grade="B";else if(tt>=150) grade="C";else if(tt>=100) grade="D";else grade="E";System.out.println("Grade :"+grade);}void disp(){System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println(" MARK LIST OF STUDENTS ");System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("Register No :"+reg);System.out.println("Name :"+name);System.out.println("Mark1 :"+m1);System.out.println("Mark2 :"+m2);System.out.println("Mark3 :"+m3);disp_grade();}}class AIOBException{public static void main(String ar[]){

Page 20: (Java MCSL 025 Solved)

20

int no=0;student s=new student();try{DataInputStream in= new DataInputStream(System.in);System.out.println("enter the number of students : ");no=Integer.parseInt(in.readLine());for(int i=0;i<no;i++);s.read();}catch(ArrayIndexOutOfBoundsException e){System.out.println("the maximum students should be ten\n");no=10;}catch(Exception e){ System.out.println(e); }for(int i=0;i<no;i++);s.disp();}}

Exercise 2: Write a Java program to enable the user to handle any chance of divide by zero exception.

//Java program to show DivideByZero excepion

public class DivideByzero{.public static void main(String args[]){int b=100,res=0;int a[]={0,1,2,5,0,25,0,50,0};for (int i=0;i<9;i++){try{res=res+(b/a[i]);System.out.println(" "+res);} catch (ArithmeticException e){a[i]=1;}}}}

Exercise 3: Create an exception class, which throws an

Page 21: (Java MCSL 025 Solved)

21

exception if operand is non-numeric in calculating modules. (Use command line arguments).

//Java program to show NumberFormat excepion

public class EXceptionnonnumeric{public static void main(String args[]){int sum=0;int invalid=0;for(int i=0;i<args.length;i++){try{sum+=Integer.parseInt(args[i]); }catch(NumberFormatException e){invalid++;}}System.out.println("Total number of arguments:"+args.length);System.out.println("Invalid numbers:"+invalid); System.out.println("Sum:"+sum);}

Exercise 4: On a single track two vehicles are running. As vehicles are going in same direction there is no problem. If the vehicles are running in different direction there is a chance of collision. To avoid collisions write a Java program using exception handling. You are free to make necessary assumptions.

//Java program to avoid vehicle collision

import java.io.*;class collision extends Exception{ collision(String s){ super(s); } }

class TwoVehicles{

Page 22: (Java MCSL 025 Solved)

22

public static void main(String ar[]) {String t1=null,t2=null; try {DataInputStream in= new DataInputStream(System.in); System.out.println("enter the direction of vehicle1:(left/right):");t1=in.readLine();System.out.println("enter the direction of vehicle2:(left/right):");t2=in.readLine();if(!t1.equals(t2))throw new collision("truck2 has to go on "+ t1 +" direction");}catch(collision e){System.out.println(e); t2=t1; System.out.println("the collision has been avoided by redirection truck2"); }catch(Exception e){ System.out.println(e); } System.out.println("direction of truck1 :"+t1); System.out.println("direction of truck2 :"+t2); } }

Session 7: Multithreading

Exercise 1: Write a Java program to create five threads with different priorities. Send two threads of the highest priority to sleep state. Check the aliveness of the threads and mark which thread is long lasting.

//Java program to show multithreading with priority

public class FiveThreads implements Runnable {public static void main(String args[]) throws InterruptedException{Thread T1=new Thread();Thread T2=new Thread();Thread T3=new Thread();Thread T4=new Thread();Thread T5=new Thread();T1.setPriority(7);T2.setPriority(2);T3.setPriority(10);

Page 23: (Java MCSL 025 Solved)

23

T4.setPriority(5);T5.setPriority(8);T1.sleep(1500);if (T1.isAlive())System.out.println("Thread 1 is alive");elseSystem.out.println("Thread 1 is not alive");T2.start(); if (T2.isAlive())System.out.println("Thread 2 is alive");elseSystem.out.println("Thread 2 is not alive");T3.sleep(1000);if (T3.isAlive())System.out.println("Thread 3 is alive");elseSystem.out.println("Thread 3 is not alive");T4.start(); if (T4.isAlive())System.out.println("Thread 4 is alive");elseSystem.out.println("Thread 4 is not alive");T5.start();if (T5.isAlive())System.out.println("Thread 5 is alive");elseSystem.out.println("Thread 5 is not alive");}}

Exercise 2: Write a program to launch 10 threads. Each thread increments a counter variable. Run the program with synchronization.

//Java program to launch multiple threads and count them

class ThreadSyncronisation{ public static void main(String arg[])throws Exception {data d1=new data(); data d2=new data();data d3=new data();data d4=new data();data d5=new data();data d6=new data();data d7=new data();data d8=new data();data d9=new data();data d10=new data();System.out.println(d10.count);}

Page 24: (Java MCSL 025 Solved)

24

} class item { static int count=0; } class data extends item implements Runnable {item d=this; Thread t; data() {t=new Thread(this); t.start(); } public void run() { d=syn.increment(d); } }class syn { synchronized static item increment(item i) {i.count++; return(i); } }

Exercise 3: Write a program for generating 2 threads, one for printing even numbers and the other for printing odd numbers.

//Java program to generate two threads one for counting even numbers & other for counting odd numbers

class even extends Thread {Thread t=null;even(){t=new Thread(this); start(); } public void run() {try{for(int i=2;i<50;i+=2) System.out.print(i+" ");Thread.sleep(100);}catch(Exception e) {System.out.println("thread interepted");} } }

Page 25: (Java MCSL 025 Solved)

25

class odd extends Thread { Thread t=null; odd() {t=new Thread(this); start(); } public void run() {try{for(int i=1;i<50;i+=2) System.out.print(i+" ");Thread.sleep(100);}catch(Exception e) {System.out.println("thread interepted");} } }

class ThreadEvenOdd{public static void main(String arg[]) {even e=new even();odd o=new odd();} }

Exercise 4: Write a Java program using thread synchronization in multithreading (You can take some objects visible on screen for real time effect).

//Java program to show thread synchronization

import java.io.*;class read{static String get(String x){String n=null;try{DataInputStream in = new DataInputStream(System.in);System.out.println(x);n=in.readLine();System.out.flush();}catch(Exception e){ System.out.println("i/o stream error"); }return(n);

Page 26: (Java MCSL 025 Solved)

26

}}class s07_04{public static void main(String arg[]){try{stud s1=new stud();stud s2=new stud();}catch(Exception e){System.out.println("i/o stream error");}}}class st{String name;int code,m1,m2,m3,tt;float avg;}class stud extends st implements Runnable{st data=this;Thread t;stud(){t=new Thread(this);t.start();}public void run(){try{data=sy.r(data);t.sleep(100);data=sy.sum(data);t.sleep(100);sy.p(data);t.sleep(100);}catch(Exception e){ System.out.println("interrupted"); }}}class sy{synchronized static st r(st e){System.out.println("sychronized fountion read() ");e.name=read.get("enter the name:");e.code=Integer.parseInt(read.get("enter the regno:"));e.m1=Integer.parseInt(read.get("enter mark1:"));

Page 27: (Java MCSL 025 Solved)

27

e.m2=Integer.parseInt(read.get("enter mark2:"));e.m3=Integer.parseInt(read.get("enter mark3:"));return(e);}synchronized static void p(st x){System.out.println("no :"+x.code);System.out.println("name :"+x.name);System.out.println("mark1 :"+x.m1);System.out.println("mark2 :"+x.m2);System.out.println("mark3 :"+x.m3);System.out.println("avg :"+x.avg);System.out.println("total :"+x.tt);}synchronized static st sum(st z){System.out.println("synchronized sum() ");z.tt=z.m1+z.m2+z.m3;z.avg=(z.tt)/3;return(z);}}

Session 8: Reading, Writing and String handling in Java

Exercise 1: Writ a program in Java to create a String object. Initialize this object with your name. Find the length of your name using the appropriate String method. Find whether the character ‘a’ is in your name or not; if yes find the number of times ‘a’ appears in your name. Print locations of occurrences of ‘a’ .Try the same for different String objects.

// Java Applet program which reads your name and address in different text fields and when a button named find is pressed the sum of the length of characters in name and address is displayed in another text field. Use appropriate colors, layout to make your applet look good.

import java.applet.*;import java.awt.*;import java.awt.event.*;public class s09_01 extends Applet implements ActionListener { public void init() {label1 = new Label();label2 = new Label();label3 = new Label();t1 = new TextField();t2 = new TextField();t3 = new TextField();b1 = new Button();setLayout(null);setBackground(new Color(0, 153, 102));label1.setAlignment(Label.RIGHT);label1.setText("Name");add(label1);

Page 28: (Java MCSL 025 Solved)

28

label1.setBounds(140, 60, 50, 20);label2.setAlignment(Label.RIGHT);label2.setText("Address");add(label2);label2.setBounds(140, 90, 50, 20);label3.setAlignment(Label.RIGHT);label3.setText("Total length");add(label3);label3.setBounds(130, 120, 60, 20);add(t1); t1.setBounds(200, 60, 100, 20); add(t2); t2.setBounds(200, 90, 100, 20); add(t3); t3.setBounds(200, 120, 100, 20); b1.setBackground(new Color(255, 204, 153));b1.setLabel("Total");b1.addActionListener(this);add(b1);b1.setBounds(150, 180, 80, 24);} public void actionPerformed(ActionEvent ae) { int a=t1.getText().length();a+=t2.getText().length();t3.setText(Integer.toString(a));}Label label1;Label label2; Label label3; TextField t1; TextField t2; TextField t3; Button b1; }

<html> <body><applet code="s09_01.class" width=400 height=400></applet></body></html>

Exercise 2: Write a program in Java for String handling which performs the following:i) Checks the capacity of StringBuffer objects.ii) Reverses the contents of a string given on console and converts the resultant string in upper case.iii) Reads a string from console and appends it to the resultant string of ii.

//Java program read string from console and display uppercase in consoleclass ReadWriteConsole

Page 29: (Java MCSL 025 Solved)

29

{public static void main(String a[]) throws IOException{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter file Statement:");String s1=in.readLine();System.out.println(s1.toUpperCase());}}Exercise 3: Write a program for searching strings for the first occurrence of a character or substring and for the last occurrence of a character or substring.

//Java program find first and last occurance of character substring in string

import java.io.*;class FirstLastOccuranceChar{public static void main(String[]args) throws Exception{int len1,len2,last=0;DataInputStream in=new DataInputStream(System.in);System.out.println("Enter the string:");String s1=in.readLine();System.out.println("Enter searching string:");String s2=in.readLine();len1=s1.length();len2=s2.length();for(int i=0;i<=(len1-len2);i++){if(s1.substring(i,len2+i).equals(s2)){if(last==0)System.out.println("first occurance is at position:"+(i+1));last=i+1;}}if(last!=0)System.out.println("last occurance is at position :"+last);elseSystem.out.println("the string is not found");}}Exercise 4: Write a program in Java to read a statement from console, convert it into upper case and again print on console.

//Java program read string from console and display uppercase in consoleclass ReadWriteConsole{public static void main(String a[]) throws IOException

Page 30: (Java MCSL 025 Solved)

30

{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter file Statement:");String s1=in.readLine();System.out.println(s1.toUpperCase());}}

Exercise 5: Write a program in Java, which takes the name of a file from user, read the contents of the file and display it on the console.

//Java program to find file name from console and display contents on console

class ReadWriteConsole{public static void main(String a[]) throws IOException{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter file Statement:");String s1=in.readLine();FileInputStream fis=null; try{fis=new FileInputStream(s1);byte ch;while((ch=(byte)fis.read())!=-1){System.out.print((char)ch); }}catch(IOException e){ System.out.println("interrupted");}finally{try {fis.close();}catch(IOException e){System.out.println("error in closing");}} }}}

Exercise 6: Write a Java program to copy a file into another file.

Page 31: (Java MCSL 025 Solved)

31

//Java program to copy a fle to another file

class FileCopy{public static void main(String a[]) throws IOException{int d=0;FileInputStream fi=null;FileOutputStream fo=null;DataInputStream in=new DataInputStream(System.in);System.out.println("Enter file name:");String s1=in.readLine();System.out.println("Enter new file name:");String s2=in.readLine();try{fi=new FileInputStream(s1);fo=new FileOutputStream(s2);System.out.println("Copying file");while((d=fi.read())!=-1)fo.write((byte)d); System.out.println("File copyied"); } catch(IOException e){System.out.println(e);} }}

Session 9: Applets and its applications

Exercise 1: Write a Java Applet program which reads your name and address in different text fields and when a button namedfind is pressed the sum of the length of characters in name and address is displayed in another text field. Use appropriate colors, layout to make your applet look good.

// Java Applet program which reads your name and address in different text fields and when a button named find is pressed the sum of the length of characters in name and address is displayed in another text field. Use appropriate colors, layout to make your applet look good.

import java.applet.*;import java.awt.*;import java.awt.event.*;public class s09_01 extends Applet implements ActionListener { public void init() {label1 = new Label();label2 = new Label();label3 = new Label();

Page 32: (Java MCSL 025 Solved)

32

t1 = new TextField();t2 = new TextField();t3 = new TextField();b1 = new Button();setLayout(null);setBackground(new Color(0, 153, 102));label1.setAlignment(Label.RIGHT);label1.setText("Name");add(label1);label1.setBounds(140, 60, 50, 20);label2.setAlignment(Label.RIGHT);label2.setText("Address");add(label2);label2.setBounds(140, 90, 50, 20);label3.setAlignment(Label.RIGHT);label3.setText("Total length");add(label3);label3.setBounds(130, 120, 60, 20);add(t1); t1.setBounds(200, 60, 100, 20); add(t2); t2.setBounds(200, 90, 100, 20); add(t3); t3.setBounds(200, 120, 100, 20); b1.setBackground(new Color(255, 204, 153));b1.setLabel("Total");b1.addActionListener(this);add(b1);b1.setBounds(150, 180, 80, 24);} public void actionPerformed(ActionEvent ae) { int a=t1.getText().length();a+=t2.getText().length();t3.setText(Integer.toString(a));}Label label1;Label label2; Label label3; TextField t1; TextField t2; TextField t3; Button b1; }

<html> <body><applet code="s09_01.class" width=400 height=400></applet></body></html>

Exercise 2: Create an applet which displays a rectangle/string with specified colour & coordinate passed as parameter from the HTML file.

Page 33: (Java MCSL 025 Solved)

33

// Java Applet to display rectangle or string in specified color

import java.applet.*;import java.awt.*;import java.awt.event.*;public class Applet2 extends Applet implements ActionListener{public void init() {setLayout(null); setBackground(new Color(0,10,100)); } public void paint(Graphics p) {String t=null; int x,y,w,h,r,g,b;t=getParameter("xx");x=Integer.parseInt(t);t=getParameter("yy");y=Integer.parseInt(t);t=getParameter("ww");w=Integer.parseInt(t);t=getParameter("hh");h=Integer.parseInt(t);t=getParameter("rr");r=Integer.parseInt(t);t=getParameter("gg");g=Integer.parseInt(t);t=getParameter("bb");b=Integer.parseInt(t);p.setColor(new Color(r,g,b));p.fillRect(x,y,w,h);}}<html> <body><applet code="s09_02.class" width=400 height=400><param name="xx" value="25"><param name="yy" value="25"><param name="ww" value="150"><param name="hh" value="150"><param name="rr" value="0"><param name="gg" value="150"><param name="bb" value="100"></applet></body></html>

Exercise 3: Create an applet which will display the calendar of a given date.

//Java applet to read text and display calander of a given date

Page 34: (Java MCSL 025 Solved)

34

import java.util.*;import java.awt.*;import java.applet.*;public class DisplayCalander extends Applet{GregorianCalendar cal=new GregorianCalendar();String s,s1,s2,s3,s4;int a=0,b=0,c=0,d=0;public void start(){s=getParameter("fg");s1=getParameter("as");s2=getParameter("as1");s3=getParameter("as2");s4=getParameter("as3");a=Integer.parseInt(s1);b=Integer.parseInt(s2);c=Integer.parseInt(s3);d=Integer.parseInt(s4);}public void init(){}public void paint(Graphics g){if(s.equals("red"))g.setColor(Color.red);g.drawRect(a,b,c,d);g.drawString("Color = "+"",25,25);g.drawString("Calendar is"+cal.DATE+"/"+cal.MONTH+"/"+cal.YEAR,34,36);}}

<html> <body><applet code="DisplayCalander.class" width=400 height=400></applet></body></html>

Exercise 4: Write a program to store student’s detail using Card Layout.

Exercise 5: Write a Java Applet program, which provides a text area with horizontal and vertical scrollbars. Type some lines of text in the text area and use scrollbars for movements in the text area. Read a word in a text field and find whether the word is in the content of the text area or not.

Page 35: (Java MCSL 025 Solved)

35

Session 10: Networking and other advanced feature and JAVA

Exercise 1: Write a Java program to find the numeric address of the following web sitesi. www.ignou.ac.inii. www.indiatimes.comiii. www.rediff.comiv. www.apple.comIn addition to this, find the Internet Address of your local host.

//Java program to find numeric network address for sites

import java.net.*;class findnetworkaddress{public static void main(String ar[])throws Exception {InetAddress a=InetAddress.getLocalHost(); System.out.println("The Local Host IP:"+a);a=InetAddress.getByName("www.ignou.ac.in");System.out.println("The IP of www.ignou.ac.in :"+a);a=InetAddress.getByName("www.indiatimes.com");System.out.println("The IP of www.indiatimes.com :"+a);a=InetAddress.getByName("www.apple.com");System.out.println("The IP of www.apple.com :"+a);InetAddress s[]=InetAddress.getAllByName("www.rediff.com");for(int i=0;i<s.length;i++)System.out.println("The IP of www.rediff.com :"+s[i]);}}

Exercise 2: Create an applet which takes name and age as parameters and display the message “<name> is <age> year old.”. Print the URL of the class file.

//Java program to accept name age and display message and url of class

import java.applet.*;import java.awt.*;import java.awt.event.*;public class NameAgeApplet extends Applet{public void init()

Page 36: (Java MCSL 025 Solved)

36

{ Font f=new Font("adobe-courier",Font.PLAIN,18);setFont(f);setLayout(null);setForeground(Color.green);setBackground(new Color(200,0,200));}public void paint(Graphics g) {String n,a,msg; n=getParameter("name");a=getParameter("age");msg=n+" is "+a+" year old. ";g.drawString(msg,25,25);}}Exercise 3: Write a program to test Socket functionality for appropriate hostname and port number.

//Java program to test socket functionality for host name port number

public class SocketfunctionalityTest{public static final short TIME_PORT = 13;public static void main(String[] args) throws IOException {String hostName = args.length == 0 ? "localhost" : args[0];System.out.println(); try {// --------------------------------------// Open a socket // --------------------------------------Socket serverSocket = new Socket(hostName, TIME_PORT);System.out.println("-------------------------");System.out.println("Server Socket Information");System.out.println("-------------------------");System.out.println("serverSocket : " + serverSocket);System.out.println("Keep Alive : " + serverSocket.getKeepAlive());System.out.println("Receive Buffer Size : " + serverSocket.getReceiveBufferSize());System.out.println("Send Buffer Size : " + serverSocket.getSendBufferSize());System.out.println("Is Socket Bound? : " + serverSocket.isBound());System.out.println("Is Socket Connected? : " + serverSocket.isConnected());System.out.println("Is Socket Closed? : " + serverSocket.isClosed());

Page 37: (Java MCSL 025 Solved)

37

System.out.println("So Timeout : " + serverSocket.getSoTimeout());System.out.println("So Linger : " + serverSocket.getSoLinger());System.out.println("TCP No Delay : " + serverSocket.getTcpNoDelay());System.out.println("Traffic Class : " + serverSocket.getTrafficClass());System.out.println("Socket Channel : " + serverSocket.getChannel());System.out.println("Reuse Address? : " + serverSocket.getReuseAddress());System.out.println("\n");// --------------------------------------// Get (Server) InetAddress / Socket Information// --------------------------------------InetAddress inetAddrServer = serverSocket.getInetAddress();System.out.println("---------------------------");System.out.println("Remote (Server) Information");System.out.println("---------------------------");System.out.println("InetAddress - (Structure) : " + inetAddrServer);System.out.println("Socket Address - (Remote) : " + serverSocket.getRemoteSocketAddress());System.out.println("Canonical Name : " + inetAddrServer.getCanonicalHostName());System.out.println("Host Name : " + inetAddrServer.getHostName());System.out.println("Host Address : " + inetAddrServer.getHostAddress());System.out.println("Port : " + serverSocket.getPort()); System.out.print("RAW IP Address - (byte[]) : ");byte[] b1 = inetAddrServer.getAddress();for (int i=0; i< b1.length; i++) {if (i > 0) {System.out.print(".");}System.out.print(b1[i] & 0xff);}System.out.println();System.out.println("Is Loopback Address? : " + inetAddrServer.isLoopbackAddress());System.out.println("Is Multicast Address? : " + inetAddrServer.isMulticastAddress());System.out.println("\n");// ---------------------------------------------// Get (Client) InetAddress / Socket Information// ---------------------------------------------InetAddress inetAddrClient = serverSocket.getLocalAddress();System.out.println("--------------------------");System.out.println("Local (Client) Information");

Page 38: (Java MCSL 025 Solved)

38

System.out.println("--------------------------");System.out.println("InetAddress - (Structure) : " + inetAddrClient);System.out.println("Socket Address - (Local) : " + serverSocket.getLocalSocketAddress());System.out.println("Canonical Name : " + inetAddrClient.getCanonicalHostName());System.out.println("Host Name : " + inetAddrClient.getHostName());System.out.println("Host Address : " + inetAddrClient.getHostAddress());System.out.println("Port : " + serverSocket.getLocalPort()); System.out.print("RAW IP Address - (byte[]) : ");byte[] b2 = inetAddrClient.getAddress();for (int i=0; i< b2.length; i++) {if (i > 0) {System.out.print(".");}System.out.print(b2[i] & 0xff);}System.out.println();System.out.println("Is Loopback Address? : " + inetAddrClient.isLoopbackAddress());System.out.println("Is Multicast Address? : " + inetAddrClient.isMulticastAddress());System.out.println("\n");// -------------------------------------------------------------// Open an input (buffered) stream that can be used to read from// the socket.// -------------------------------------------------------------BufferedReader is = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));// --------------------// Read from the socket// --------------------String remoteTime = is.readLine();

// ---------------------------------// Close the input (buffered) stream// ---------------------------------is.close();System.out.println("Remote Server Time : " + remoteTime);System.out.println();} catch (UnknownHostException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace(); }}

Page 39: (Java MCSL 025 Solved)

39

}

Exercise 4: Write a Java program to connect to a database created inMS–ACCESS/SQL–SERVER/ORACLE using JDBC concept.Perform basic operations of Selection, Insertion and Deletion on the database.

//Java program to connect to database and perform selection inserion and deletion operations

import java.sql.*;import sun.jdbc.odbc.*;import java.io.*;public class ConnectDatabase{public static void main(String a[]) throws Exception{DataInputStream in=null;Statement s=null;Connection con=null;ResultSet rs=null;int i1,i2,i3;long l1,l2,l3;int n=0;try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }catch(Exception e) {System.out.println(e.getMessage()); System.exit(0); } try {con=DriverManager.getConnection("jdbc:odbc:table"); }catch(Exception e) {System.out.println(e.getMessage()); System.exit(0); } try{in=new DataInputStream(System.in);while(n!=7){String st1,st2,st3; System.out.println("WHAT IS YOUR NEEDS");System.out.println("\t\t 1.To Create a New table");System.out.println("\t\t 2.To Insert values");System.out.println("\t\t 3.To Delete rows");System.out.println("\t\t 4.To Update ");System.out.println("\t\t 5.To Select all records ");System.out.println("\t\t 6.To Drop a table");System.out.println("\t\t 7.Exit");System.out.print("ENTER YOUR CHOICE:");

Page 40: (Java MCSL 025 Solved)

40

n=Integer.parseInt(in.readLine());s=con.createStatement();StringBuffer strb=new StringBuffer();switch(n){case 1: System.out.println("Enter table name:");String s2=new String(in.readLine());System.out.print("Enter number of fields:");int i,n1=Integer.parseInt(in.readLine());strb=strb.append("CREATE TABLE "+s2+"("); for(i=0;i<n1;++i){System.out.print("Enter Field Name:");st1=in.readLine();System.out.print("Enter Data Type[NUMBER,TEXT,DATE/TIME]:");st2=in.readLine();if(i==n1-1)strb=strb.append(st1+" "+st2);elsestrb=strb.append(st1+" "+st2+",");}strb=strb.append(" )");st3=strb.toString();s.executeUpdate(st3);System.out.println("Table created");break;case 2: System.out.println("Enter Employee number:");int eno=Integer.parseInt(in.readLine());System.out.println("Employee Name:");String name=in.readLine();System.out.println("Enter salary:");long sal=Long.parseLong(in.readLine());System.out.println(eno+" "+name+" "+sal);st1="INSERT INTO EMP VALUES("+eno+",'"+name+"',"+sal+")";s.executeUpdate(st1);break;case 3: System.out.println("Enter Employee number:");eno=Integer.parseInt(in.readLine());s.executeUpdate("DELETE FROM EMP WHERE eno="+eno);break;case 4: System.out.println("UPDATE WHAT?");System.out.println("1.EMPLOYEE NAME");System.out.println("2.EMPLOYEE SALARY");System.out.println("3.BOTH");System.out.println("Enter Choice:");i1=Integer.parseInt(in.readLine());switch(i1) {case 1: System.out.print("Enter employee number:");l1=Long.parseLong(in.readLine());System.out.print("Enter new name:");st3=in.readLine();s.executeUpdate("UPDATE EMP SET ename='"+st3+"' WHEREeno="+l1);System.out.println("Table updated");

Page 41: (Java MCSL 025 Solved)

41

break;case 2: System.out.println("Enter employee number:");l1=Long.parseLong(in.readLine());System.out.println("Enter new salary:");l2=Long.parseLong(in.readLine());s.executeUpdate("UPDATE EMP SET sal="+l2+" WHEREeno="+l1);System.out.println("Table updated");break;case 3: System.out.println("Enter employee number:"); l1=Long.parseLong(in.readLine());System.out.println("Enter employee name:");st1=in.readLine();System.out.println("Enter new salary:"); l2=Long.parseLong(in.readLine()); s.executeUpdate("UPDATE EMP SET sal="+l2+",name='"+st1+"' WHERE eno="+l1);System.out.println("Table updated");break;default : System.out.println("Wrong Choice");break;}break; case 5:System.out.println("EMPNUMPER EMPNAME SAL ");System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");rs=s.executeQuery("SELECT * FROM EMP");while(rs.next()){System.out.print(rs.getString("eno")+"\t");System.out.print(rs.getString("ename")+"\t");System.out.print(rs.getString("sal")+"\t");System.out.println();}rs.close();break;case 6:System.out.println("Enter table name:");st1=in.readLine();s.executeUpdate("DROP TABLE "+st1);System.out.println("Table Dropped");break;case 7:break; default:System.out.println("WRONG CHOICE"); break; } }} catch(Exception e) {System.out.println(e.getMessage()); System.exit(0);

Page 42: (Java MCSL 025 Solved)

42

} }}

import java.sql.*;import sun.jdbc.odbc.*;public class oracle{public static void main(String a[]) throws Exception{Statement s=null;Connection con=null; ResultSet rs=null; try{Class.forName("oracle.jdbc.driver.OracleDriver");}catch(Exception e){ System.out.println("driver failure");System.exit(0);}System.out.println("EMPNUMPER"+""+"EMPNAME"+" "+"SAL"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); try{con=DriverManager.getConnection("jdbc:odbc:emp","scott","tiger");}catch(Exception e){ System.out.println("connection problem");System.exit(0);}try { s=con.createStatement(); rs=s.executeQuery("SELECT * FROM EMP");while(rs.next()){System.out.print(rs.getString("empno")+"\t");System.out.print(rs.getString("ename")+"\t");System.out.print(rs.getString("sal")+"\t");System.out.println();} }catch(Exception e) { System.out.println("problem on selection");System.exit(0);}}}

***---END--***