50
LABORATORY MANUAL CS2309 JAVA LAB THIRD YEAR V SEM DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

96680522-Java-Lab

  • Upload
    prasad

  • View
    28

  • Download
    3

Embed Size (px)

Citation preview

Page 1: 96680522-Java-Lab

LABORATORY MANUAL

CS2309 JAVA LAB

THIRD YEAR – V SEM

DEPARTMENT OF COMPUTER SCIENCE &

ENGINEERING

Page 2: 96680522-Java-Lab

EX NO:1.1) EFFICIENT REPRESENTATION FOR RATIONAL

NUMBER DATE:

AIM To write a JAVA program for finding simplified form of the given rational number.

ALGORITHM

1. Import java.util and java.io package. 2. Define Rational class with required variables .

3. Get the numerator and denominator values. 4. Using the object of the Rational class call the method efficientrep().

5. If the numerator is greater than the denominator then i). Return the input as it is.

Else i). Find the Rational value.

ii). Return (numerator+"/"+denominator).

6. Display the Simplified form of rational number on screen like numerator/denominator.

REVIEW QUESTIONS

1. What is Bytecode? Each java program is converted into one or more class files. The content of the class

file is a set of instructions called bytecode to be executed by Java Virtual

Machine

(JVM).Java introduces bytecode to create platform independent program.

2. What is JVM? JVM is an interpreter for bytecode which accepts java bytecode and produces result.

3. How many JVMs can run on a single machine?

No limitation. A JVM is just like any other process.

4. What is the use of StringTokenizer class? The class allows an application to break a string into tokens.

5. Differentiate java from C++.

Java doesn‟t support pointers.

Java doesn‟t provide operator overloading option for programmers though

it internally use it for string concatenation.

Java doesn‟t support multiple class inheritance. However, it supports multiple inheritance using interface.

Java doesn‟t global variables, global functions, typedef, structures or unions.

Java uses final keyword to avoid a class or method to be overridden.

6. What are the three different types of comments in

java?

Java comments make your code easy to understand, modify

and use. Java supports

three different types of comment styles.

1. Every thing between initial slash –asterisk and ending asterisk-slash is ignored by

the java compiler.(/*……*/)

2. Double slash (//)mark is ignored by java compiler.

3. Every thing between initial slash – asterisk - asterisk and ending asterisk-slash is

Page 3: 96680522-Java-Lab

ignored by the java compiler and another program called JAVADOC.EXE that

ships with the JDK uses these comments to construct HTML documentation files

that describe your packages, classes and methods as well as all the variables used.

(/**……*/)

PROGRAM

rational_main.java import java.util.Scanner; class rational_main { /** Class that contains the main function * @author Vivek Venkatesh (Your name) */ public static void main(String args[]) { /** Create an instance of "rational" class * to call the function in it. */ rational x = new rational(); //To get input from user Scanner s = new Scanner(System.in); int a,b; System.out.println("\n Enter the Numerator and Denominator:"); a = s.nextInt(); b = s.nextInt(); x.efficient_rep(a,b); } } rational.java public class rational { /** Rational number class * To give an efficient representation of user's input rational number * For ex: 500/1000 to be displayed as 1/2 */ public void efficient_rep(int a, int b) { int x=b; if(a=2;i--) { if(a%i==0 && b%i==0) { a=a/i; b=b/i; } } System.out.println(a + "/" + b); } }

RESULT Thus the java program for finding simplified form of the given rational number was compiled and executed successfully.

Page 4: 96680522-Java-Lab

EX NO:1.2) FIBONACCI

SERIES DATE:

AIM To write a JAVA program for finding first N Fibonacci numbers.

ALGORITHM 1. import java.io package.

2. Length of Fibonacci series „N‟ must be got as a keyboard input by using

InputStreamReader class.

BufferedReader br=new BufferedReader(new InputStreamReader(System.in))

3. Convert the input into an integer using parseInt( ) method which is available in Integer

class.

4. Declare two integer data type variables F1 & F2 and assign values as F1=-1 & F2=1.

5. FOR i=1 to N do the following

FIB= F1 + F2

F1 = F2 F2 =FIB PRINT FIB

END FOR

6. Stop the Program.

REVIEW

QUESTIONS

1. What is class?

A class is a blueprint or prototype from which objects are created. We can create any number of objects for the same class.

2. What is object?

Object is an instance of class. Object is real world entity which has state, identity and behavior.

3. What are different types of access modifiers?

public: Anything declared as public can be accessed from

anywhere.

private: Anything declared as private can‟t be seen outside of its class.

protected: Anything declared as protected can be accessed by classes in the

same package and subclasses in the other packages.

default modifier : Can be accessed only to classes in the same package.

4. What is encapsulation? Encapsulation is the mechanism that binds together code and the data it manipulates,

and keeps both safe from outside interference and misuse.

5. What is data hiding? Implementation details of methods are hidden from the user.

6. Define DataInputStream & DataOutputStream.

DataInputStream is used to read java primitive datatypes directly from the stream.

DataOutputStream is used to write the java primitive datatypes directly to the

stream.

Page 5: 96680522-Java-Lab

PROGRAM import java.io.*;

import javax.swing.JOptionPane;

class fibb

{

public static void main(String[] args)throws IOException

{

int[] fib=new int[100];

fib[0]=0;

fib[1]=1;

int num;

int i;

num=Integer.parseInt(JOptionPane.showInputDialog("Enter Number:"));

if(num>1)

{

for(i=2;i<=num;i++)

{

fib[i]=fib[i-1]+fib[i-2];

}

}

String str="";

for(i=0;i<num;i++)

str=str + " " +fib[i];

JOptionPane.showMessageDialog(null, str);

}

}

RESULT

Thus the java program for finding first N Fibonacci numbers was compiled and

executed successfully.

Page 6: 96680522-Java-Lab

EX NO:1.3) PRIME NUMBER

CHECKING DATE:

AIM

To write a JAVA program that reads an array of N integers and print whether each one is

prime or not.

ALGORITHM In main method do the following

1. Read N integers from keyboard and store it in an array a. Here N is the number of

entries in an array.

2. FOR i=1 to N do the following

IF IsPrime(a[i]) is TRUE then

Print a[i] is Prime

ELSE Print a[i] is not Prime

END IF

END FOR

Method IsPrime is returns Boolean value. If it is Prime then return true otherwise return false.

1. FOR i=2 to N/2

IF N is divisible by i return FALSE

ELSE CONTINUE FOR loop

END IF

END FOR

return TRUE

REVIEW QUESTIONS

1. What is casting?

Casting is used to convert the value of one data type to another.

2. What is a package? A package is a collection of classes and interfaces that provides a high-level layer of

access protection and name space management.

3. What is the use of „classpath‟ environment variable? Classpath is the list of directories through which the JVM will search to find a class.

4. Why does the main method need a static identifier?

Because static methods and members don‟t need an instance of their class to invoke

them and main is the first method which is invoked.

Page 7: 96680522-Java-Lab

5. What is the difference between constructor and method? Constructor will be automatically invoked when an object is created whereas method

has to be called explicitly.

PROGRAM import java.util.Scanner;

/**

* Simple Java program to print prime numbers from 1 to 100 or any number.

* A prime number is a number which is greater than 1 and divisible

* by either 1 or itself.

*/ public class PrimeNumberExample {

public static void main(String args[]) {

//get input till which prime number to be printed

System.out.println("Enter the number till which prime number to be printed: ");

int limit = new Scanner(System.in).nextInt();

//printing primer numbers till the limit ( 1 to 100)

System.out.println("Printing prime number from 1 to " + limit);

for(int number = 2; number<=limit; number++){

//print prime numbers only

if(isPrime(number)){

System.out.println(number);

}

}

}

/*

* Prime number is not divisible by any number other than 1 and itself

* @return true if number is prime

*/

public static boolean isPrime(int number){

for(int i=2; i<number; i++){

if(number%i == 0){

return false; //number is divisible so its not prime

}

}

return true; //number is prime now

}

}

RESULT

Thus the java program for checking prime number was compiled and executed successfully.

Page 8: 96680522-Java-Lab

EX NO:2) LEAP YEAR

CALCULATION DATE:

AIM

To write a JAVA program for finding whether the given year is a leap year or not.

ALGORITHM

1. Import java.util package.

2. Inside the class Date,define the methods isvalid(),isleapyear(),compareto().

3. The method isvalid() is used to check the form of the date,month,year .

4. The method isleapyear() is a Boolean methods it return true when the given year is a

leap year otherwise it return false.

5. The method compareto() compares the value of the object with that of date.return 0 if

the values are equal.Returns a negative value if the invoking object is earlier than

date.Returns a positive value if the invoking object is later than date.

6. Inside the main() method we perform the leap year calculation.

7. Stop the program.

REVIEW

QUESTIONS

7. What is class? A class is a blueprint or prototype from which objects are created. We can create any

number of objects for the same class.

8. What is object?

Object is an instance of class. Object is real world entity which has state, identity and

behavior.

9. What are different types of access modifiers?

public: Anything declared as public can be accessed from anywhere.

private: Anything declared as private can‟t be seen outside of its class.

protected: Anything declared as protected can be accessed by classes in the same package and subclasses in the other packages.

default modifier : Can be accessed only to classes in the same package.

10. What is encapsulation?

Encapsulation is the mechanism that binds together code and the data it manipulates,

and keeps both safe from outside interference and misuse.

11. What is data hiding?

Implementation details of methods are hidden from the user.

Page 9: 96680522-Java-Lab

12. Define DataInputStream & DataOutputStream.

DataInputStream is used to read java primitive datatypes directly from the stream.

DataOutputStream is used to write the java primitive datatypes directly to the

stream.

PROGRAM

import java.util.*;

import java.io.*;

public class LeapYear{

public static void main(String[] args) throws IOException{

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter year to check for leap year : ");

int year;

try{

year = Integer.parseInt(in.readLine());

if(year < 1900 || year > 2100){

System.out.print("Please enter a year less than 2101 and greater than

1899.");

System.exit(0);

}

GregorianCalendar cal = new GregorianCalendar();

if(cal.isLeapYear(year))

System.out.print("Given year is leap year.");

else

System.out.print("Given year is not leap year.");

}

catch(NumberFormatException ne){

System.out.print(ne.getMessage() + " is not a legal entry.");

System.out.println("Please enter a 4-digit number.");

System.exit(0);

}

}

}

RESULT

Thus the java program for finding whether the given year is leap or not was compiled

and executed successfully.

Page 10: 96680522-Java-Lab

EX NO:3) LISP

IMPLEMENTATION DATE:

AIM

To write a JAVA program to implement basic operations of

LISP.

ALGORITHM

1. LinkedList class can be accessed by importing java.util package.

2. Create a class LISPList with the basic operations of LISP List such as „cons‟, „car‟, „cdr‟ .

3. Define the LISPList class with an array of string and three methods.

Void cons( )

String car( )

String cdr( )

4. cons() method used to append item to the list at first location. List.addFirst(String item)

5. car() method is used to view the first item in the list. PRINT List.getFirst()

6. cdr() method is used to view the part of the list that follows the first item.

REVIEW QUESTIONS 1. How this() method used with constructors?

this() method within a constructor is used to invoke another constructor in the same

class.

2. How super() method used with constructors?

super() method within a constructor is used to invoke its immediate superclass constructor.

3. What is reflection in java? Reflection is the ability of a program to analyze itself. The java.lang.reflect package

provides the ability to obtain information about the fields, constructors, methods,

and modifiers of a class.

.

4. What is Exceptions in java? An exception is an abnormal condition that arises in a code sequence at run time. In

other words, an exception is a run-time error. All exception types are subclasses of the

built- in class Throwable.

5. What is Error? This class describes internal errors, such as out of disk space etc...The user can only

be informed about such errors and so objects of these cannot be thrown

Exceptions.

6. What is the List interface? The List interface extends Collection and declares the behavior of a collection that stores a

Page 11: 96680522-Java-Lab

sequence of elements. Elements can be inserted or accessed by their position in the list,

using a zero-based index. A list may contain duplicate elements.

7. What is the LinkedList class?

The LinkedList class extends AbstractSequentialList and implements the

List interface. It provides a linked-list data structure. LinkedList class defines some

useful methods of its own for manipulating and accessing lists. void addFirst(Object obj)

void addLast(Object obj) Object getFirst( )

Object getLast( )

Object removeFirst(

) Object removeLast(

)

8. What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer

needed by a program so that their resources can be reclaimed and reused. A Java object

is subject to garbage collection when it becomes unreachable to the program in which

it is used.

PROGRAM import java.util.*;

// To implement LISP-like List in Java to perform functions like car, cdr, cons.

class Lisp

{

public Vector car(Vector v)

{

Vector t = new Vector();

t.addElement(v.elementAt(0));

return t;

}

public Vector cdr(Vector v)

{

Vector t = new Vector();

for(int i=1;i

t.addElement(v.elementAt(i));

return t;

}

public Vector cons(String x, Vector v)

{

v.insertElementAt(x,0);

return v;

Page 12: 96680522-Java-Lab

}

public Vector cons(int x, Vector v)

{

v.insertElementAt(x,0);

return v;

}

}

class Lisp_List2

{

public static void main(String[] args)

{

Lisp a = new Lisp();

Vector v = new Vector(4,1);

Vector v1 = new Vector();

System.out.println("\n Creating a List of Strings....\n");

v.addElement("S.R.Tendulkar");

v.addElement("M.S.Dhoni");

v.addElement("V.Sehwag");

v.addElement("S.Raina");

System.out.println("\n The Contents of the List are " + v);

System.out.print("\n The CAR of this List....");

System.out.println(a.car(v));

System.out.print("\n The CDR of this List....");

v1 = a.cdr(v);

System.out.println(v1);

System.out.println("\n The Contents of this list after CONS..");

v1 = a.cons("Gambhir",v);

System.out.print(" " + v1);

v.removeAllElements();

v1.removeAllElements();

System.out.println("\n\n Creating a List of Integers....\n");

v.addElement(3);

v.addElement(0);

v.addElement(2);

v.addElement(5);

System.out.println("\n The Contents of the List are " + v);

Page 13: 96680522-Java-Lab

System.out.print("\n The CAR of this List....");

System.out.println(a.car(v));

System.out.print("\n The CDR of this List....");

v1 = a.cdr(v);

System.out.println(v1);

System.out.println("\n The Contents of this list after CONS..");

v1 = a.cons(9,v);

System.out.print(" " + v1);

}

}

Output

Creating a List of Strings....

The Contents of the List are [S.R.Tendulkar, M.S.Dhoni, V.Sehwag, S.Raina]

The CAR of this List....[S.R.Tendulkar]

The CDR of this List....[M.S.Dhoni, V.Sehwag, S.Raina]

The Contents of this list after CONS..

[Gambhir, S.R.Tendulkar, M.S.Dhoni, V.Sehwag, S.Raina]

Creating a List of Integers....

The Contents of the List are [3, 0, 2, 5]

The CAR of this List....[3]

The CDR of this List....[0, 2, 5]

The Contents of this list after CONS..

[9, 3, 0, 2, 5]

RESULT

Thus the java program for implementing the basic operations of LISP was compiled and executed successfully.

Page 14: 96680522-Java-Lab

EX NO:4) POLYMORPHISM - METHOD

OVERLOADING DATE:

AIM

To write a JAVA program to design a Vehicle class hierarchy and a test program to

demonstrate polymorphism concept.

ALGORITHM

1. Define a superclass vehicle with three private integer data members ( speed,color, wheel).

2. Define a function disp() to display the details about vehicle.

3. Define a constructor to initialize the data member cadence, speed and gear.

4. Define a subclass bus which extends superclass vehicle.

5. Overridden disp() method in vehicle class. Additional data about the suspension is

included to the output. 6. Define a subclass train which extends superclass vehicle.

7. There are three classes: bus, train, and car The three subclasses override the disp method and print unique information.

8. Define a sample class program that creates three vehicle variables. Each variable is assigned to one of the three vehicle classes. Each variable is then printed.

REVIEW QUESTIONS

1. What is polymorphism? Polymorphism means the ability to take more than one form. Subclasses of a class

can define their own unique behaviors and yet share some of the same functionality of

the parent class.

2. What is overloading?

Same method name can be used with different type and number of arguments (in same

class)

3. What is overriding?

Same method name, similar arguments and same number of arguments can be defined in super class and sub class. Sub class methods override the super class methods.

4. What is the difference between overloading and overriding?

Overloading related to same class and overriding related sub-super class

Compile time polymorphism achieved through overloading, run time polymorphism

achieved through overriding.

5. What is hierarchy? Ordering of classes (or inheritance)

PROGRAM

import java.util.*;

abstract class Vehicle

{

boolean engstatus=false;

abstract void start();

Page 15: 96680522-Java-Lab

abstract void moveForward();

abstract void moveBackward();

abstract void applyBrake();

abstract void turnLeft();

abstract void turnRight();

abstract void stop();

}

class Porsche extends Vehicle

{

void truckManufacture()

{

System.out.println("Porsche World Wide Car manufactures ");

}

void gearSystem()

{

System.out.println("\n automatic gearing system.. So don't worry !!");

}

void start()

{

engstatus=true;

System.out.println("\n engine is ON ");

}

void moveForward()

{

if(engstatus==true)

System.out.println("\nCar is moving in forward direction .. Slowly gathering speed ");

else

System.out.println("\n Car is off...Start engine to move");

}

void moveBackward()

{ if(engstatus=true)

System.out.println("\n Car is moving in reverse direction ...");

else

System.out.println("\n Car is off...Start engine to move");

}

void applyBrake()

{

System.out.println("\n Speed is decreasing gradually");

}

void turnLeft()

{

System.out.println("\n Taking a left turn.. Look in the mirror and turn ");

}

void turnRight()

{

System.out.println("\n Taking a right turn.. Look in the mirror and turn ");

}

void stop()

{

engstatus=false;

System.out.println("\n Car is off ");

}

}

Page 16: 96680522-Java-Lab

class Volvo extends Vehicle

{

void truckManufacture()

{

System.out.println("Volvo Truck Manufactures");

}

void gearSystem()

{

System.out.println("\nManual Gear system...ooops....take care while driving ") ;

}

void start()

{

engstatus=true;

System.out.println("\n engine is ON ");

}

void moveForward()

{

if(engstatus==true)

System.out.println("\n truck is moving in forward direction .. Slowly gathering speed ");

else

System.out.println("\n truck is off...Start engine to move");

}

void moveBackward()

{ if(engstatus=true)

System.out.println("\n truck is moving in reverse direction ...");

else

System.out.println("\n truck is off...Start engine to move");

}

void applyBrake()

{

System.out.println("\n Speed is decreasing gradually");

}

void turnLeft()

{

System.out.println("\n Taking a left turn.. Look in the mirror and turn ");

}

void turnRight()

{

System.out.println("\n Taking a right turn.. Look in the mirror and turn ");

}

void stop()

{

engstatus=false;

System.out.println("\n Truck is off ");

}

}

class Vehicle1

{

public static void main(String[] args)

{

Porsche v1=new Porsche();

v1.truckManufacture();

v1.start();

Page 17: 96680522-Java-Lab

v1.gearSystem();

v1.moveForward();

v1.applyBrake();

v1.turnLeft();

v1.moveForward();

v1.applyBrake();

v1.turnRight();

v1.moveBackward();

v1.stop();

v1.moveForward();

Volvo v2= new Volvo();

v2.truckManufacture();

v2.start();

v2.gearSystem();

v2.moveForward();

v2.applyBrake();

v2.turnLeft();

v2.moveForward();

v2.applyBrake();

v2.turnRight();

v2.moveBackward();

v2.stop();

v2.moveForward();

}

}

RESULT Thus the java program for design a Vehicle class hierarchy was compiled and executed

successfully.

Page 18: 96680522-Java-Lab

NO:5) STACK IMPLEMENTATION USING ARRAY AND LINKED LIST

DATE:

AIM

To write a JAVA program to implement stack using array and linked list.

ALGORITHM Interface: StackADT

1. Create a StackADT interface with basic stack operations.

Void PUSH(int) & int POP( )

Class: StackArray

1. Create a class StackArray which implements StackAdt using Array.

2. Define the StackArray class with two integer variables(top & size) and one integer array.

3. Initialize the variable top =-1. It indicates that the stack is empty.

4. PUSH method read the element and push it into stack.

Void PUSH(data type

element) IF top==size

THEN

Print Stack Full

ELSE top++

stack[top]=element

END IF

5. POP method return the data

popped. Data type POP()

IF top==-1

Print Stack is Empty

ELSE return stack[top--]

Class: StackLinkedlist

END IF

1. LinkedList class can be accessed by importing java.util package. 2. Create a class StackLinkedlist which implements StackADT interface.

3. addFirst() method in LinkedList class used to push element in the stack. 4. removeFirst() method in LinkedList class used for deleting an element from stack.

REVIEW QUESTIONS

1. What is Inheritance? Inheritance is the process by which one object acquires the properties of another

object. This is important because it supports the concept of hierarchical classification.

2. Why inheritance is important? Reusability is achieved through inheritance.

3. Which types of inheritances are available in Java?

Simple, Hierarchical and Multilevel

Page 19: 96680522-Java-Lab

4. Can we achieve multiple inheritances in Java? With the help of interfaces we can achieve multiple inheritances.

5. What is interface? Interface is a collection of methods declaration and constants that one or more classes of

object will use.

All methods in an interface are implicitly abstract.

All variables are final and static.

Methods should not be declared as static, final, private and protected.

PROGRAM

Stack Interface

package datastruct;

public interface Stack {

void push(Object a);

Object pop();

boolean isEmpty();

void makeEmpty();

int size();

}

Node

Node is the important part of stack implementation. Node holds the information about the element and connected node. package datastruct;

public class Node {

//element where the object is stored

private Object element;

//represents the next node

private Node next;

//Constructors

public Node(){

this(null, null);

}

/**

* Node which stores the given Object

* and next node information

* @param element

* @param next

*/

public Node(Object element, Node next){

this.element = element;

this.next = next;

Page 20: 96680522-Java-Lab

}

//returns the Object containing in it.

public Object getElement(){

return element;

}

/**

* returns the information of previous node.

* @return

*/

public Node getNode(){

return next;

}

/**

* Update the value of Node

* @param obj

*/

public void setElement(Object obj){

this.element = obj;

}

/**

* Update the value of previous node.

* @param node

*/

public void setNode(Node node){

this.next = node;

}

}

Implementation of Stack

package datastruct;

/**

* This example is implementation of Stack using singly Linked List.

* @author jegan

*

*/

public class LinkedStack implements Stack {

private Node top;

private int size;

/**

* Checks weather the Stack is empty or not

*/

@Override

public boolean isEmpty() {

//if value of size is zero then stack is empty.

return (size == 0);

}

/**

* Makes the Stack empty

*/

@Override

Page 21: 96680522-Java-Lab

public void makeEmpty() {

//make reference of top to null and makes size to zero.

top = null;

size =0;

}

/*

* pops the element in the top of stack.

*/

@Override

public Object pop() {

//if top element is null returns null

if (top == null)

return null; //TO-DO throw new StackEmptyException

//returns the top element in stack

//and set node to previous one.

Object val = top.getElement();

top = top.getNode();

size -= 1;

return val;

}

/**

* insert new element into the Stack

*/

@Override

public void push(Object obj) {

//Creates the new Node and inserts into stack.

Node v = new Node(obj, top);

size += 1;

top = v;

}

/**

* returns the size of the Stack.

*/

@Override

public int size() {

return size;

}

}

RESULT Thus the java program for implementing stack using array and linked list was compiled and

executed successfully.

Page 22: 96680522-Java-Lab

EX NO:6) CURRENCY CONVERSION

DATE:

AIM To write a JAVA program that randomly generates one number which is stored in a file then

read the dollar value from the file and converts to rupee.

ALGORITHM

1. Random numbers in java can be generated either by using the Random class in

java.util package or by using the random() method in the Math class in java.

2. Using the random() method in Math class

double randomValue =

Math.random();

Using the Random

class

import java.util.Random;

Random random = new Random();

Int

randomValue=random.nextInt();

3. Write the generated random number in a file using FileWriter stream.

BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));

out.write(randomValue);

out.close(); 4. Read the data from the file using FileReader stream.

BufferedReader in = new BufferedReader(new FileReader("test.txt")); String line = in.readLine();

Int dollar = Integer.parseInt(line); 5. Convert the dollar value into rupee by equation and display it on screen.

REVIEW QUESTIONS

1. Define Stream

Stream produces and consumes information. It is the communication path between the source and the destination .It is the ordered sequence of data shared by IO devices.

2. List out the types of stream.

Byte Stream

Character Stream

3. Differentiate between byte stream & character stream?

Byte stream Character stream

A byte stream class provides support for handling I/O operations on bytes.

Byte stream classes are

InputStream and OutputStream.

It provides support for managing I/O operations on characters.

Reader and Writer classes are

character stream classes.

Page 23: 96680522-Java-Lab

4. What is the use of output streams?

It is used to perform input and output operations on objects using the object streams.

It is used to declare records as objects and use the objects classes to write and read these objects from files.

5. What is Random class?

The Random class is a generator of pseudorandom numbers. Random( ) creates a

number generator that uses the current time as the starting, or seed, value. Integers can

be extracted via the nextInt( ) method. PROGRAM

SerializationWrite.java import java.io.*; import java.util.*; class Currency implements Serializable { protected String currency; protected int amount; public Currency(String cur, int amt) { this.currency = cur; this.amount = amt; } public String toString() { return currency + amount; } public String dollarToRupee(int amt) { return "Rs" + amt * 45; } } class Rupee extends Currency { public Rupee(int amt) { super("Rs",amt); } } class Dollar extends Currency { public Dollar(int amt) { super("$",amt); } } public class SerializationWrite { public static void main(String args[]) { Random r = new Random(); try { Currency currency; FileOutputStream fos = new FileOutputStream("serial.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); System.out.println("Writing to file using Object Serialization:"); for(int i=1;i<=25;i++) { Object[] obj = { new Rupee(r.nextInt(5000)),new Dollar(r.nextInt(5000)) }; currency = (Currency)obj[r.nextInt(2)]; // RANDOM Objects for Rs and $ System.out.println(currency); oos.writeObject(currency); oos.flush(); } oos.close(); }

Page 24: 96680522-Java-Lab

catch(Exception e) { System.out.println("Exception during Serialization: " + e); } } } SerializationRead.java import java.io.*; import java.util.*; public class SerializationRead { public static void main(String args[]) { try { Currency obj; FileInputStream fis = new FileInputStream("serial.txt"); ObjectInputStream ois = new ObjectInputStream(fis); System.out.println("Reading from file using Object Serialization:"); for(int i=1;i<=25;i++) { obj = (Currency)ois.readObject(); if((obj.currency).equals("$")) System.out.println(obj + " = " + obj.dollarToRupee(obj.amount)); else System.out.println(obj + " = " + obj); } ois.close(); } catch(Exception e) { System.out.println("Exception during deserialization." + e); } } } Output vivek@ubuntu:~/Desktop$ javac SerializationWrite.java vivek@ubuntu:~/Desktop$ java SerializationWrite Writing to file using Object Serialization: $4645 Rs105 $2497 $892 Rs1053 Rs1270 $1991 Rs4923 Rs4443 Rs3537 Rs2914 $53 $561 $4692 Rs860 $2764 Rs752 $1629 $2880 Rs2358 Rs3561 $3796 Rs341 Rs2010 Rs427 vivek@ubuntu:~/Desktop$ javac SerializationRead.java vivek@ubuntu:~/Desktop$ java SerializationRead

Page 25: 96680522-Java-Lab

Reading from file using Object Serialization: $4645 = Rs209025 Rs105 = Rs105 $2497 = Rs112365 $892 = Rs40140 Rs1053 = Rs1053 Rs1270 = Rs1270 $1991 = Rs89595 Rs4923 = Rs4923 Rs4443 = Rs4443 Rs3537 = Rs3537 Rs2914 = Rs2914 $53 = Rs2385 $561 = Rs25245 $4692 = Rs211140 Rs860 = Rs860 $2764 = Rs124380 Rs752 = Rs752 $1629 = Rs73305 $2880 = Rs129600 Rs2358 = Rs2358 Rs3561 = Rs3561 $3796 = Rs170820 Rs341 = Rs341 Rs2010 = Rs2010 Rs427 = Rs427

RESULT

Thus the java program for currency conversion was compiled and executed successfully.

Page 26: 96680522-Java-Lab

EX NO:7) MUTLITHREADING

DATE:

AIM

To write a JAVA program to print all numbers below 100,000 that are both prime and

Fibonacci number.

ALGORITHM

For creating a thread a class has to extend the Thread Class. For creating a thread by

this procedure you have to follow these steps:

1. Extend the java.lang.Thread Class.

2. Override the run( ) method in the subclass from the Thread class to define the

code executed by the thread. 3. Create an instance of this subclass. This subclass may call a Thread class constructor by

subclass constructor. 4. Invoke the start( ) method on the instance of the class to make the thread eligible for

running.

The procedure for creating threads by implementing the Runnable Interface is as follows:

1. A Class implements the Runnable Interface, override the run() method to define the

code executed by thread. An object of this class is Runnable Object.

2. Create an object of Thread Class by passing a Runnable object as argument.

3. Invoke the start( ) method on the instance of the Thread class.

Like creation of a single thread, create more than one thread (multithreads) in a program using class Thread or implementing interface Runnable.

REVIEW QUESTIONS

1. What is thread? Thread is similar to a program that has single flow of control. Each thread has

separate path for execution.

2. What is multithreading? Simultaneous execution of threads is called

multithreading.

3. What are the advantages of Multithreading over multitasking?

Reduces the computation time

Improves performance of an application

Threads share the same address space so it saves the memory.

Cost of communication between is relatively low.

4. How to create thread?

By creating instance of Thread class or implementing Runnable interface.

Page 27: 96680522-Java-Lab

5. List out methods of Thread class? currentThread( ), setName( ), getName( ), setPriority( ), getPriority( ), join( ), isAlive( )

6. What is join( ) method of Thread? Combines two or more threads running process and wait till their execution is

completed.

7. What are the states in Thread Life Cycle?

Ready, running, block, wait, dead.

PROGRAM import java.util.*; import java.io.*; class Fibonacci extends Thread { private PipedWriter out = new PipedWriter(); public PipedWriter getPipedWriter() { return out; } public void run() { Thread t = Thread.currentThread(); t.setName("Fibonacci"); System.out.println(t.getName() + " thread started"); int fibo1=0,fibo2=1,fibo=0; while(true) { try { fibo = fibo1 + fibo2; if(fibo>100000) { out.close(); break; } out.write(fibo); sleep(1000); } catch(Exception e) { System.out.println("Fibonacci:"+e); } fibo1=fibo2; fibo2=fibo; } System.out.println(t.getName() + " thread exiting"); } } class Prime extends Thread { private PipedWriter out1 = new PipedWriter(); public PipedWriter getPipedWriter() { return out1; } public void run() { Thread t= Thread.currentThread(); t.setName("Prime"); System.out.println(t.getName() + " thread Started..."); int prime=1; while(true) { try { if(prime>100000) { out1.close(); break;

Page 28: 96680522-Java-Lab

} if(isPrime(prime)) out1.write(prime); prime++; sleep(0); } catch(Exception e) { System.out.println(t.getName() + " thread exiting."); System.exit(0); } } } public boolean isPrime(int n) { int m=(int)Math.round(Math.sqrt(n)); if(n==1 || n==2) return true; for(int i=2;i<=m;i++) if(n%i==0) return false; return true; } } public class PipedIo { public static void main(String[] args) throws Exception { Thread t=Thread.currentThread(); t.setName("Main"); System.out.println(t.getName() + " thread Started..."); Fibonacci fibonacci = new Fibonacci(); Prime prime = new Prime(); PipedReader fpr = new PipedReader(fibonacci.getPipedWriter()); PipedReader ppr = new PipedReader(prime.getPipedWriter()); fibonacci.start(); prime.start(); int fib=fpr.read(), prm=ppr.read(); System.out.println("The numbers common to PRIME and FIBONACCI:"); while((fib!=-1) && (prm!=-1)) { while(prm<=fib) { if(fib==prm) System.out.println(prm); prm=ppr.read(); } fib=fpr.read(); } System.out.println(t.getName() + " thread exiting"); } }

RESULT

Thus the java program for creating multithread was compiled and executed successfully.

Page 29: 96680522-Java-Lab

EX NO:8) SCIENTIFIC CALCULATOR

DATE:

AIM

To design a scientific calculator using event driven programming paradigm of JAVA.

ALGORITHM 1. Import applet, awt and awt.event packages.

2. Create a class calculator which extends Applet and implements ActionListener.

3. Create object for TextFiled, List, Label and Button classes. Add all these objects to

the window using add(obj) method.

4. Use addActionerListener(obj) method to receive action event notification from

component.

When the button is pressed the generated event is passed to every EventListener objects

that receives such types of events using the addActionListener() method of the object.

5. Implement the ActionListener interface to process button events

using actionPerformed(ActionEvent obj) method.

6. Align the buttons in container by using Grid Layout.The format of grid layout

constructor is public GridLayout(int numRows, int NumColumns, int horz, int vert)

7. Set the layout for the window using setLayout(gridobj(row,column)) method.

REVIEW QUESTIONS

1. What is an applet?

Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.

2. What is the difference between applications and applets?

Application must be run on local machine whereas applet needs no explicit installation on local machine.

3. What is Abstract Windowing Toolkit (AWT)?

A library of java packages that forms part of java API, used to for GUI design.

4. What is a layout manager and what are different types of layout managers available

in java AWT? A layout manager is an object that is used to organize components in a

container. The different layouts are available are

FlowLayout

BorderLayout

CardLayout

GridLayout and GridBagLayout.

5. Which package is required to write GUI (Graphical User Interface) programs? Java.awt

6. What is event listener? A listener is an object that is notified when an event occurs. The methods that

receive and process events are defined in a set of interfaces found in java.awt.event.

For example, the MouseMotionListener interface defines two methods to receive

notifications when the mouse is dragged or moved.

Page 30: 96680522-Java-Lab

PROGRAM // Initial Declarations import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; // Creating a class named Calculator class Calculator { // Components that are required to create the Calculator JFrame frame = new JFrame(); // Creating the Menu Bar JMenuBar menubar = new JMenuBar(); //---> Creating the "Calculator-->Exit" Menu JMenu firstmenu = new JMenu("Calculator"); JMenuItem exitmenu = new JMenuItem("Exit"); // Creating The TextArea that gets the value JTextField editor = new JTextField(); JRadioButton degree = new JRadioButton("Degree"); JRadioButton radians = new JRadioButton("Radians"); String[] buttons = {"BKSP","CLR","sin","cos","tan","7","8","9","/","+/-","4","5","6","X","x^2","1","2","3","-","1/x","0",".","=","+","sqrt"}; JButton[] jbuttons = new JButton[26]; double buf=0,result; boolean opclicked=false,firsttime=true; String last_op; // Creating a Constructor to Initialize the Calculator Window public Calculator() { frame.setSize(372,270); frame.setTitle("Calculator - By G.Vivek Venkatesh."); frame.setLayout(new BorderLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); ButtonHandler bhandler = new ButtonHandler(); menubar.add(firstmenu); firstmenu.add(exitmenu); exitmenu.setActionCommand("mExit"); exitmenu.addActionListener(bhandler); editor.setPreferredSize(new Dimension(20,50)); Container buttoncontainer = new Container(); buttoncontainer.setLayout(new GridLayout(5,5)); for(int i=0;i { jbuttons[i] = new JButton(buttons[i]); jbuttons[i].setActionCommand(buttons[i]); jbuttons[i].addActionListener(bhandler); buttoncontainer.add(jbuttons[i]); } JPanel degrad = new JPanel(); degrad.setLayout(new FlowLayout()); ButtonGroup bg1 = new ButtonGroup(); bg1.add(degree); bg1.add(radians); degrad.add(degree); radians.setSelected(true); degrad.add(radians); frame.setJMenuBar(menubar);

Page 31: 96680522-Java-Lab

frame.add(editor,BorderLayout.NORTH); frame.add(degrad,BorderLayout.CENTER); frame.add(buttoncontainer,BorderLayout.SOUTH); frame.setVisible(true); } // Class that handles the Events (that implements ActionListener) public class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { String action = e.getActionCommand(); if(action == "0" || action=="1" || action=="2" || action=="3" || action=="4" || action=="5" || action=="6" || action=="7" || action=="8" || action=="9" || action==".") { if(opclicked == false) editor.setText(editor.getText() + action); else { editor.setText(action); opclicked = false; } } if(action == "CLR") { editor.setText(""); buf=0; result=0; opclicked=false; firsttime=true; last_op=null; } //Addition if(action=="+") { firsttime = false; if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" && last_op!="x^2" && last_op!="+/-") { buf = buf + Double.parseDouble(editor.getText()); editor.setText(Double.toString(buf)); last_op = "+"; opclicked=true; } else { opclicked=true; last_op = "+"; } } // Subtraction if(action=="-") { if(firsttime==true) { buf = Double.parseDouble(editor.getText()); firsttime = false; opclicked=true; last_op = "-"; } else { if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" && last_op!="x^2" && last_op!="+/-") { buf = buf - Double.parseDouble(editor.getText()); editor.setText(Double.toString(buf)); last_op = "-"; opclicked=true; } else { opclicked=true; last_op = "-"; } } }

Page 32: 96680522-Java-Lab

//Multiplication if(action=="X") { if(firsttime==true) { buf = Double.parseDouble(editor.getText()); firsttime = false; opclicked = true; last_op = "X"; } else { if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" && last_op!="x^2" && last_op!="+/-") { buf = buf * Double.parseDouble(editor.getText()); editor.setText(Double.toString(buf)); last_op = "X"; opclicked=true; } else { opclicked=true; last_op = "X"; } } } //Division if(action=="/") { if(firsttime==true) { buf = Double.parseDouble(editor.getText()); firsttime = false; opclicked=true; last_op = "/"; } else { if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" && last_op!="x^2" && last_op!="+/-") { buf = buf / Double.parseDouble(editor.getText()); editor.setText(Double.toString(buf)); last_op = "/"; opclicked=true; } else { opclicked=true; last_op = "/"; } } } // Equal to if(action=="=") { result = buf; if(last_op=="+") { result = buf + Double.parseDouble(editor.getText()); buf = result; } if(last_op=="-") { result = buf - Double.parseDouble(editor.getText()); buf = result; } if(last_op=="X") { result = buf * Double.parseDouble(editor.getText()); buf = result; } if(last_op=="/") { try { result = buf / Double.parseDouble(editor.getText());

Page 33: 96680522-Java-Lab

} catch(Exception ex) { editor.setText("Math Error " + ex.toString()); } buf = result; } editor.setText(Double.toString(result)); last_op = "="; } // Sqrt if(action=="sqrt") { if(firsttime==false) { buf = Math.sqrt(buf); editor.setText(Double.toString(buf)); opclicked=true; last_op = "sqrt"; } else { if(editor.getText()=="") JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { buf = Double.parseDouble(editor.getText()); buf = Math.sqrt(buf); editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "sqrt"; } } } // Reciprocal if(action=="1/x") { if(firsttime==false) { buf = 1/ buf; editor.setText(Double.toString(buf)); opclicked=true; last_op = "1/x"; } else { if(editor.getText()==null) JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { buf = Double.parseDouble(editor.getText()); buf = 1 / buf; editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "1/x"; } } } // Square if(action=="x^2") { if(firsttime==false)

Page 34: 96680522-Java-Lab

{ buf = buf * buf; editor.setText(Double.toString(buf)); opclicked=true; last_op = "x^2"; } else { if(editor.getText()==null) JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { buf = Double.parseDouble(editor.getText()); buf = buf * buf; editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "x^2"; } } } // Negation +/- if(action=="+/-") { if(firsttime==false) { buf = -(buf); editor.setText(Double.toString(buf)); opclicked=true; last_op = "+/-"; } else { if(editor.getText()==null) JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { buf = Double.parseDouble(editor.getText()); buf = -(buf); editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "+/-"; } } } // Exit if(action=="mExit") { frame.dispose(); System.exit(0); } if(action=="mCut") editor.cut(); if(action=="mCopy") editor.copy(); if(action=="mPaste") editor.paste(); if(action=="sin") { if(radians.isSelected()) { if(firsttime==false) { buf = Math.sin(Double.parseDouble(editor.getText())); editor.setText(Double.toString(buf)); opclicked=true; last_op = "sin"; } else

Page 35: 96680522-Java-Lab

{ if(editor.getText()=="") JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { buf = Double.parseDouble(editor.getText()); buf = Math.sin(Double.parseDouble(editor.getText())); editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "sin"; } } } else { if(firsttime==false) { double rad=Math.toRadians(Double.parseDouble(editor.getText())); buf = Math.sin(rad); editor.setText(Double.toString(buf)); opclicked=true; last_op = "sin"; } else { if(editor.getText()=="") JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { double rad=Math.toRadians(Double.parseDouble(editor.getText())); buf = Math.sin(rad); editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "sin"; } } } }// end of sin if(action=="cos") { if(radians.isSelected()) { if(firsttime==false) { buf = Math.cos(Double.parseDouble(editor.getText())); editor.setText(Double.toString(buf)); opclicked=true; last_op = "cos"; } else { if(editor.getText()=="") JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { buf = Double.parseDouble(editor.getText()); buf = Math.sin(Double.parseDouble(editor.getText())); editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "cos"; } } } else { if(firsttime==false) { double rad=Math.toRadians(Double.parseDouble(editor.getText())); buf = Math.cos(rad);

Page 36: 96680522-Java-Lab

editor.setText(Double.toString(buf)); opclicked=true; last_op = "cos"; } else { if(editor.getText()=="") JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { double rad=Math.toRadians(Double.parseDouble(editor.getText())); buf = Math.cos(rad); editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "cos"; } } } }// end of cos if(action=="tan") { if(radians.isSelected()) { if(firsttime==false) { buf = Math.tan(Double.parseDouble(editor.getText())); editor.setText(Double.toString(buf)); opclicked=true; last_op = "tan"; } else { if(editor.getText()=="") JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { buf = Double.parseDouble(editor.getText()); buf = Math.tan(Double.parseDouble(editor.getText())); editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "tan"; } } } else { if(firsttime==false) { double rad=Math.toRadians(Double.parseDouble(editor.getText())); buf = Math.tan(rad); editor.setText(Double.toString(buf)); opclicked=true; last_op = "tan"; } else { if(editor.getText()=="") JOptionPane.showMessageDialog(frame,"Enter input pls...","Input Missing",JOptionPane.ERROR_MESSAGE); else { double rad=Math.toRadians(Double.parseDouble(editor.getText())); buf = Math.tan(rad); editor.setText(Double.toString(buf)); firsttime = false; opclicked=true; last_op = "tan"; } } } }// end of tan }

Page 37: 96680522-Java-Lab

} }

RESULT Thus the java program for design a scientific calculator was compiled and executed

successfully.

Page 38: 96680522-Java-Lab

EX NO:9) OPAC SYSTEM FOR

LIBRARY DATE:

AIM

To develop a simple OPAC system for library using event driven programming paradigm of

JAVA and it is connected with backend database using JDBC connection.

ALGORITHM

1. Create a database table Books with following fields Field Name Data Type

Title String

Author String

Edition Int

ISBN String

2. Define a class Library that must have the following methods for accessing the information

about the books available in library. a. addBook( )

b. deleteBook( ) c. viewBooks( )

3. Design the user interface screen with necessary text boxes and buttons. This page is formatted using grid layout.

Method: addBook( )

This method takes the book title, author name,edition and ISBN as input parameters

and store them in Books table.

1. Establish connection with database

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Connection con=DriverManager.getConnection(“jdbc:odbc:DSN”,””,””);

2. Add the details in Books table.

PreparedStatement ps=con.prepareStatement(“insert into Books

values(?,?,?,?)”); Ps.setString(1,title);

Ps.setString(2,author)

; Ps.setInt(3,edition);

Ps.setString(4,ISBN);

3. Execute the statement.

ps.executeUpdate()

;

4. Close the connection.

Method :deleteBook()

1. Establish connection with database

2. Delete the details from Books table.

PreparedStatement ps=con.prepareStatement(“delete from Books where

author=?”); Ps.setString(1,author);

3. Execute the statement.

ps.executeQuery()

;

4. Close the connection.

Page 39: 96680522-Java-Lab

Method :viewBook()

1. Establish connection with database

2. read the details in Books table.

PreparedStatement ps=con.prepareStatement(“select * from Books where

title=?”); Ps.setString(1,title);

3. Execute the statement.

ps.executeQuery()

;

4. Close the connection.

REVIEW QUESTIONS

1. What do you mean by JDBC? JDBC is a part of the Java Development Kit which defines an application-

programming

interface that enables java programs to execute SQL statements and retrieve results from database.

2. List down the ways ODBC differ from JDBC?

ODBC is for Microsoft and JDBC is for java applications.

ODBC can't be directly used with Java because it uses a C interface.

ODBC requires manual installation of the ODBC driver manager and driver on

all client machines.

3. What are drivers available?

JDBC-ODBC Bridge driver

Native API Partly-Java driver

JDBC-Net Pure Java driver

Native-Protocol Pure Java driver

4. What are the steps involved for making a connection with a database or how do

you connect to a database? 1) Loading the driver:

Class. forName(”sun. jdbc. odbc. JdbcOdbcDriver”);

When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver.

2) Making a connection with database: Connection con = DriverManager. getConnection (”jdbc:odbc:somedb”, “user”,

“password”); 3) Executing SQL statements :

Statement stmt = con. createStatement(); ResultSet rs = stmt. executeQuery(”SELECT * FROM some table”);

4) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row.

The getString() and getObject() methods are used for retrieving column values.

Page 40: 96680522-Java-Lab

5. Define ODBC. ODBC is a standard for accessing different database systems. There are interfaces for

Visual Basic, Visual C++, SQL and the ODBC driver pack contains drivers for the

Access, Paradox, dBase, Text, Excel and Btrieve databases

PROGRAM

Develop a simple OPAC system for library using even-driven and concurrent programming

paradigms of Java. Use JDBC to connect to a back-end database.

Procedure

1. Create a new Database file in MS ACCESS (our backend) named “books.mdb”.

2. Then create a table named “Library” in it.

3. The table Library contains the following fields and data types,

i. AuthorName – Text

ii. ISBN – Text

iii. BookName - Text

iv. Price - Number

v. Publisher – Text

4. Enter various records as you wish.

5. Save the database file.

6. Next step is to add our “books.mdb” to the System DSN. To do that follow the procedure

given below,

i. Go to Start-> Control Panel -> Administrative tools.

ii. In that double click “Data Sources (ODBC)”.

iii. ODBC Data Source Administrator dialog appears.

iv. In that select “System DSN” tab and click the Add Button.

v. Select “Microsoft Access Driver(*.mdb)” and click Finish.

vi. ODBC Microsoft Access Setup appears. In the “Data Source name” type “Library”.

vii. Click on the “Select” button and choose your database file. Then click ok.

Now your database file gets added to the System DSN. It should look like below,

Page 41: 96680522-Java-Lab

Now execute the following code “Library.java”.

Library.java import java.sql.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class Library implements ActionListener { JRadioButton rbauthor = new JRadioButton("Search by Author name"); JRadioButton rbbook = new JRadioButton("Search by Book name"); JTextField textfld = new JTextField(30); JLabel label = new JLabel("Enter Search Key"); JButton searchbutton = new JButton("Search"); JFrame frame = new JFrame(); JTable table; DefaultTableModel model; String query = "select * from Library"; public Library() { frame.setTitle("Online Public Access Catalog"); frame.setSize(500,600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); p1.setLayout(new FlowLayout()); p1.add(label); p1.add(textfld); ButtonGroup bg = new ButtonGroup(); bg.add(rbauthor); bg.add(rbbook); p2.setLayout(new FlowLayout()); p2.add(rbauthor); p2.add(rbbook);

Page 42: 96680522-Java-Lab

p2.add(searchbutton); searchbutton.addActionListener(this); p3.setLayout(new BorderLayout()); p3.add(p1,BorderLayout.NORTH); p3.add(p2,BorderLayout.CENTER); frame.add(p3,BorderLayout.NORTH); addTable(query); frame.setVisible(true); } public void addTable(String s) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection("jdbc:odbc:Library","",""); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(s); ResultSetMetaData md = rs.getMetaData(); int cols = md.getColumnCount(); model = new DefaultTableModel(1,cols); table = new JTable(model); String[] tabledata = new String[cols]; int i=0; while(i0) model.removeRow(0); frame.remove(table); addTable(query); } public static void main(String[] args) { new Library(); } }

RESULT Thus the java program for develop a simple OPAC system for library was compiled and

executed successfully.

Page 43: 96680522-Java-Lab

EX NO:10) CHATTING

DATE:

AIM

To implement a simple chat application using JAVA.

ALGORITH

M Server 1. Import io and net packages. 2. Using InputStreamReader(System.in) class read the contents from keyboard and pass it to

BufferedReader class.

3. Create a server socket using DatagramSocket(port no) class.

4. Use DatagramPacket() class to create a packet.

5. To send and receive the datagram packets, use send(packetobj) and receive(packetobj).

Client 1. Import io and net packages.

2. Using InputStreamReader(System.in) class read the contents from keyboard and pass it to

BufferedReader class.

3. Create a client socket using DatagramSocket(port no) class.

4. Use DatagramPacket() class to create a packet.

5. To send and receive the datagram packets, use send(packetobj) and receive(packetobj).

REVIEW QUESTIONS

1. Define socket. The socket is a software abstraction used to represent the terminals of a connection between

two machines or processes. (Or) it is an object through which application sends or receives packets of data across network.

2. What are the basic operations of client sockets?

1.Connect to a remote machine 2.Send data

3.Receive data 4.Close a connection

3. What are the basic operations of Server socket? Bind to a port

Listen for incoming data

Accept connections from remote machines on the bound port

4. What is meant by datagram? The data‟s are transmitted in the form of packets that is called as datagram. Finite size

data packets are called as datagram.

Page 44: 96680522-Java-Lab

5. List all the socket classes in java. Socket

ServerSocket

Datagram Socket

Multicast Socket

Secure sockets

PROGRAM

Server Code

import java.net.*;

import java.io.*;

public class server10

{

public static DatagramSocket ds;

public static int clientPort=777,serverPort=666;

public static byte buff[]=new byte[1024];

public static void main (String[] args) throws Exception

{

ds=new DatagramSocket(serverPort);

BufferedReader dfs=new BufferedReader(new InputStreamReader(System.in));

System.out.println(“Server is waiting..”);

InetAddress in=InetAddress.getByName(“localhost”);

System.out.println(“Enter a choice 1 or 2″);

int cho;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

cho=Integer.parseInt(br.readLine());

Page 45: 96680522-Java-Lab

switch(cho)

{

case 1:

while(true)

{

String s=dfs.readLine();

if(s==null||s.equals(“ends”))

break;

buff=s.getBytes();

ds.send(new DatagramPacket(buff,s.length(),in,clientPort));

}

break;

case 2:

while(true)

{

DatagramPacket p=new DatagramPacket(buff,buff.length);

ds.receive(p);

String s1=new String(p.getData(),0,p.getLength());

System.out.println(s1);

}

}

}

}

Page 46: 96680522-Java-Lab

Client Code

import java.net.*;

import java.io.*;

class client10

{

public static DatagramSocket ds;

public static int clientPort=777,serverPort=666;

public static byte buff[]=new byte[1024];

public static void main(String args[]) throws Exception

{

ds=new DatagramSocket(clientPort);

System.out.println(“Client is waiting for Server to send data…..”);

InetAddress in=InetAddress.getLocalHost();

int cho;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println(“Enter a choice 1 or 2″);

cho=Integer.parseInt(br.readLine());

switch(cho)

{

case 1:

Page 47: 96680522-Java-Lab

while(true)

{

DatagramPacket p=new DatagramPacket(buff,buff.length);

ds.receive(p);

String s1=new String(p.getData(),0,p.getLength());

System.out.println(s1);

}

case 2:

while(true)

{

String s=br.readLine();

if(s==null||s.equals(“ends”))

break;

buff=s.getBytes();

ds.send(new DatagramPacket(buff,s.length(),in,serverPort));

}

break;

}

}

}

RESULT Thus the java program for developing chat application was compiled and executed

successfully.

Page 48: 96680522-Java-Lab

EX NO:11) DATE CLASS IMPLEMENTATION

DATE:

AIM

To develop a User defined Date class in java.

ALGORITHM

1. Import

sun.util.calendar.CalendarDate,sun.util.calendar,java.text.DateFormat and

sun.util.calendar.BaseCalendar packages.

2. Create an instance to the class BaseCalendar in util package.

3. Get the Date and time using getGregorianCalendar() method.

BaseCalendar gcal =

CalendarSystem.getGregorianCalendar();

4. currentTimeMillis() method is used to return the current time in milliseconds.

5. Get year using getYear() method in CalenderSystem class and display it on screen.

REVIEW QUESTIONS

1. List some functions of Date class. Date class has two important functions.

long getTime( ) Returns the number of milliseconds that have elapsed since

January 1,

1970.

void setTime(long time) Sets the time and date as specified by time, which

represents an elapsed time in milliseconds from midnight, January 1, 1970.

2. What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.

Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map.

3. What is the GregorianCalendar class? GregorianCalendar is a concrete implementation of a Calendar that implements the

normal Gregorian calendar with which you are familiar. The getInstance( )

method of Calendar returns a GregorianCalendar initialized with the current date

and time in the default locale and time zone. GregorianCalendar defines two

fields: AD and BC. These represent the two eras defined by the Gregorian calendar.

4. What is the SimpleTimeZone class?

The TimeZone class allows you to work with time zone offsets from Greenwich

mean time (GMT), also referred to as Coordinated Universal Time

Page 49: 96680522-Java-Lab

(UTC).

5. What is the SimpleTimeZone class? The SimpleTimeZone class is a convenient subclass of TimeZone. It implements

TimeZone‟s abstract methods and allows you to work with time zones for a

Gregorian calendar.

6. Which package is required to use Gregorian Calendar programs? Java. util.calendar.Gregorian

PROGRAM import java.util.*;

public class CDate

{

private int day;

private int month;

private int year;

public CDate() // default constructor

{

setDate(0,0,0);

}

public CDate(int day, int month, int year) // constructor with parameters

{

setDate(day, month, year);

}

public void setDate(int day, int month, int year)

{

[COLOR="Blue"]if month = 1 && day < 32 (syntax err on token "if", invalid Type. - syntax err,

insert Block statements for value "32")[/COLOR] D = day;

M = month;

Y = year;

else [COLOR="Blue"](syntax err on token "else)[/COLOR] D = 0;

M = 0;

Y = 0;

if month = 2 && day < 29

D = day;

M = month;

Y = year;

else

Page 50: 96680522-Java-Lab

D = 0;

M = 0;

Y = 0;

if month = 3 && day < 32

D = day;

M = month;

Y = year;

else

D = 0;

M = 0;

Y = 0;

if month = 4 && day < 31

D = day;

M = month;

Y = year;

else

D = 0;

M = 0;

Y = 0;

}

public static void main(String[] args)

{

Scanner console = new Scanner(System.in);

/* CDate aDate = new CDate(); */ // I don't think I need this statement (?)

String inputLine; [COLOR="Blue"](local variable inputLine never read)[/COLOR]

System.out.println(" This program is a date validator.\n"

+" When you enter a date, it will tell you"

+" whether the date is a valid date.\n"

+" You must enter a year greater than or equal to 1950. ");

System.out.println("Please enter today's date (month, day, and year separated by spaces):");

inputLine = console.nextLine();

}

}

RESULT Thus the java program for implementing Date class was compiled and executed

successfully.