Vous êtes sur la page 1sur 33

1. a) Write a JAVA Program to demonstrate Constructor Overloading and Method overloading.

class box { double width,height,depth,length,breadth; box() { } box(double w,double h,double d) { width = w; height = h; depth = d; } box(double len) { width = height = depth = len; } void rect(double x,double y) { length = x; breadth = y; } void rect(double x) { length = breadth = x; } double volume() { return(width * height * depth); } double area() { return(length * breadth); } } class lab01a { public static void main(String args[]) { box mybox1 = new box(10,20,15);

box mybox2 = new box(5); box rect1 box rect2 = new box(); = new box();

rect1.rect(10,20); rect2.rect(8); double areaR, vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 = " +vol); vol = mybox2.volume(); System.out.println("Volume of mybox2 = " +vol); areaR = rect1.area(); System.out.println("Area of rect1= " +areaR); areaR = rect2.area(); System.out.println("Area of rect1 = " +areaR); } } Output: C:\New Folder>java lab01a Volume of mybox1 = 3000.0 Volume of mybox2 = 125.0 Area of rect1= 200.0 Area of rect1 = 64.0 Two or more methods within the same class that share the same name, as long as their parameter declarations are different are called method overloading. box () is a constructor is called three times with different parameters and rect() is a method, which is called two times with different parameters. 1 b) Write a JAVA Program to implement Inner class and demonstrate its Access Protections. class outer { int outdata = 10; void display() { inner inobj = new inner();

System.out.println("Accessing from outer class"); System.out.println("The value of outdata is " +outdata); System.out.println("The value of indata is " +inobj.indata); } class inner { int indata = 20; void inmethod() { System.out.println("Accessing from inner class"); System.out.println("The sum of indata & outdata is " +(outdata + indata)); } } } class lab01b { public static void main(String args[]) { outer outobj = new outer(); outobj.display(); outer.inner inobj1 = outobj.new inner(); inobj1.inmethod(); } } Output: C:\New Folder>java lab01b Accessing from outer class The value of outdata is 10 The value of indata is 20 Accessing from inner class The sum of indata & outdata is 30 An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class. An instance of Inner can be created only within the scope of class Outer. The Java compiler generates an error message if any code outside of class Outer attempts to instantiate class Inner. 2 a) Write a JAVA Program to implement Inheritance. class A { int i = 10; protected int j = 20;

void showij() { System.out.println("i = " +i); System.out.println("j = " +j); } } class B extends A { int k = 30; void showk() { System.out.println("k = " +k); } void sum() { System.out.println("i + j + k = " +(i+j+k)); } } class lab02a { public static void main(String args[]) { B subobj = new B(); System.out.println("Contents of Super class accessed using sub class object"); subobj.showij(); System.out.println("Contents of Supter class accessed using sub class object"); subobj.showk(); System.out.println("Sum of i, j, & k accessed using sub class object"); subobj.sum(); } } Output: C:\New Folder>java lab02a Contents of Super class accessed using sub class object i = 10 j = 20 Contents of Super class accessed using sub class object k = 30

Sum of i, j, & k accessed using sub class object i + j + k = 60 The subclass B includes all of the members of its superclass, A. This is why subOb can access i and j and call showij( ). Also, inside sum( ), i and j can be referred to directly, as if they were part of B. Even though A is a superclass for B, it is also a completely independent, standalone class. Being a superclass for a subclass does not mean that the superclass cannot be used by itself. 2 b) Write a JAVA Program to implement Exception Handling (Using Nested try catch and finally). class Nesttry { public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a" + "= " + a); try { if(a==1) a = a / (a-a); if(a==2) { int c[] = {1}; c[42] = 99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("array out of bounds" + e) ; } finally { System.out.println("inside first try"); } } catch(ArithmeticException e) { System.out.println("Arithmetic Exp" + e); } finally { System.out.println("Inside 2nd try"); } } }

Output: C:\New Folder>java Nesttry Arithmetic Expjava.lang.ArithmeticException: / by zero Inside 2nd try C:\New Folder>java Nesttry 1 3 a= 2 array out of boundsjava.lang.ArrayIndexOutOfBoundsException: 42 inside first try Inside 2nd try A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. This program will generate Divide by zero and ArrayIndexOutOfBoundsException. 3. i) Write a Java program which has a class called Account that creates account with 500 Rs minimum balance, a deposit () method to deposit amount, a whithdraw () method to withdraw amount and also throws LessBalancEexception if an account holder tries withdraw money which makes the balance become less than 500Rs. ii) A class called LessBalanceException which returns the statement that says (_Rs) is not valid. iii) A class which creates two accounts, both account deposit money and one account tries to withdraw more money which generates a LessBalanceException take appropriate action for the same. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class LessBalanceException extends Exception { double wid; LessBalanceException(Double withdraw) { wid = withdraw; } public String toString() { return "Rs. "+wid+" U Cannot with draw, Balance should not less than 500"; } }

class Account { double currBal=500; void Deposit () throws IOException { BufferedReader br= new BufferedReader (new InputStreamReader (System. in)); System.out.println ("Enter deposit amount: "); double dep = Double.parseDouble (br.readLine ()); if (dep < 100) { System.out.println (" Deposit Amount should be atleast 100 "); return; } currBal+=dep; System.out.println ("Amount RS.+dep+" Deposited... "); } void CurrBalance() { System.out.print("Current Balance : "+currBal); } void Withdraw() throws LessBalanceException,IOException { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Withdrawal amount : "); double with = Double.parseDouble(br.readLine()); if(with < 100) { System.out.println(" Withdrawal Amount should b atleast 100 "); return; } if(currBal - with < 500) throw new LessBalanceException(with); else { currBal-=with; System.out.println("Amount RS. "+with+" withdrawed... "); } } } public class Person { public static void main(String args[]) throws IOException,LessBalanceException {

Account a1 = new Account(); Account a2 = new Account(); int ch=1,num; while(true) { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); System.out.println("Which Account [1,2] And Other num to exit"); num=Integer.parseInt(br.readLine()); if(num == 3) break; switch(num) { case 1: while(true) { System.out.println(" Enter the choice \n 1: Deposit \n 2: Withdraw \n 3: Current Balance \n Others: Main menu"); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: a1.Deposit(); continue; case 2: try { a1.Withdraw(); } catch(LessBalanceException e) { System.out.println("Error : "+e+"\n"); } continue; case 3: System.out.println(" Current Balance : "+a1.currBal+"\n"); continue; default: break; } break; } break;

case 2: while(true) { System.out.println(" Enter the choice \n 1: Deposit \n 2: Withdraw \n 3: Current Balance \n Others: Main Menu"); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: a2.Deposit(); continue; case 2: try { a1.Withdraw(); } catch(LessBalanceException e) { System.out.println("Error : "+e+"\n"); } continue; case 3: System.out.println(" Current Balance : "+a2.currBal+"\n"); continue; default: break; } break; } break; default: break; } } } OutPut: C:\New Folder>java Person Which Account [1,2] And Other num to exit 1 Enter the choice 1: Deposit 2: Withdraw 3: Current Balance Others: Main Menu 1 Enter deposit amount : 1000

Amount RS. 1000.0 Deposited... Enter the choice 1: Deposit 2: Withdraw 3: Current Balance Others: Main Menu 3 Current Balance : 1500.0 Enter the choice 1: Deposit 2: Withdraw 3: Current Balance Others: Main Menu 2 Enter Withdrawal amount : 1200 Error : Rs. 1200.0 U Cannot with draw, Balance should not less than 500 Enter the choice 1: Deposit 2: Withdraw 3: Current Balance Others: Main Menu 3 Current Balance : 1500.0 Enter the choice 1: Deposit 2: Withdraw 3: Current Balance Others: Main Menu 4 Which Account [1,2] And Other num to exit 3 We create our own customized exception as per requirements of the application. Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter. While defining an user defined exception, we need to take care of the following aspects:

The user defined exception class should extend from Exception class. The toString () method should be overridden in the user defined exception class in order to display meaningful information about the exception.

4. Write a Java program using Synchronized Threads, Which demonstrates Producer Consumer concepts. class Q { int n; boolean valueSet = false; synchronized int get() { while(!valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { while(valueSet) try { wait(); } catch (Interrupted Exception e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("Put: " + n); notify(); } } class Producer implements Runnable { Q q; Producer (Q q) {

this.q = q; new Thread(this, "Producer").start(); } public void run () { int i = 0; while(true) { q.put(i++); } } } class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while(true) { q.get(); } } } class PCFixed { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } } Output: Got: 296 Put: 297 Got: 297 Put: 298 Got: 298 Put: 299 Got: 299 Put: 300

Got: 300 Put: 301 Got: 301 Put: 302 Got: 302 5. Write a JAVA program which has i. A Interface class for Stack Operations ii. A Class that implements the Stack Interface and creates a fixed length Stack. iii. A Class that implements the Stack Interface and creates a Dynamic length Stack. iv. A Class that uses both the above Stacks through Interface reference and does the Stack operations that demonstrates the runtime binding. // Define an integer stack interface. interface IntStack { void push(int item); // store an item int pop(); // retrieve an item } // An implementation of IntStack that uses fixed storage. class FixedStack implements IntStack { private int stck[]; private int tos; // allocate and initialize stack FixedStack(int size) { stck = new int[size]; tos = -1; } // Push an item onto the stack public void push(int item) { if(tos==stck.length-1) // use length member System.out.println("Stack is full."); else stck[++tos] = item; } // Pop an item from the stack public int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; }

else return stck[tos--]; } } // Implement a "growable" stack. class DynStack implements IntStack { private int stck[]; private int tos; // allocate and initialize stack DynStack(int size) { stck = new int[size]; tos = -1; } // Push an item onto the stack public void push(int item) { // if stack is full, allocate a larger stack (tos==stck.length-1) { int temp[] = new int[stck.length * 2]; // double size for(int i=0; i<stck.length; i++) temp[i] = stck[i]; stck = temp; stck[++tos] = item; } else stck[++tos] = item; } // Pop an item from the stack public int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos--]; } } /* Create an interface variable and access stacks through it. */ class IFTest3 { public static void main(String args[]) {

IntStack mystack; // create an interface reference variable DynStack ds = new DynStack(5); FixedStack fs = new FixedStack(8); mystack = ds; // load dynamic stack // push some numbers onto the stack for(int i=0; i<12; i++) mystack.push(i); mystack = fs; // load fixed stack for(int i=0; i<8; i++) mystack.push(i); mystack = ds; System.out.println("Values in dynamic stack:"); for(int i=0; i<12; i++) System.out.println(mystack.pop()); mystack = fs; System.out.println("Values in fixed stack:"); for(int i=0; i<8; i++) System.out.println(mystack.pop()); } } Output: C:\New Folder>java IFTest3 Values in dynamic stack: 11 10 9 8 7 6 5 4 3 2 1 0 Values in fixed stack: 7 6 5 4 3 2 1 0 The above program creates a stack, pushes several Integer objects onto it, and

then pops them off. 6. Write a JAVA program which has i. 2 classes which initializes a String in its constructor ii. A Generic class with 2 type Parameters iii. Create a Generic Class reference for the above 2 Class and try to print the message inside the constructor (Use to string method).
class samp1A { String s1; samp1A(String s) { s1=s; } public String toString() { return s1; } } class samp2A { String s2; samp2A(String s) { s2=s; } public String toString() { return s2; } } class TwoGenA<T,V> { T obj1; V obj2; TwoGenA(T t,V v) { obj1=t; obj2=v; System.out.println("Contents of s1 is,"+obj1.toString()); System.out.println("Contents of s2 is,"+obj2.toString()); } } class lab6A { public static void main(String args[]) { samp1A o1=new samp1A("Hi");A o2=new samp2A("Raj");

TwoGenA<samp1A,samp2A> o3=new TwoGenA<samp1A,samp2A>(o1,o2); TwoGenA<Integer,Double> o4=new TwoGenA<Integer,Double>(1,234.677); System.out.println("\n"); } } -----------------------------------------------------------------------------------------------------------------------------------

// A simple generic class with two type parameters: T and V. class TwoGen<T, V> { T ob1; V ob2; // Pass the constructor a reference to // an object of type T and an object of type V. TwoGen(T o1, V o2) { ob1 = o1; ob2 = o2; } // Show types of T and V. void showTypes() { System.out.println("Type of T is " + ob1.getClass().getName()); System.out.println("Type of V is " + ob2.getClass().getName()); } T getob1() { return ob1; } V getob2() { return ob2; } } // Demonstrate TwoGen. class simpGen { public static void main(String args[]) { TwoGen<Integer, String> tgObj = new TwoGen<Integer, String>(24, "Java"); TwoGen<Integer, String> tgObj1 = new TwoGen<Integer, String>(24, "Generics class"); // Show the types.

tgObj.showTypes(); // Obtain and show values. int v = tgObj.getob1(); System.out.println("value: " + v); String str = tgObj.getob2(); System.out.println("value: " + str); int x = tgObj1.getob1(); System.out.println("value: " + x); String str1 = tgObj1.getob2(); System.out.println("value: " + str1); } } OutPut: C:\New Folder>java simpGen Type of T is java.lang.Integer Type of V is java.lang.String value: 24 value: Java value: 24 value: Generics class The term generic means parameterized types. Using generics, it is possible to create a single class, for example, that automatically works with different types of data. A class, interface, or method that operates on a parameterized type is called generic, as in generic class or generic method. When declaring an instance of a generic type, the type argument passed to the type parameter must be a class type. You cannot use a primitive type, such as int or char. 7. Write JAVA programs which demonstrate utilities of Linked List Class. // Demonstrate Linked List. import java.util.*; class LinkedListDemo { public static void main (String args[]) { // Create a linked list. Linked List<String> ll = new LinkedList<String>(); // Add elements to the linked list. ll.add ("F"); ll.add ("B"); ll.add ("D"); ll.add ("E"); ll.add ("C"); ll.addLast ("Z"); ll.addFirst ("A");

ll.add (1, "A2"); System.out.println ("Original contents of ll: " + ll); // Remove elements from the linked list. ll.remove ("F"); ll.remove (2); System.out.println ("Contents of ll after deletion: "+ ll); // Remove first and last elements. ll.removeFirst (); ll.removeLast (); System.out.println ("ll after deleting first and last: "+ ll); // Get and set a value. String val = ll.get (2); ll.set (2, val + Changed"); System.out.println ("ll after change: " + ll); } } OutPut : Original contents of ll: [A, A2, F, B, D, E, C, Z] Contents of ll after deletion: [A, A2, D, E, C, Z] ll after deleting first and last: [A2, D, E, C] ll after change: [A2, D, E Changed, C] 8. Write JAVA programs which uses FileInputStream/FileOutputStream Classes. a) FileinputStream /*FileInStreamDemo.java*/ import java.io.*; public class FileInStreamDemo { public static void main(String[] args) { // create file object File file = new File("DevFile.txt"); int ch; StringBuffer strContent = new StringBuffer(""); FileInputStream fin = null; try { fin = new FileInputStream(file); while ((ch = fin.read()) != -1) strContent.append((char) ch); fin.close(); } catch (FileNotFoundException e) {

System.out.println("File " + file.getAbsolutePath() + " could not be found on filesystem"); } catch (IOException ioe) { System.out.println("Exception while reading the file" + ioe); } System.out.println("File contents :"); System.out.println(strContent); } } OutPut: C:\New Folder>java FileInStreamDemo File contents : The text shown here will write to a file after run The FileInputStream class is a subclass of InputStream. An InputStream is a reference to source of data (be it a file, network connection etc).The FileInputStream class allows you to read binary data sequentially from a file. The FileInputStream class's constructors allow you to pass either a File object or a path to a file. b)FileoutputStream /* Example of FileOutputStream */ import java.io.*; public class FileOutStreamDemo { public static void main(String[] args) { FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object try { // Create a new file output stream connected to "DevFile.txt" out = new FileOutputStream("DevFile.txt"); // Connect print stream to the output stream p = new PrintStream(out); p.println("The text shown here will write to a file after run"); System.out.println("The Text is written to DevFile.txt"); p.close(); } catch (Exception e) { System.err.println("Error writing to file"); } } }

OutPut: C:\New Folder>java FileOutStreamDemo The Text is written to DevFile.txt


9. Write a JAVA Program which writes a object to a file (use transient variable also).

import java.util.Vector; import java.io.*; public class SerializationTest { static long start,end; OutputStream out = null; OutputStream outBuffer = null; ObjectOutputStream objectOut = null; public Person getObject() { Person p = new Person("SID","austin"); Vector v = new Vector(); for(int i=0;i<7000;i++) { v.addElement("StringObject:" +i); } p.setData(v); return p; } public static void main(String[] args) { SerializationTest st = new SerializationTest(); start = System.currentTimeMillis(); st.writeObject(); end = System.currentTimeMillis(); System.out.println("Time taken for writing :"+ (end-start) + "milli seconds"); } public void writeObject() { try { out = new FileOutputStream("c:/temp/test.txt"); outBuffer = new BufferedOutputStream(out); objectOut = new ObjectOutputStream(outBuffer); objectOut.writeObject(getObject()); } catch(Exception e){e.printStackTrace();} finally { if(objectOut != null) try {

objectOut.close();}catch(IOException e){e.printStackTrace(); } } } } class Person implements java.io.Serializable { private String name; private transient Vector data; private String address; public Person(String name,String address) { this.name = name; this.address = address; } public String getAddress() { return address; } public Vector getData() { return data; } public String getName() { return name; } public void setData(Vector data) { this.data = data; } }
Serilization is the process of making the object's state persistent. That means the state of the object is converted into stream of bytes and stored in a file. In the same way we can use the de-serilization concept to bring back the object's state from bytes. This is one of the important concept in Java programming because this serilization is mostly used in the networking programming. The object's which are needs to be transmitted through network has to be converted as bytes, for that purpose ever class or interface must implements Serilization interface. By default all the variables in the object is converted into the persistent. In some cases, you may want to avoid persisting some variables because you don't have the necesscity to persist those varibale. So, you can declare those variables as transient. if the variable is declared as transient, then it will not be persisted. It is the main purpose of the transient keyword. transient keyword indicates the following : The transient keyword is applicable to the member variables of a class. The transient keyword is used to indicate that the member variable should not be serialized when the class instance containing that transient variable is needed to be serialized.

When an instance variable is declared as transient, then its value need not persist when an object is stored. For example: class T { transient int a; // will not persist int b; // will persist } The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs. volatile variable does not have a copy maintained in the local memory of the thread (on the stack). All changes to the volatile variable (caused by multiple threads) are flushed out to the heap memory (visible from all threads). Hence volatile variable values remain consistent for all threads. On the other hand, for other instance variables, each java thread maintains a local copy on the stack. Multiple threads may modify this local copy of the instance variable and hence inconsistent values may be visible for multiple threads.

10. Write JAVA programs which uses Datagram Socket for Client Server Communication. // Demonstrate datagrams. import java.net.*; class WriteServer { public static int serverPort = 998; public static int clientPort = 999; public static int buffer_size = 1024; public static DatagramSocket ds; public static byte buffer[] = new byte[buffer_size]; public static void TheServer() throws Exception { int pos=0; while (true) { int c = System.in.read(); switch (c) { case -1: System.out.println("Server Quits."); return; case '\r': break; case '\n': ds.send(new DatagramPacket(buffer,pos, InetAddress.getLocalHost(),clientPort)); pos=0; break;

default: buffer[pos++] = (byte) c; } } } public static void TheClient() throws Exception { while(true) { DatagramPacket p = new DatagramPacket(buffer, buffer.length); ds.receive(p); System.out.println(new String(p.getData(), 0, p.getLength())); } } public static void main(String args[]) throws Exception { if(args.length == 1) { ds = new DatagramSocket(serverPort); TheServer(); } else { ds = new DatagramSocket(clientPort); TheClient(); } } } OutPut: TCP/IP-style networking is appropriate for most networking needs. It provides a serialized,predictable, reliable stream of packet data. This is not without its cost, however. TCP includes many complicated algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to a somewhat inefficient way to transport data. Datagrams provide an alternative. Datagrams are bundles of information passed between machines. They are somewhat like a hard throw from a well-trained but blindfolded catcher to the third baseman. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it. Likewise, when the datagram is received, there is no assurance that it hasnt been damaged in transit or that whoever sent it is still there to receive a response.Java implements datagrams on top of the UDP protocol by using two classes: the DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or receive the DatagramPackets.

11. Write JAVA programs which handles MouseEvent

// Demonstrate the mouse event handlers. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="MouseEvents" width=300 height=100> </applet> */ public class MouseEvents extends Applet implements MouseListener, MouseMotionListener { String msg = ""; int mouseX = 0, mouseY = 0; // coordinates of mouse public void init() { addMouseListener(this); addMouseMotionListener(this); } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse clicked."; repaint(); } // Handle mouse entered. public void mouseEntered(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse entered."; repaint(); } // Handle mouse exited. public void mouseExited(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse exited."; repaint(); } // Handle button pressed. public void mousePressed(MouseEvent me)

{ // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Down"; repaint(); } // Handle button released. public void mouseReleased(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Up"; repaint(); } // Handle mouse dragged. public void mouseDragged(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + ", " + mouseY); repaint(); } // Handle mouse moved. public void mouseMoved(MouseEvent me) { // show status showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } } 12. Write JAVA programs which handles keyboardEvent // Demonstrate the key event handlers. import java.awt.*; import java.awt.event.*; import java.applet.*;

/* <applet code="SimpleKey" width=300 height=100> </applet> */ public class SimpleKey extends Applet implements KeyListener { String msg = ""; int X = 10, Y = 20; // output coordinates public void init() { addKeyListener(this); } public void keyPressed(KeyEvent ke) { showStatus("Key Down"); } public void keyReleased(KeyEvent ke) { showStatus("Key Up"); } public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); } // Display keystrokes. public void paint(Graphics g) { g.drawString(msg, X, Y); } } 13. Write JAVA programs which implements RMI. //addserverintf.java import java.rmi.*; public interface addserverintf extends Remote { double add(double d1,double d2) throws RemoteException; } //addserverimpl.java import java.rmi.*; import java.rmi.server.*; public

class addserverimpl extends UnicastRemoteObject implements addserverintf { public addserverimpl() throws RemoteException { } public double add(double d1,double d2) throws RemoteException { return (d1+d2); } } //addserver.java import java.net.*; import java.rmi.*; public class addserver { public static void main(String args[]) { try { addserverimpl addsi = new addserverimpl(); Naming.rebind("addserver", addsi); } catch(Exception e) { System.out.println("Exception : " +e); } } } //addclient.java import java.rmi.*; public class addclient { public static void main(String args[]) { try { String addserverURL = "rmi://" +args[0]+ "/addserver"; addserverintf addsi = (addserverintf) Naming.lookup(addserverURL); System.out.println("the first number is " +args[1]); double d1 = Double.valueOf(args[1]).doubleValue(); System.out.println("the second number is " +args[2]); double d2 = Double.valueOf(args[2]).doubleValue();

System.out.println("The sum is " +addsi.add(d1,d2)); } catch(Exception e) { System.out.println("Exception : " +e); } } } The first file, AddServerIntf.java, defines the remote interface that is provided by the server. It contains one method that accepts two double arguments and returns their sum. All remote interfaces must extend the Remote interface, which is part of java.rmi. Remote defines no members. Its purpose is simply to indicate that an interface uses remote methods. All remote methods can throw a RemoteException. The second source file, AddServerImpl.java, implements the remote interface. The implementation of the add( ) method is straightforward. All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines. The third source file, AddServer.java, contains the main program for the server machine.Its primary function is to update the RMI registry on that machine. This is done by using therebind( ) method of the Naming class (found in java.rmi). That method associates a namewith an object reference. The first argument to the rebind( ) method is a string that names the server as AddServer. Its second argument is a reference to an instance of AddServerImpl. The fourth source file, AddClient.java, implements the client side of this distributed application. AddClient.java requires three command-line arguments. The first is the IP address or name of the server machine. The second and third arguments are the two numbers that are to be summed. The application begins by forming a string that follows the URL syntax. This URL uses the rmi protocol. The string includes the IP address or name of the server and the string AddServer. The program then invokes the lookup( ) method of the Naming class. This method accepts one argument, the rmi URL, and returns a reference to an object of type AddServerIntf. All remote method invocations can then be directed to this object. Execution procedure: 1. Compile all the above program. 2. Generate a Stub To generate a stub, we use a tool called the RMI compiler, which is invoked from the command line. rmic AddServerImpl 3. Start the RMI Registry on the Server Machine start rmiregistry 4. Start the Serv java AddServerer 5. Start the Client The Add Client software requires three arguments: the name or IP address of the server machine and the two numbers that are to be summed together. We may invoke it from the command line by using one of the two formats shown here: java Add Client server1 8 9

Java Add Client 11.12.13.14 8 9 java AddClient 127.0.0.1 8 9 Here, the address 127.0.0.1 is the loop back address for the local machine. Using this address allows you to exercise the entire RMI mechanism without actually having to install the server on a remote computer. 14. Write a swing Application which uses JTabbedPane i. Each Tab should use JPanel, which includes any one component given below in each Panel ii. ComboBox/List/Tree/RadioButton. // Demonstrate JTabbedPane. import java.awt.*; import javax.swing.event.*; import javax.swing.*; import javax.swing.tree.*; /* <applet code="JTabbedPaneDemo" width=700 height=200> </applet> */ public class JTabbedPaneDemo extends JApplet { public void init() { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { makeGUI(); } }); } catch (Exception exc) { System.out.println("Can't create because of " + exc); } } private void makeGUI() {

JTabbedPane jtp = new JTabbedPane(); jtp.addTab("Cities", new CitiesPanel()); jtp.addTab("Colors", new ColorsPanel()); jtp.addTab("Flavors", new FlavorsPanel()); jtp.addTab("Subjects", new SubjectsPanel()); jtp.addTab("Movies", new MoviePanel()); add(jtp); } } // Make the panels that will be added to the tabbed pane. class CitiesPanel extends JPanel { public CitiesPanel() { JButton b1 = new JButton("New York"); add(b1); JButton b2 = new JButton("London"); add(b2); JButton b3 = new JButton("Hong Kong"); add(b3); JButton b4 = new JButton("Tokyo"); add(b4); } } class ColorsPanel extends JPanel { public ColorsPanel() { JCheckBox cb1 = new JCheckBox("Red"); add(cb1); JCheckBox cb2 = new JCheckBox("Green"); add(cb2); JCheckBox cb3 = new JCheckBox("Blue"); add(cb3); } } class FlavorsPanel extends JPanel { public FlavorsPanel() { JComboBox jcb = new JComboBox(); jcb.addItem("Vanilla"); jcb.addItem("Chocolate"); jcb.addItem("Strawberry"); add(jcb); }

} class SubjectsPanel extends JPanel { public SubjectsPanel() { JTree tree; JLabel jlab; // Create top node of tree. DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options"); // Create subtree of "III Sem". DefaultMutableTreeNode a = new DefaultMutableTreeNode("III Sem"); top.add(a); DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("JAva"); a.add(a1); DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("SS"); a.add(a2); // Create subtree of "B". DefaultMutableTreeNode b = new DefaultMutableTreeNode("IV Sem"); top.add(b); DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("J2EE"); b.add(b1); DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("ADA"); b.add(b2); DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("WP"); b.add(b3); // Create the tree. tree = new JTree(top); // Add the tree to a scroll pane. JScrollPane jsp = new JScrollPane(tree); // Add the scroll pane to the content pane. add(jsp); } } class MoviePanel extends JPanel { public MoviePanel() { JList jlst; JLabel jlab; JScrollPane jscrlp; // Create an array of cities. String Cities[] = { "New York", "Chicago", "Houston", "Denver", "Los Angeles", "Seattle", "London", "Paris", "New Delhi", "Hong Kong", "Tokyo", "Sydney" };

// Create a JList. jlst = new JList(Cities); // Set the list selection mode to single selection. jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); add(jlst); } }

Vous aimerez peut-être aussi