Vous êtes sur la page 1sur 63

Panipat Institute of Engineering & Technology, Samalkha,

Panipat
Computer Science & Engineering Department

ADT Lab Manual


Submitted to:

Submitted By:

Mr.Shiraz khurana
(Assistant Professor)

Anuj Kumar
2814267
Cse 3rd year

Affiliated to

Kurukshetra University Kurukshetra, India

Index
Sr.
No.

Title of the Practical

Date

Learn Basics of java and its development tool 26 August 2016


library.

Write a program to implement abstract method 26 August 2016


and classes.

Write a program to implement concept of 26 August 2016


overloading.

Write a program to implement concept of 2 September


2016
overriding.

Write a program to implement concept of 2 September


2016
packages.

6
7
8

9
10

Write a program to implement inheritance.

2 September
2016

Write a program to implement interfaces.

9 September
2016

Write a program to implement multithreading 9 September


2016
in java.

9 September
2016

Write a program to design a frame.

Write a Program to demonstrate Exception 16 September


2016
Handling.
2

Signature

11

12

13

Generate an editor screen containing menus, 16 September


2016
dialog boxes etc using Java.

Create an applet with a text field and three 16 September


buttons. When you press each button, make 2016
some different text appear in the text field.
Add a check box to the applet created, capture
the event and insert different text in the text
field.

Create an applet with a button and a text field. 23 September


Write a Focus Event ( ) so that if the button has 2016
the focus, characters typed into it will appear
in the text field.

14

Write a Program to demonstrate various 23 September


2016
methods to input from keyboard in JAVA

15

Write a program to implement JDBC/ODBC 7 October 2016


connectivity to data base using java program.

16

Write a program to connect MYSQL database 7 October 2016


to a java program.

17

Write a program to create a java socket for 21 October 2016


both client and server.

18

Write a program to set a connection between 21 October 2016


client and server in java using TCP.

19

Write a program to set a connection between 11 November


2016
client and server in java using UDP.

20

Design a frame consisting of options Line, 11 November


2016
Rectangle, Oval.

21

Using Java develop a front end for a contact 18 November


management program using a flat file 2016
database. DB needs to be distributed or
centralized.

Practical no 1

Aim: Learn Basics of java and its development tool library.


Theory:
JAVA: Java is programming language developed by James gosling at sun microsystem and released
in 1995 as a core component of sun Microsystem java platform.
The language devices much of its syntax from C and C++ but has a simpler object mode 1 and fewer
low level facilities. Java is a general purpose,concurrent,class based object oriented that is
specifically designed to have as few implementation dependencies as possible.Java is currently one
of the most popular programming language in use and is widely used from application software to
web application.
Need For Java
The java language contains built-in support for the world wide web (www) which is a service of the
internet to reterive information in the form of web pages
Java Tools
These tools are the foundation of JDK. These are the tools we use to create and build application.
Javac: Compiler for the java programming language.
Javadoc: APJ documentation generator.
Applet Viewer: Run and debug applets withoutbrowser.
Jar: Create and manage java archieve(JAR) files.
Jdb: The java debugger.
Characteristics of Java
Simple
Object-Oriented
Compiled and Interpreted
Portable
Distributed
Secure
Java supports the object oriented approach to develop programs. It supports various features of an
object-oriented language such as abstraction, encapsulation, inheritance and polymorphism. To
implement the object oriented language, the entire code of the program must be written within a
class. The java does not supports stand-alone statements. Even the most basic program in java must
be written with in a class.
Object Oriented Concepts:
Object
Classes
Polymorphisms
Inheritance
Encapsulation
Abstraction

The Java Virtual Machine:


This is defined as an imaginary machine that is implemented by emulating it in software on a real
machine. Code for JVM is stored in .class file, each of which contains code for at most one public
class. The Java virtual machine specification provides that hardware platform specification to which
you compile all java technology code. This specification enables the java software to be platformindependent because the compilation is done for a generic machine, known as the JVM.
The compiler takes the java application source code and generates byte codes.
Byte codes are machine codes instructions for JVM.
JVM reads the class files not the source file.
The tools for JVM are heap and stack.
JVM also support high precision timing for execution of files.
The Java Runtime Environment (JRE)
A Java virtual machine is a program which executes certain other programs, namely those
containing Java byte code instructions. JVMs are most often implemented to run on an existing
operating system, but can also be implemented to run directly on hardware. A JVM provides an
environment in which Java byte code can be executed, enabling such features automated, which
provides root-cause debugging information for every software error (exception), independent of the
source code. A JVM is distributed along with a set of standard class libraries that implement the Java
application programming interface (API). These libraries, bundled together with the JVM, form the
Java Runtime Environment (JRE).
JVMs are available for many hardware and software platforms. The use of the same bytecode for all
JVMs on all platforms allows Java to be described as a write once, run anywhere programming
language, versus write once, compile anywhere, which describes cross-platform compiled
languages. Thus, the JVM is a crucial component of the Java platform.
The tasks of JVM are:

Load Code
Verifier
Executes Codes

Garbage Collection
Many programming languages permit the memory to be allocated dynamically at run time. The
process allocating memory varies based on the syntax of the language but always involves returning
a pointer to the starting address of the memory block.
After allocated memory is no longer required, the program or run time environment should deallocate the memory.
The java programming language removes you from the responsibility of de-allocating memory. It
provides a system level thread that tracks each memory allocation. During idle cycles in the JVM,
the garbage collection threads checks for and frees any memory that can be freed.
Garbage collection happens automatically during the lifetime of a java technology program.
Applets
These are small executable programs that run on web page. These programs required a java-enabled
browser such as internet explorer or Netscape navigator. These have limited access to computer
resources.
Servlets
These are the programs that are used to extend the functionality of web servers.
Packages
6

Packages are collection of classes that can be reused by application and applets.
Features of Java
The JUM
Garbage Collection
The JRE
JVM Tool Interface
1. The primary motive behind developing java language was the need for a portable and platform
independent language that could be used to produce code that would run on a variety of control
processing unit under different environments.
2. You can use java to develop network-oriented programs because networking features are builtin features in java.
Applications of java:
1. Applications that use character user interface: These applications have an access to the system
resources such as file system and can read and write to files on local computers.
2. Application that use graphical user interface (GUI): These applications are used in the windows
environment. In GUI, you can interact with the application in graphical mode.

Practical no 2
Aim: Write a program to implement abstract method and classes.
Code/Description:
abstract class Shape
{
int x,y;
Shape(int a, int b)
{
x=a;
y=b;
}
abstract int area();
}
class Rectangle extends Shape
{
Rectangle(int a, int b)
{
super(a,b);
}
int area()
{
System.out.println("Inside Rectangle_area");
return x*y;
}
}
public class Abst
{
public static void main(String args[])
{
Rectangle r=new Rectangle(4,2);
Shape s;
s=r;
System.out.println("Area of the rectangle: "+s.area());
}
}

Output:

Practical no 3
Aim: Write a program for Overloading

Code/Description:
class OverloadDemo
{
void area(float x)
{
System.out.println("the area of the square is "+Math.pow(x, 2)+" sq units");
}
void area(float x, float y)
{
System.out.println("the area of the rectangle is "+x*y+" sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
System.out.println("the area of the circle is "+z+" sq units");
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();

ob.area(5);
ob.area(11,12);
ob.area(2.5);
}
}

Output:
10

11

Practical no 4
Aim: Write a program to implement concept of overriding.

Code/Description:

class ABC{
public void disp()
{
System.out.println("disp() method of parent class");
}
public void abc()
{
System.out.println("abc() method of parent class");
}
}
class Override extends ABC{
public void disp(){
System.out.println("disp() method of Child class");
}
public void xyz(){
System.out.println("xyz() method of Child class");
}
public static void main( String args[]) {
//Parent class reference to child class object
ABC obj = new Override();
obj.disp();
//will override the parent class method
obj.abc();
}
}

12

Output:

13

Practical no 5
Aim: Write a program to implement concept of packages.
Code/Description:

public class package1


{

public void display()


{

System.out.println("YOU ARE IN THE DISPLAY FUNCTION OF THE PACKAGE1");


}
}

//class that imports the package


import adt_lab.*;
class import1
{
public static void main(String args[])
{
import1 obj= new import1();
obj.display1();
}
}

14

Output:

15

Practical no 6
Aim: Write a program to implement inheritance.

Code/Description:

class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
class inherit extends Calculation {
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
inherit demo = new inherit();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
} }

16

Output:

17

Practical no 7
Aim: Write a program to implement interface.
Code/Description:

interface Janvar {
public void eat();
public void travel();
}
public class Animal implements Janvar {

public void eat()


{
System.out.println(" janvar khata h

bach ke rehna apko na kha jae");

public void travel() {


System.out.println("janvaro ko ghumne ka bahut shauk h");
}
public int noOfLegs() {
return 0;
}
public static void main(String args[]) {
Animal m = new Animal();
m.eat();
m.travel()
}

}
18

Output:

19

Practical no 8
Aim: Write a program to implement multi-threading.
Code/Description:

import java.util.Timer;
import java.util.TimerTask;

public class timer {


static int counter = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {

public void run() {


System.out.println("TimerTask executing counter is: " + counter);
counter++;//increments the counter
}
};

Timer timer = new Timer("MyTimer");//create a new Timer

timer.scheduleAtFixedRate(timerTask, 30, 3000);//this line starts the timer at the same time its
executed
}}

20

Output:

21

Practical no 9
Aim: Write a program to design a frame.
Code/Description:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;

class frames extends JFrame implements ActionListener


{
JPanel pr;
JLabel name,roll,stream,age;
JTextField n,r,a,s;
JTextArea area;
JButton ok,ca;
frames()
{
setSize(1080,580);
Font f=new Font("Lucida Calligraphy",Font.BOLD,35);
pr=new JPanel();
pr.setVisible(true);
pr.setSize(1080,580);
pr.setBounds(200,200,1080,580);
pr.setLayout(null);
pr.setBackground(Color.white);
add(pr);
22

roll=new JLabel("Roll:");
name=new JLabel("Name:");
age=new JLabel("Age:");
stream=new JLabel("Stream:");
n=new JTextField(25);
r=new JTextField(25);
s=new JTextField(25);
a=new JTextField(25);
area=new JTextArea();
ok=new JButton("OK");
ca=new JButton("CANCEL");

name.setBounds(200,120,180,30);
name.setFont(f);
name.setForeground(Color.black);
pr.add(name);

n.setBounds(470,120,150,40);
n.setFont(f);
n.setForeground(Color.black);
pr.add(n);

roll.setBounds(200,170,250,30);
roll.setFont(f);
roll.setForeground(Color.black);
pr.add(roll);

23

r.setBounds(470,170,150,40);
r.setFont(f);
r.setForeground(Color.black);
pr.add(r);

stream.setBounds(200,220,250,30);
stream.setFont(f);
stream.setForeground(Color.black);
pr.add(stream);

s.setBounds(470,220,150,40);
s.setFont(f);
s.setForeground(Color.black);
pr.add(s);

age.setBounds(200,270,250,50);
age.setFont(f);
age.setForeground(Color.black);
pr.add(age);

a.setBounds(470,270,150,40);
a.setFont(f);
a.setForeground(Color.black);
pr.add(a);

area.setBounds(600,320,150,150);
24

pr.add(area);

ok.setBounds(320,470,130,50);
pr.add(ok);
ca.setBounds(470,470,100,50);
pr.add(ca);

ok.addActionListener(this);
ca.addActionListener(this);

setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
// Side Buttons Main Window
if(e.getSource()==ok)
{
String nm,rl,st,ag;
nm=(String)n.getText();
rl=(String)r.getText();
st=(String)s.getText();
ag=(String)a.getText();
area.setText("HEY "+nm+"\n"+"YOUR ROLL NUMBER: "+rl+"\nYOU ARE
FROM:"+st);
}
if(e.getSource()==ca)
25

{
setVisible(false);

}
}
public static void main(String []args)
{
new frames();
}
}

26

Output:

27

Practical no 10
Aim: Write a Program to demonstrate Exception Handling.
Code/Description:

class exc
{
public static void main(String args[])
{
int d;
try
{
d=5/0;
}
catch(ArithmeticException e)
{
System.out.println("divide by zero error");
}

}
}

28

Output:

29

Practical no 11
Aim: Generate an editor screen containing menus, dialog boxes etc using Java.
Code/Description:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class five extends Frame implements ActionListener
{
MenuBar mb;
Menu m1,m2;
TextArea t;
String b;
MenuItem m3,m4,m5,m6,m7,m8,m9;
five()
{
setTitle("Notepad");
t=new TextArea();
mb =new MenuBar();
m1=new Menu("file");
m2 =new Menu("edit");
m3=new MenuItem("open");
m4=new MenuItem("save");
m5=new MenuItem("cut");
m6=new MenuItem("paste");
m7=new MenuItem("copy");
m8=new MenuItem("new");
m9=new MenuItem("exit");
t.setBackground(Color.WHITE);
add(t);
setMenuBar(mb);
mb.add(m1);
mb.add(m2);
30

m1.add(m8);
m1.add(m3);
m1.add(m4);
m1.add(m9);
m2.add(m5);
m2.add(m6);
m2.add(m7);
m3.addActionListener(this);
m4.addActionListener(this);
m5.addActionListener(this);
m6.addActionListener(this);
m7.addActionListener(this);
m8.addActionListener(this);
m9.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String s;
File ff;
FileInputStream fis;
FileOutputStream fos;
s=ae.getActionCommand();
try
{
if(s.equals("Exit"))
{
System.exit(0);
}
else
if(s.equals("new"))
{
t.setText("");
}else
if(s.equals("cut"))
31

{
b=t.getSelectedText();
t.replaceRange("", t.getSelectionStart(), t.getSelectionEnd());
}else
if(s.equals("paste"))
{
t.insert(b,t.getCaretPosition());
}else
if(s.equals("copy"))
{
b=t.getSelectedText();
}else
if(s.equals("open"))
{
FileDialog fd=new FileDialog(this,"open",FileDialog.LOAD);
fd.setVisible(true);
ff =new File(fd.getDirectory()+fd.getFile());
fis=new FileInputStream(ff);
String tt="";
int bb;
while(fis.available()>0)
{
bb =fis.read();
tt=tt+(char)bb;
}
t.setText(tt);
fis.close();
}else
if(s.equals("save"))
{
FileDialog fd=new FileDialog(this,"save",FileDialog.SAVE);
fd.setVisible(true);
ff=new File(fd.getDirectory()+fd.getFile());
fos =new FileOutputStream(ff);
32

byte ss[]=t.getText().getBytes();
fos.write(ss);
fos.close();
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
class six
{
public static void main(String args[])
{
five f=new five();
f.setVisible(true);
f.setSize(700,700);
}
}

33

Output:

34

Practical no 12
Aim: Create an applet with a text field and three buttons. When you press each button, make some
different text appear in the text field. Add a check box to the applet created, capture the event and
insert different text in the text field.
Code/Description:

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*<applet code="actionlistener1.class" height="200" width="200">*/
public class actionlistener1 extends Applet implements ActionListener{
TextField t1;
Button b1,b2,b3,b4;
@Override
public void init()
{
setBackground(Color.WHITE);
setLayout(null);
t1=new TextField(25);
t1.setBounds(100,50,100,25);
add(t1);
b1=new Button("CYAN");
b1.setBackground(Color.CYAN);
b1.setBounds(10, 100, 50, 50);
add(b1);
b2=new Button("BLACK");
b2.setBackground(Color.BLACK);
b2.setBounds(70, 100, 50, 50);
b2.setForeground(Color.WHITE);
add(b2);
b3=new Button("MAGENTA");
b3.setBackground(Color.MAGENTA);
b3.setBounds(140, 100, 50, 50);
add(b3);
35

b4=new Button("GREEN");
b4.setBackground(Color.GREEN);
b4.setBounds(200, 100, 50, 50);
add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("BLACK"))
{
t1.setText("black");
t1.setBackground(Color.BLACK);
t1.setForeground(Color.WHITE);
}
if(e.getActionCommand().equals("CYAN"))
{
t1.setText("cyan");
t1.setBackground(Color.CYAN);
t1.setForeground(Color.BLACK);
}
if(e.getActionCommand().equals("MAGENTA"))
{
t1.setText("Magenta");
t1.setBackground(Color.MAGENTA);
t1.setForeground(Color.BLACK);
}
if(e.getActionCommand().equals("GREEN"))
{
t1.setText("Green");
t1.setBackground(Color.GREEN);
t1.setForeground(Color.BLACK);
}
}

36

Output:

37

Practical no 13
Aim: Create an applet with a button and a text field. Write a Focus Event ( ) so that if the button has
the focus, characters typed into it will appear in the text field.

Code/Description:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="focus" height=500 width=500></applet>*/
public class focus extends Applet implements FocusListener
{
TextField t1;
Button b1,b2;
public void init()
{
Font f=new Font("Arial",Font.BOLD,25);
t1=new TextField(20);
t1.setFont(f);
add(t1);
b1=new Button("button 1");
add(b1);
b2=new Button("button 2");
add(b2);
b1.addFocusListener(this);
b2.addFocusListener(this);
}
public void focusGained(FocusEvent fe)
{
if(fe.getSource()==b1)
{
t1.setText("button 1 is focused");
}
else if(fe.getSource()==b2)
{
t1.setText("button 2 is focused");
}
}
public void focusLost(FocusEvent fe)
{
t1.setText("button is not focused");
}}
38

Output:-

39

Practical No: 14
Aim: Write a program to implement ODBC JDBC connectivity to database using java program.
Code/Description:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.pool.OracleDataSource;

/*
* Simple Java Program to connect Oracle database by using Oracle JDBC thin driver
*/
public class OracleJdbcExample {

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


//creating connection to Oracle database
Connection con=null;
try {
OracleDataSource ods=new OracleDataSource();
//URL of Oracle database server
ods.setURL("jdbc:Oracle:thin:@localhost:1521:XE");//location of database
con=ods.getConnection("SYSTEM","#Hashtag88#");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
40

//creating PreparedStatement object to execute query


PreparedStatement preStatement = con.prepareStatement("select * from textname");
ResultSet result = preStatement.executeQuery();
System.out.println("Output of Query : ");
while(result.next()){
String field1,field2;
field1=result.getString("NAME");
field2=result.getString("EMOJI");
System.out.println(field1 + " "+ field2);
}
System.out.println("Done");
}}

41

Output :

42

Practical no 15
Aim: Write a program to connect MYSQL database to a java program.

Code/Description: import java.sql.*;


import java.util.Scanner;
class Login
{
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Do", "root",
"anuj");
Statement stmt = con.createStatement();
boolean check;
String Username;
String Password;
do {
System.out.println("Enter your Username");
Username=sc.next();
System.out.println("Enter your Password");
Password=sc.next();
ResultSet rs = stmt.executeQuery("select * from mo where username = '"+Username+"'
and password = '"+Password+"'");
check = rs.next();
43

if(check)
{
System.out.println("Successful Login");
}
else
{
System.out.println("Incorrect username or password");
}
}while(!check);

}
catch(Exception ex)
{
System.out.println("EXception: " +ex.getMessage());
}
}
}

44

Output

45

Practical no 16

Aim: Write a Program to demonstrate various methods to input from keyboard in JAVA
Code/Description:
package adt_la;
import java.io.*;
import java.util.*;
class Input {
public static void main(String[] args) {
// using InputStreamReader
try {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = r.readLine();
System.out.println("Your name is: " + name);
} catch (Exception e) {
e.printStackTrace();
}
// using Scanner
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your roll number: ");
int r = scanner.nextInt();
System.out.println("Your roll no. is: " +r);
// using Console
Console c = System.console();

System.out.print("Enter the Stream: ");


String s = c.readLine();
System.out.print("Enter the year of engineering: ");
String ye = c.readLine();
System.out.println("Your Stream is: " +s);
System.out.println("Your year of passing is: " +ye);
}
}
46

Output:

47

Practical no 17
Aim: Write a program to create a java socket for both client and server.
// This code is for Client
import
import
import
import
import

java.io.IOException;
java.io.PrintStream;
java.net.Socket;
java.net.UnknownHostException;
java.util.Scanner;

public class cli{


public static void main(String args[]) throws UnknownHostException,
IOException
{
int number,temp;
Scanner sc =new Scanner(System.in);
Socket s =new Socket("127.0.0.1",1344);// for ip address & port number
Scanner sc1= new Scanner(s.getInputStream());//get input stream
System.out.println("Enter any number");
number= sc.nextInt();
PrintStream P= new PrintStream(s.getOutputStream());
P.println(number);
temp=sc1.nextInt(); // creating temporary variable in order to
accepting result from the server
System.out.println(temp);
}
}

// This code is for Server

import
import
import
import
import

java.io.IOException;
java.io.PrintStream;
java.net.ServerSocket;
java.net.Socket;
java.util.Scanner;
48

public class ser {


public static void main(String args[]) throws IOException
{
int number,temp;
ServerSocket s1=new ServerSocket(1344);// specified same port number
as specified in the client
Socket ss=s1.accept(); // for accept incoming request from the client.
Scanner sc=new Scanner(ss.getInputStream()); // accept some data from
the client.
number=sc.nextInt();
temp=number*2; // result saving on the operation and pass it.
PrintStream p=new PrintStream(ss.getOutputStream());
p.println(temp);
}
}

49

OutPut

50

Practical no 18
Aim : Write a program to set a connection between client and server in java using TCP.
// this code is for server save it as TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
System.out.println("SERVER is waiting to receive a string");
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new
BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
System.out.println("SERVER has converted a string from lowercase to uppercase");
}
}
}

51

// this code is for client save it as TCPClient.java


import java.io.*;
import java.net.*;
class TCPClient {
// this program wil send a string to server & server in return send the same string in capital
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}

52

OutPut

53

Practical 19
Aim: Write a program to set a connection between client and server in java using UDP.

// this is code for Server save it as UDPServer.java


import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
System.out.println("SERVER is waiting to receive a string");
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, port);

serverSocket.send(sendPacket);
System.out.println("SERVER has converted a string from lowercase to uppercase");

}
}

54

// this is code for Client save it as UDPClient.java


import java.io.*;
import java.net.*;
// this program wil send a string to server & server in return send the same string in
capital
class UDPClient {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}

55

56

Practical 20

Aim Design a frame consisting of options Line, Rectangle, Oval.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class firstGUI extends JFrame
implements ActionListener {
private
private
private
private
private
private
private
private

boolean showText = false;


boolean showRect = true;
boolean showOval = false;
JButton text;
JButton oval;
JButton rectangle;
JPanel buttonPanel;
DrawStuff drawPanel = new DrawStuff();

public firstGUI() {
super("First GUI");
setSize(512, 512);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 3));
text = new JButton("Text");
text.addActionListener(this);
buttonPanel.add(text);
oval = new JButton("Oval");
oval.addActionListener(this);
buttonPanel.add(oval);
rectangle = new JButton("Rectangle");
rectangle.addActionListener(this);
buttonPanel.add(rectangle);

Container contentPane = this.getContentPane();


contentPane.add(buttonPanel, BorderLayout.NORTH);
add(drawPanel);
}
57

public void actionPerformed(ActionEvent event) {


Object source = event.getSource();
if (source == text) {
showText = true;
repaint();
} else if (source == oval) {
showOval = true;
repaint();
} else if (source == rectangle) {
showRect = true;
repaint();
}
}
public static void main(String[] args) {
firstGUI myTest = new firstGUI();
myTest.setVisible(true);
}
class DrawStuff extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (showText) {
g.drawString("Hello", getHeight() / 2, getWidth() / 2);
showText = false;
} else if (showOval) {
g.drawOval(getWidth() / 4, getHeight() / 4, getWidth() /
2, getHeight() / 2);
showOval = false;
} else if (showRect) {
g.drawRect(getWidth() / 4, getHeight() / 4, getWidth() /
2, getHeight() / 2);
showRect = false;
}
}
}}

58

OutPut

59

60

61

62

63