java lab manual

92
Rajalakshmi Institute of Technology Department of Information Technology Subject Code: IT 2305 JAVA Programming LAB Manual Name : …………………………………… Reg No : ……………………………………

Upload: ashok-kumar

Post on 30-Dec-2015

18 views

Category:

Documents


5 download

DESCRIPTION

java lab manual for engg

TRANSCRIPT

Page 1: java Lab Manual

Rajalakshmi Institute of Technology

Department of Information Technology

Subject Code: IT 2305

JAVA Programming LAB Manual

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

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

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

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

Page 2: java Lab Manual

JAVA LAB

EX NO:1.1) EFFICIENT REPRESENTATION FOR RATIONAL NUMBER DATE:

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

ALGORITHM1. 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: java Lab Manual

Page 1 of 38

Page 4: java Lab Manual

JAVA LAB

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 5: java Lab Manual

Page 2 of 38

Page 6: java Lab Manual

JAVA LAB

RESULTThus the java program for finding simplified form of the given rational number was

compiled and executed successfully.

Page 7: java Lab Manual

Page 3 of 38

Page 8: java Lab Manual

JAVA LAB

EX NO:1.2) FIBONACCI SERIESDATE:

AIMTo write a JAVA program for finding first N Fibonacci numbers.

ALGORITHM1. 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 + F2F1 = F2F2 =FIBPRINT FIB

END FOR6. 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 9: java Lab Manual

Page 4 of 38

Page 10: java Lab Manual

JAVA LAB

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 11: java Lab Manual

Page 5 of 38

Page 12: java Lab Manual

JAVA LAB

EX NO:1.3) PRIME NUMBER CHECKINGDATE:

AIMTo 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 following1. 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 thenPrint a[i] is Prime

ELSEPrint a[i] is not Prime

END IFEND FOR

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

1. FOR i=2 to N/2IF N is divisible by i

return FALSEELSE

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 13: java Lab Manual

Page 6 of 38

Page 14: java Lab Manual

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

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

Page 15: java Lab Manual

Page 7 of 38

Page 16: java Lab Manual

JAVA LAB

EX NO:2) LEAP YEAR CALCULATIONDATE:

AIMTo 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 17: java Lab Manual

Page 8 of 38

Page 18: java Lab Manual

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

Page 19: java Lab Manual

Page 9 of 38

Page 20: java Lab Manual

JAVA LAB

RESULT

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

Page 21: java Lab Manual

Page 10 of 38

Page 22: java Lab Manual

JAVA LAB

EX NO:3) LISP IMPLEMENTATIONDATE: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 QUESTIONS1. How this() method used with constructors?

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

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 23: java Lab Manual

Page 11 of 38

Page 24: java Lab Manual

JAVA LAB

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 25: java Lab Manual

Page 12 of 38

Page 26: java Lab Manual

CS58 - JAVA LAB

RESULTThus the java program for implementing the basic operations of LISP was compiled

and executed successfully.

Page 27: java Lab Manual

Page 13 of 38

Page 28: java Lab Manual

JAVA LAB

EX NO:4) POLYMORPHISM - METHOD OVERLOADINGDATE:

AIMTo 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 29: java Lab Manual

Page 14 of 38

Page 30: java Lab Manual

CS58 - JAVA LAB

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

PROGRAM

Page 31: java Lab Manual

Page 15 of 38

Page 32: java Lab Manual

CS58 - JAVA LAB

RESULTThus the java program for design a Vehicle class hierarchy was compiled and

executed successfully.

Page 33: java Lab Manual

Page 16 of 38

Page 34: java Lab Manual

JAVA LAB

EX NO:5) STACK IMPLEMENTATION USING ARRAY AND LINKED LIST DATE:

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

ALGORITHM

Interface: StackADT1. 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 FullELSE

top++ stack[top]=element

END IF5. POP method return the data

popped. Data type POP()IF top==-1

Print Stack is EmptyELSE

return stack[top--] END IF

Class: StackLinkedlist1. 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 QUESTIONS1. 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 35: java Lab Manual

Page 17 of 38

Page 36: java Lab Manual

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

Page 37: java Lab Manual

Page 18 of 38

Page 38: java Lab Manual

CS58 - JAVA LAB

RESULTThus the java program for implementing stack using array and linked list was

compiled and executed successfully.

Page 39: java Lab Manual

Page 19 of 38

Page 40: java Lab Manual

JAVA LAB

EX NO:6) CURRENCY CONVERSIONDATE:

AIMTo 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 classimport 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 StreamStream 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 41: java Lab Manual

Page 20 of 38

Page 42: java Lab Manual

JAVA LAB

A byte stream class provides support It provides support for managing I/Ofor handling I/O operations on bytes. operations on characters.

Byte stream classes are InputStream Reader and Writer classes areand OutputStream. 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 43: java Lab Manual

Page 21 of 38

Page 44: java Lab Manual

JAVA LAB

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

Page 45: java Lab Manual

Page 22 of 38

Page 46: java Lab Manual

JAVA LAB

EX NO:7) MUTLITHREADINGDATE:

AIMTo 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 47: java Lab Manual

Page 23 of 38

Page 48: java Lab Manual

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

Page 49: java Lab Manual

Page 24 of 38

Page 50: java Lab Manual

JAVA LAB

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

Page 51: java Lab Manual

Page 25 of 38

Page 52: java Lab Manual

JAVA LAB

EX NO:8) SCIENTIFIC CALCULATORDATE:

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

ALGORITHM1. 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 53: java Lab Manual

Page 26 of 38

Page 54: java Lab Manual

JAVA LAB

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 55: java Lab Manual

Page 27 of 38

Page 56: java Lab Manual

JAVA LAB

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

successfully.

Page 57: java Lab Manual

Page 28 of 38

Page 58: java Lab Manual

JAVA LAB

EX NO:9) LIBRARY Management SystemDATE:

AIMTo develop a simple Library Management system for library using event driven

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

ALGORITHM1. Create a database table Books with following fields

Field Name Data TypeTitle String

Author StringEdition IntISBN 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 59: java Lab Manual

Page 29 of 38

Page 60: java Lab Manual

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 61: java Lab Manual

Page 30 of 38

Page 62: java Lab Manual

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

Page 63: java Lab Manual

Page 31 of 38

Page 64: java Lab Manual

CS58 - JAVA LAB

RESULTThus the java program for develop a simple Library Management system for library

was compiled and executed successfully.

Page 65: java Lab Manual

Page 32 of 38

Page 66: java Lab Manual

JAVA LAB

EX NO:10) CHATTINGDATE:

AIMTo implement a simple chat application using JAVA.

ALGORITHMServer

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

Client1. 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 67: java Lab Manual

Page 33 of 38

Page 68: java Lab Manual

JAVA LAB

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

PROGRAM

Page 69: java Lab Manual

Page 34 of 38

Page 70: java Lab Manual

CS58 - JAVA LAB

RESULTThus the java program for developing chat application was compiled and executed

successfully.

Page 71: java Lab Manual

Page 35 of 38

Page 72: java Lab Manual

JAVA LAB

EX NO:11) DATE CLASS IMPLEMENTATIONDATE:

AIMTo 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 73: java Lab Manual

Page 36 of 38

Page 74: java Lab Manual

CS58 - JAVA LAB

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

PROGRAM

RESULTThus the java program for implementing Date class was compiled and executed

successfully.

Page 75: java Lab Manual

Page 37 of

38

Page 76: java Lab Manual