Sunteți pe pagina 1din 35

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

PROGRAM NO:01
AIM: Write a java program to multiply 2 matrices import java.io.*; classmatrixmul { public static void main(String arg[])throws IOException { InputStreamReaderobj=new InputStreamReader(System.in); BufferedReaderbr=new BufferedReader(obj); System.out.println("Enter row and column size of the first array"); int r1=Integer.parseInt(br.readLine()); int c1=Integer.parseInt(br.readLine()); int[][] a=new int[r1][c1]; System.out.println("Enter row and column size of the second array"); int r2=Integer.parseInt(br.readLine()); int c2=Integer.parseInt(br.readLine()); int[][] b=new int[r2][c2]; int[][] c=new int[r1][c2]; if(c1==r2) { System.out.println("Enter the first matrix value"); for(int i=0;i<r1;i++) { for(int j=0;j<c1;j++ ) a[i][j]=Integer.parseInt(br.readLine()); } System.out.println("Enter the second matrix value"); for(int i=0;i<r2;i++) { for(int j=0;j<c2;j++ ) b[i][j]=Integer.parseInt(br.readLine()); } for(int i=0;i<r1;i++) { for(int j=0;j<c2;j++) { c[i][j]=0; for(int k=0;k<=r1;k++) { c[i][j]=c[i][j]+(a[i][k]*b[k][j]); } } } System.out.println("The resultant matrix is");
Dept.of Computer Science And Applications, SJCET, Palai Page 1

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

for(int i=0;i<r1;i++) { for(int j=0;j<c2;j++) { System.out.print(" "+c[i][j]); } System.out.println("\n"); } } else { System.out.println("multiplication cann't perform"); } } }

OUTPUT Enter row and column size of the matrix 3 3 Enter the matrix values 3 3 2 4 6 7 8 9 10 The resultant matrix is 3 4 8 3 6 9

2 7 10

Dept.of Computer Science And Applications, SJCET, Palai Page 2

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

PROGRAM NO: 02
AIM: Program that demonstrate the concept of class, object and constructor import java.io.*; classemp { intemp_code; String name,designation; doubleba_pay,hra,da,total; emp(intcode,doubleba,Stringnme,String des) { emp_code=code; ba_pay=ba; name=nme; designation=des; } void display() { hra=ba_pay* .1; da =ba_pay* .45; total=ba_pay+hra+da; System.out.println("Emp_code :"+emp_code); System.out.println("Name :"+name); System.out.println("Designation:"+designation); System.out.println("Basic pay :"+ba_pay); System.out.println("hra :"+hra); System.out.println("da :"+da); System.out.println("total pay :"+total); } } class employee { public static void main(String arg[])throws IOException { intcode,i; doubleba; String name=" "; String designation=" "; InputStreamReaderobj=new InputStreamReader(System.in); BufferedReaderbr=new BufferedReader(obj); System.out.println("Enter the number of employees"); int n=Integer.parseInt(br.readLine()); emp stud[]=new emp[n]; System.out.println("Enter the detailesof"+n+"employee")
Dept.of Computer Science And Applications, SJCET, Palai Page 3

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

for(i=0;i<n;i++) { System.out.println(" "+(i+1)); System.out.println("Enter Employee code"); code=Integer.parseInt(br.readLine()); System.out.println("Enter the name"); name=br.readLine(); System.out.println("Enter designation"); designation=br.readLine(); System.out.println("Enter basic pay"); ba=Double.parseDouble(br.readLine()); stud[i]=new emp(code,ba,name,designation); System.out.println("The Entered details are:"); for(i=0;i<n;i++) { System.out.println("Sl no."+(i+1)); stud[i].display(); }

OUTPUT Enter the number of employees 2 Enter the detailes of2employee 1 Enter Employee code 12 Enter the name sree Enter designation md Enter basic pay 50000 2 Enter Employee code 13
Dept.of Computer Science And Applications, SJCET, Palai Page 4

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

Enter the name sr Enter designation sdgd Enter basic pay 100 The Entered details are: Sl no.1 Emp_code :12 Name :sree Designation:md Basic pay :50000.0 hra :5000.0 da :22500.0 total pay :77500.0 Sl no.2 Emp_code :13 Name :sr Designation:sdgd Basic pay :100.0 hra :10.0 da :45.0 total pay :155.0

Overloading
In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. Method overloading is one of Java's most exciting and useful features. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. When an overloaded method is called, Java looks for a match between the arguments used to call the method and the method's parameters. However, this match need not always be exact. Java understands these methods withtheir signatures. Java identifies the methods by comparing their signatures like return types, constructor parameters & access modifier used.

Dept.of Computer Science And Applications, SJCET, Palai Page 5

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

PROGRAM NO:03
AIM: Program demonstrating method overloading PROGRAM import java.io.*; classrect { double a; voidcir_area(double r) { a=3.14*r*r; } voidrect_area(double l,double b) { a=l*b; } voidtra_area(double l,doubleb,double h) { a=h*(l+b)/2;
Dept.of Computer Science And Applications, SJCET, Palai Page 6

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

} void display() { System.out.println("Area="+a); } class area2 { public static void main(String arg[])throws IOException { InputStreamReaderobj=new InputStreamReader(System.in); BufferedReaderbr=new BufferedReader(obj); charch; double b; do { System.out.println("1.Rectangle\n2.Circle\n3.Trapezium\n4.Exit"); int x=Integer.parseInt(br.readLine()); BufferedReader br1=new BufferedReader(obj); rectrectarea=new rect(); switch(x) { case 1: System.out.println("Enter the length"); double l=Double.parseDouble(br.readLine()); System.out.println("Enter the breadth"); b=Double.parseDouble(br.readLine()); rectarea.rect_area(l,b); break; case 2: System.out.println("Enter the radius"); double r=Double.parseDouble(br.readLine()); rectarea.cir_area(r); break; case 3: System.out.println("Enter the length of first side"); double a=Double.parseDouble(br.readLine()); System.out.println("Enter the length of second side"); b=Double.parseDouble(br.readLine()); System.out.println("Enter the height"); double h=Double.parseDouble(br.readLine()); rectarea.tra_area(a,b,h); break;
Dept.of Computer Science And Applications, SJCET, Palai Page 7

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

case 4: System.exit(0); break; default: System.out.println("Wrong entry"); } rectarea.display(); System.out.println("Do u want to continue"); ch=(char)br1.read(); }while(ch=='y'||ch=='Y'); } }

OUTPUT 1.Rectangle 2.Circle 3.Trapezium 4.Exit 1 Enter the length 4 Enter the breadth 5 Area=20.0 Do u want to continue y 1.Rectangle 2.Circle 3.Trapezium 4.Exit 2 Enter the radius 5 Area=78.5 Do u want to continue y 1.Rectangle 2.Circle 3.Trapezium
Dept.of Computer Science And Applications, SJCET, Palai Page 8

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

4.Exit 3 Enter the length of first side 2 Enter the length of second side 2 Enter the height 5 Area=10.0 Do u want to continue n

Inheritance
Inheritance is one of the concepts of the Object- Oriented programming. It allows us to define a general class, and later more specialized classes by simply adding some new details.The derived class is called as child class or the subclass or we can say the extended class and the class from which we are deriving the subclass are called the base class or the parent class. The properties of the parent class will automatically will be inherited by the base class.To derive a class in java the keyword extends is used. The following kinds of inheritance are there in java: Simple Inheritance When a subclass is derived simply from its parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and its parent class. It is also called single inheritance or one level inheritance. Multilevel Inheritance It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for its parent class and this parent class works as the child class for it's just above (parent) class. Multilevel inheritance can go up to any number of levels. A subclass does not inherit the private members of its parent class. A nested class has access to all the private members of its enclosing classboth fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass. A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. We can use the inherited members as is, replace them, hide them, or supplement them with new members:

Dept.of Computer Science And Applications, SJCET, Palai Page 9

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

We can declare new fields and methods in the subclass that are not in the superclass. The inherited methods can be used directly as they are. We can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. We can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. Super keyword The super is java keyword. As the name suggest super is used to access the members of the super class. It is used for two purposes in java. The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class.

PROGRAM NO: 04
AIM Program demonstrating inheritance PROGRAM import java.io.*; importjava.lang.Math; class mean { int m=0,n,i,x; mean(intnum,intarr[]) { n=num; for(i=0;i<n;i++) { x=x+arr[i]; } m=x/n; } void display() { System.out.println("m="+m); } } classsd extends mean { doublestd_dev,a=0; sd(intnum,intarr[])
Dept.of Computer Science And Applications, SJCET, Palai Page 10

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

{ super(num,arr); for(i=0;i<n;i++) a=a+Math.pow((arr[i]-m),2); std_dev=Math.sqrt(a/n); } void display() { System.out.println("standard dev="+std_dev); } } classmean_sd { public static void main(String arg[])throws IOException { InputStreamReaderobj=new InputStreamReader(System.in); BufferedReaderbr=new BufferedReader(obj); charch; intn,i; do { BufferedReader br1=new BufferedReader(obj); System.out.println("Enter the number of values"); n=Integer.parseInt(br.readLine()); int[] arr=new int[n]; System.out.println("Enter n numbers"); for(i=0;i<n;i++) { arr[i]=Integer.parseInt(br.readLine()); } meansupobj=new mean(n,arr); supobj.display(); sdsubobj=new sd(n,arr); subobj.display(); System.out.println("Do u want to continue"); ch=(char)br1.read(); }while(ch=='y'||ch=='Y'); } }

Dept.of Computer Science And Applications, SJCET, Palai Page 11

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

OUTPUT Enter the number of values 5 Enter n numbers 9 8 7 6 5 m=7 standarddev=1.4142135623730951 Do u want to continue n

Dept.of Computer Science And Applications, SJCET, Palai Page 12

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

Abstract class
An abstract class is a class that is declared abstractit may or may not include abstract methods. An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this: abstract void moveTo(double deltaX, double deltaY); Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree. Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods. Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. We need to create a subclass that provides an implementation for the abstract method.

Dept.of Computer Science And Applications, SJCET, Palai Page 13

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

PROGRAM NO: 05
AIM: Program demonstrating concept of abstract class PROGRAM import java.io.*; importjava.lang.Math; abstract class perfect { abstract void special(int n); } class square extends perfect { int a; void special(int n) { for(int i=1;i<=n;i++) { a=(int)Math.sqrt(i); if((a*a)==i) System.out.println(i); } } } classabstract_void { public static void main(String args[])throws IOException { InputStreamReaderobj=new InputStreamReader(System.in); BufferedReaderbr=new BufferedReader(obj); charch; do { BufferedReader br1=new BufferedReader(obj); System.out.println("Enter value of n"); int n1=Integer.parseInt(br.readLine()); squaresubobj=new square(); subobj.special(n1);
Dept.of Computer Science And Applications, SJCET, Palai Page 14

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

System.out.println("Do u want to continue"); ch=(char)br1.read(); }while(ch=='y'||ch=='Y'); } }

OUTPUT
Dept.of Computer Science And Applications, SJCET, Palai Page 15

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

Enter value of n 50 1 4 9 16 25 36 49 Do u want to continue n

Packages

Dept.of Computer Science And Applications, SJCET, Palai Page 16

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

TheJava Language Specification defines Packages as groups of Java classes and Java interfaces. Packages are a tool for managing a large namespace and avoiding conflicts. Every Java class and interface name is contained in some package. A package is a grouping of related types providing access protection and name space management. Note that types refer to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces. Multiple files can specify the same package name. If no package is specified, the classes in the file go into a special unnamed package (the same unnamed package for all files). If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name). We can access public classes in another (named) package using: package-name.class-name We can access the public fields and methods of such classes using: package-name.class-name.field-or-method-name We can avoid having to include the package-name using: importpackage-name.*; or importpackage-name.class-name; at the beginning of the file (after the package declaration). The former imports all of the classes in the package, and the second imports just the named class. You must still use: class-name to access the classes in the packages, and class-name.field-or-method-name to access the fields and methods of the class; the only thing you can leave off is the package name.

PROGRAM NO: 06
AIM: Program demonstrating packages PROGRAM package access; public class Access { intdef=1; privateintpri=2; publicint pub=3;
Dept.of Computer Science And Applications, SJCET, Palai Page 17

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

protectedint pro=4; public void display() { System.out.println("inside Access"); System.out.println(def); System.out.println(pri); System.out.println(pub); System.out.println(pro); } } package access; public class derv extends Access { public void display1() { System.out.println("inside derv"); System.out.println(def); System.out.println("pri can't access in derv class"); System.out.println(pub); System.out.println(pro); } } package access; public class nonderv { public void display() { Access object=new Access(); System.out.println("inside nonderv"); System.out.println(object.def); System.out.println("private can't access in non derv class"); System.out.println(object.pub); System.out.println(object.pro); } } package access1; import access.*; public class OtherPack extends Access { public void display() { System.out.println("inside otherpack"); System.out.println("default can't access in otherpack class");
Dept.of Computer Science And Applications, SJCET, Palai Page 18

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

System.out.println("private can't access in otherpack class"); System.out.println(pub); System.out.println(pro); } } package access1; import access.*; class OtherPack1 { public static void main(String arg[]) { Access ob=new Access(); ob.display(); derv ob1=new derv(); ob1.display1(); nonderv ob2=new nonderv(); ob2.display(); OtherPack ob3=new OtherPack(); ob3.display(); } }

OUTPUT Z:\java\cycle4\qn3>cd access Z:\java\cycle4\qn3\access>javac *.java Z:\java\cycle4\qn3\access>cd.. Z:\java\cycle4\qn3>javac access1\*.java Z:\java\cycle4\qn3>java access1.OtherPack1 inside Access 1 2 3 4 inside derv 1 pri can't access in derv class
Dept.of Computer Science And Applications, SJCET, Palai Page 19

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

3 4 insidenonderv 1 private can't access in non derv class 3 4 insideotherpack default can't access in otherpack class private can't access in otherpack class 3 4

Interface
In the Java programming language, an interface is a reference type, similar to a class that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated - they can only be implemented by classes or extended by other interfaces. The method signatures have no braces and are terminated with a semicolon. To use an interface, we write a class that implements the interface. When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. Programs can use interfaces to make it unnecessary for related classes to share a common abstract superclass or to add methods to Object. An interface may be declared to be a direct extension of one or more other interfaces, meaning that it implicitly specifies all the member types, abstract methods and constants of the interfaces it extends, except for any member types and constants that it may hide. A class may be declared to directly implement one or more interfaces, meaning that any instance of the class implements all the abstract methods specified by the interface or interfaces. A class necessarily implements all the interfaces that its direct superclasses and direct superinterfaces do. This (multiple) interface inheritance allows objects to support (multiple) common behaviors without sharing any implementation.
Dept.of Computer Science And Applications, SJCET, Palai Page 20

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

A variable whose declared type is an interface type may have as its value a reference to any instance of a class which implements the specified interface. It is not sufficient that the class happen to implement all the abstract methods of the interface; the class or one of its superclasses must actually be declared to implement the interface, or else the class is not considered to implement the interface.

PROGRAM NO: 07
AIM: Program demonstrating concept of interfaces PROGRAM import java.io.*; importjava.lang.Math; interface Hyperbolic { int n=10; doublehypfun(double x); } classHSin implements Hyperbolic { doublec,fa,f,sum; public double hypfun(double x) { sum=0;c=0;fa=0; for(int i=1;i<=n;i++) { c=((2*i)+1); fa=fact(c); sum=sum+(Math.pow(x,c)/fa); }
Dept.of Computer Science And Applications, SJCET, Palai Page 21

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

sum=x+sum; return(sum); } public double fact(double c1) { f=1; for(int i=1;i<=c1;i++) { f=f*i; } return(f); } } classHCos implements Hyperbolic { double c1,fa1,f1,sum1; public double hypfun(double x) { sum1=0;c1=0;fa1=0; for(int i=1;i<=n;i++) { c1=(2*i); fa1=fact(c1); sum1=sum1+(Math.pow(x,c1)/fa1); } sum1=1+sum1; return(sum1); } public double fact(double cc) { f1=1; for(int i=1;i<=cc;i++) { f1=f1*i; } return(f1); } } classsico { public static void main(String args[]) throws IOException { doublec,s; BufferedReaderobj=new BufferedReader(new InputStreamReader(System.in)); HSinsobj=new HSin(); HCoscobj=new HCos(); System.out.println(" x sin cos" ); for(double i=0;i<=5;) {
Dept.of Computer Science And Applications, SJCET, Palai Page 22

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

s=sobj.hypfun(i); c=cobj.hypfun(i); System.out.println(" "+i+" i=i+0.5; } } }

"+s+"

"+c);

OUTPUT xsin 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 cos 0.0 1.0 0.5210953054937474 1.1752011936438014 2.1292794550948173 3.626860407847018 6.0502044810397315 10.017874927406208 16.542627287506175 27.289917194331494 45.00301110970271 74.20321009674765 1.1276259652063807 1.5430806348152437 2.352409615243247 3.7621956910836283 6.132289479663176 10.067661995749384 16.572824670209222 27.308232819900013 45.01411993173614 74.20994630373977

Dept.of Computer Science And Applications, SJCET, Palai Page 23

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

User-defined Exceptions
Java supports exception handling by its try catch constructs. Exceptions are conditions which the JVM or applications developed in Java are unable to handle. The Java API defines exception classes for such conditions. These classes are derived from java.lang.Throwable class. User defined exceptions are those exceptions which an application provider or an API provider defines by extending java.lang.Throwable class. A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follow the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. We can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.Using a finally block allows us to run any cleanup-type statements that we want to execute, no matter what happens in the protected code.A finally block appears at the end of the catch blocks We just need to extend the Exception class to create our own Exception class. These are considered to be checked exceptions. In the following program theUnacceptableRootsException class is a userdefined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Dept.of Computer Science And Applications, SJCET, Palai Page 24

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

PROGRAM NO: 08
AIM Program demonstrating user-defined Exceptions PROGRAM import java.io.*; importjava.lang.Math; classUnacceptableRootsException extends Exception { UnacceptableRootsException(String s) { super(s); } public static void main(String args[])throws IOException { int d; double root1,root2; InputStreamReaderobj=new InputStreamReader(System.in); BufferedReaderbr=new BufferedReader(obj); System.out.println("Enter a,b and c"); int a=Integer.parseInt(br.readLine()); int b=Integer.parseInt(br.readLine()); int c=Integer.parseInt(br.readLine()); try { d=(b*b)-(4*a*c); if(d<0) { throw new UnacceptableRootsException("Roots doesn't exists"); } else if(d>0) { root1=(-b+Math.sqrt(d))/(2*a); root2=(-b-Math.sqrt(d))/(2*a); System.out.println(root1); System.out.println(root2); } else { root1=-b/(2*a); System.out.println(root1); }
Dept.of Computer Science And Applications, SJCET, Palai Page 25

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

} catch(UnacceptableRootsException e) { System.out.println(e); } } }

OUTPUT Enter a,b and c 1 2 3


Dept.of Computer Science And Applications, SJCET, Palai Page 26

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

quadratic: Roots doesn't exists Z:\java\cycle5>java quadratic Enter a,b and c 1 7 12 -3.0 -4.0

Multi-threading
Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

Dept.of Computer Science And Applications, SJCET, Palai Page 27

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes.Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode on a single processor system. In the multithreading concept, several multiple lightweight processes are run in a single process/task or program by a single processor.Multithreaded software treats each process as a separate program. In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time. By calling a Thread object's start () method a Java application tells the JVM to start a separate thread of execution. The JVM will only allow a Thread object to create a single thread of execution for the lifetime of the object. Subsequent calls to an object's start () method will be ignored if the thread associated with the object has terminated; otherwise, the JVM will cause the start() method to throw illegalThreadStateException. Once the JVM sets up the separate thread of execution it will call the object's run() method from within the newly created thread. The run() method of a Java Thread is like the thread's "main" method. Once started by the JVM, the thread exists until the run() method terminates. Join is a simple synchronization mechanism that allows one thread to wait for another to finish. In the Basic Thread example, the main application waits for the threads that it started to finish. Note that the order in which threads are joined is not important.

PROGRAM NO: 09
AIM Program demonstrating multi-threading PROGRAM import java.io.*; importjava.lang.Math.*;
Dept.of Computer Science And Applications, SJCET, Palai Page 28

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

class sin extends Thread { double d,r; sin(double deg) { d=deg; } public void run() { doubledegforrad=Math.toRadians(d); r=Math.sin(degforrad); System.out.println("Sin(" +d+ ")=" +r); } } classcos extends Thread { double d,r; cos(double deg) { d=deg; } public void run() { doubledegforrad=Math.toRadians(d); r=Math.cos(degforrad); System.out.println("cos(" +d+ ")=" +r); } } classthreadjoin { public static void main(String args[])throws IOException { InputStreamReaderobj=new InputStreamReader(System.in); BufferedReaderbr=new BufferedReader(obj); System.out.println("Enter the angle"); double x=Double.parseDouble(br.readLine()); sin t1=new sin(x); cos t2=new cos(x); t1.start(); try { t1.join();
Dept.of Computer Science And Applications, SJCET, Palai Page 29

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

} catch(InterruptedException e) { System.out.println(e); } t2.start(); try { t2.join(); } catch(InterruptedException e) { System.out.println(e); } double result=t1.r+t2.r; System.out.println("sinx + cosx = "+result); } }

OUTPUT Z:\java>javac threadjoin.java Z:\java>java threadjoin Enter the angle 60 Sin(60.0)=0.8660254037844386 cos(60.0)=0.5000000000000001 sinx + cosx = 1.3660254037844388

Dept.of Computer Science And Applications, SJCET, Palai Page 30

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

Producer Consumer Problem


The Producer andConsumerin this example share data through a common object. And neither the Producernor the Consumer makes any effort whatsoever to ensure that the Consumeris getting each value produced once and only once. One problem arises when the Produceris quicker than the Consumer and generates two numbers before the Consumerhas a chance to consume the first one. Thus the Consumerwould skip a number. Another problem that might arise is when the Consumeris quicker than the Producerand consumes the same value twice. In this situation, the Consumerwould print the same value twice. Either way, the result is wrong. We want the Consumer to get each integer produced by the Producerexactly once. Problems such as those just described are called race conditions. They arise from multiple, asynchronously executing threads trying to access a single object at the same time and getting the wrong result.
Dept.of Computer Science And Applications, SJCET, Palai Page 31

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

The activities of the Producerand Consumermust be synchronized in two ways. First, the two threads must not simultaneously access the object. A Java thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked. And second, the two threads must do some simple coordination. That is, the Producermust have some way to indicate to the Consumerthat the value is ready and the Consumermust have some way to indicate that the value has been retrieved. The Threadclass provides a collection of methods--wait, notify, and notifyAll--to help threads wait for a condition and notify other threads of when that condition changes

PROGRAM NO:10
AIM: Program demonstrating Producer Consumer Problem

PROGRAM
import java.io.*; classpcproblem { public static void main(String args[]) { Q q=new Q(); new producer(q); new consumer(q); } } class consumer implements Runnable { Q q;
Dept.of Computer Science And Applications, SJCET, Palai Page 32

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

consumerpt; consumer(Q q) { this.q=q; Thread pt=new Thread(this); pt.start(); } public void run() { boolean i=true; int count=1; while(i) { q.gets(); count++; if(count==10) i=false; } } } class producer implements Runnable { Q q; producerpt; producer(Q q) { this.q=q; Thread pt=new Thread(this); pt.start(); } public void run() { boolean i=true; int count=1,j=0; while(i) { q.puts(j++); count++; if(count==10) i=false; } } } class Q { boolean value=false; int n; synchronizedint gets() {
Dept.of Computer Science And Applications, SJCET, Palai Page 33

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

if(!value) { try { wait(); } catch(InterruptedException e) { System.out.println(e); } } System.out.println("Get"+n); value=false; notify(); return n; } synchronized void puts(int n) { if(value) { try { wait(); } catch(InterruptedException e) { System.out.println(e); } } this.n=n; value=true; System.out.println("Put"+n); notify(); } }

Dept.of Computer Science And Applications, SJCET, Palai Page 34

Lab Manual MCA-407 Java and Web Programming Lab

ADMN 2009-10

OUTPUT Z:\java\cycle5>java pcproblem Put0 Get0 Put1 Get1 Put2 Get2 Put3 Get3 Put4 Get4 Put5 Get5 Put6 Get6 Put7 Get7 Put8 Get8

Dept.of Computer Science And Applications, SJCET, Palai Page 35

S-ar putea să vă placă și