Top Banner
EINSTEIN COLLEGE OF ENGINEERING Sir.C.V.Raman Nagar, Tirunelveli-12 Department of Computer Science and Engineering Subject Code: CS58 JAVA LAB Name : …………………………………… Reg No : …………………………………… Branch : …………………………………… Year & Semester : ……………………………………
38
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS58 Java Lab

EINSTEIN COLLEGE OF ENGINEERING Sir.C.V.Raman Nagar, Tirunelveli-12

Department of Computer Science and Engineering

Subject Code: CS58

JAVA LAB

Name : ……………………………………

Reg No : ……………………………………

Branch : ……………………………………

Year & Semester : ……………………………………

Page 2: CS58 Java Lab

CS58 - JAVA LAB

Page 1 of 38

© Einstein college of engineering

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.

Page 3: CS58 Java Lab

CS58 - JAVA LAB

Page 2 of 38

© Einstein college of engineering

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 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

Page 4: CS58 Java Lab

CS58 - JAVA LAB

Page 3 of 38

© Einstein college of engineering

RESULT

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

Page 5: CS58 Java Lab

CS58 - JAVA LAB

Page 4 of 38

© Einstein college of engineering

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.

Page 6: CS58 Java Lab

CS58 - JAVA LAB

Page 5 of 38

© Einstein college of engineering

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.

PROGRAM RESULT

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

Page 7: CS58 Java Lab

CS58 - JAVA LAB

Page 6 of 38

© Einstein college of engineering

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 8: CS58 Java Lab

CS58 - JAVA LAB

Page 7 of 38

© Einstein college of engineering

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 RESULT

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

Page 9: CS58 Java Lab

CS58 - JAVA LAB

Page 8 of 38

© Einstein college of engineering

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 10: CS58 Java Lab

CS58 - JAVA LAB

Page 9 of 38

© Einstein college of engineering

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

Page 11: CS58 Java Lab

CS58 - JAVA LAB

Page 10 of 38

© Einstein college of engineering

RESULT

Thus the java program for finding whether the given year is leap or not was compiled and executed successfully.

Page 12: CS58 Java Lab

CS58 - JAVA LAB

Page 11 of 38

© Einstein college of engineering

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.

Page 13: CS58 Java Lab

CS58 - JAVA LAB

Page 12 of 38

© Einstein college of engineering

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 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

Page 14: CS58 Java Lab

CS58 - JAVA LAB

Page 13 of 38

© Einstein college of engineering

RESULT

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

Page 15: CS58 Java Lab

CS58 - JAVA LAB

Page 14 of 38

© Einstein college of engineering

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.

Page 16: CS58 Java Lab

CS58 - JAVA LAB

Page 15 of 38

© Einstein college of engineering

5. What is hierarchy?

Ordering of classes (or inheritance) PROGRAM

Page 17: CS58 Java Lab

CS58 - JAVA LAB

Page 16 of 38

© Einstein college of engineering

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

successfully.

Page 18: CS58 Java Lab

CS58 - JAVA LAB

Page 17 of 38

© Einstein college of engineering

EX 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--] END IF

Class: StackLinkedlist 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: CS58 Java Lab

CS58 - JAVA LAB

Page 18 of 38

© Einstein college of engineering

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

Page 20: CS58 Java Lab

CS58 - JAVA LAB

Page 19 of 38

© Einstein college of engineering

RESULT

Thus the java program for implementing stack using array and linked list was compiled and executed successfully.

Page 21: CS58 Java Lab

CS58 - JAVA LAB

Page 20 of 38

© Einstein college of engineering

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

Page 22: CS58 Java Lab

CS58 - JAVA LAB

Page 21 of 38

© Einstein college of engineering

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.

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

Page 23: CS58 Java Lab

CS58 - JAVA LAB

Page 22 of 38

© Einstein college of engineering

RESULT

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

Page 24: CS58 Java Lab

CS58 - JAVA LAB

Page 23 of 38

© Einstein college of engineering

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 25: CS58 Java Lab

CS58 - JAVA LAB

Page 24 of 38

© Einstein college of engineering

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

Page 26: CS58 Java Lab

CS58 - JAVA LAB

Page 25 of 38

© Einstein college of engineering

RESULT

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

Page 27: CS58 Java Lab

CS58 - JAVA LAB

Page 26 of 38

© Einstein college of engineering

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.

Page 28: CS58 Java Lab

CS58 - JAVA LAB

Page 27 of 38

© Einstein college of engineering

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.

PROGRAM

Page 29: CS58 Java Lab

CS58 - JAVA LAB

Page 28 of 38

© Einstein college of engineering

RESULT

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

Page 30: CS58 Java Lab

CS58 - JAVA LAB

Page 29 of 38

© Einstein college of engineering

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 31: CS58 Java Lab

CS58 - JAVA LAB

Page 30 of 38

© Einstein college of engineering

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 32: CS58 Java Lab

CS58 - JAVA LAB

Page 31 of 38

© Einstein college of engineering

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

Page 33: CS58 Java Lab

CS58 - JAVA LAB

Page 32 of 38

© Einstein college of engineering

RESULT

Thus the java program for develop a simple OPAC system for library was compiled and executed successfully.

Page 34: CS58 Java Lab

CS58 - JAVA LAB

Page 33 of 38

© Einstein college of engineering

EX NO:10) CHATTING DATE: AIM

To implement a simple chat application using JAVA. ALGORITHM 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 35: CS58 Java Lab

CS58 - JAVA LAB

Page 34 of 38

© Einstein college of engineering

5. List all the socket classes in java. Socket ServerSocket Datagram Socket Multicast Socket Secure sockets

PROGRAM

Page 36: CS58 Java Lab

CS58 - JAVA LAB

Page 35 of 38

© Einstein college of engineering

RESULT

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

Page 37: CS58 Java Lab

CS58 - JAVA LAB

Page 36 of 38

© Einstein college of engineering

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 (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.

Page 38: CS58 Java Lab

CS58 - JAVA LAB

Page 37 of 38

© Einstein college of engineering

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

PROGRAM RESULT

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