Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
384 views

Advanced Java Programming Lab Manual

The document provides examples of using applets for different purposes like displaying digital clock, shapes, graphs etc. It also includes examples of network communication using TCP and UDP protocols. The key points are: 1. It shows the life cycle methods of an applet like init(), start(), paint() etc using a simple example. 2. Examples of using applets to display digital clock, shapes and bar graph passing parameters. 3. Examples of audio playback and factorial calculation using event handling in applets. 4. Examples of window closing event handling and network communication using TCP and UDP protocols.

Uploaded by

Kesava Pandian
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
384 views

Advanced Java Programming Lab Manual

The document provides examples of using applets for different purposes like displaying digital clock, shapes, graphs etc. It also includes examples of network communication using TCP and UDP protocols. The key points are: 1. It shows the life cycle methods of an applet like init(), start(), paint() etc using a simple example. 2. Examples of using applets to display digital clock, shapes and bar graph passing parameters. 3. Examples of audio playback and factorial calculation using event handling in applets. 4. Examples of window closing event handling and network communication using TCP and UDP protocols.

Uploaded by

Kesava Pandian
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

1.

Life Cycle of an Applet

app.java:

import java.io.*;
import java.applet.*;
import java.awt.*;
/*<applet code=app height=500 width=500></applet>*/
public class app extends Applet
{
String msg;
public void init()
{
msg="int->";
setBackground(Color.cyan);
System.out.println("init()called");
}
public void start()
{
msg+="start->";
System.out.println("start()called");
}
public void stop()
{
msg+="stop->";
System.out.println("stop()called");
}
public void destory()
{
msg+="destory->";
System.out.println("destroy()called");
}
public void paint(Graphics g)
{
msg+="paint->";
System.out.println("paint()called");
g.drawString(msg,200,250);
}
}

Output:

C:\Users\STUDENT>d:
D:\>cd java
D:\java>javac app.java
D:\java>appletviewer app.java
init()called
start()called
paint()called
paint()called
stop()called

Result:
2. Digital Clock using Applet

Digital.java:

import java.util.*;
import java.awt.*;
import java.applet.*;
import java.text.*;
/*<applet code=digital.class height=500 width=500></applet>*/
public class digital extends Applet implements Runnable
{
String s;
Thread t;
public void init()
{
t=new Thread(this);
t.start();
}
public void run()
{
while(true)
{
try
{
repaint();
t.sleep(1000);
}
catch(Exception e)
{

}
}
}
public void paint(Graphics g)
{
setBackground(Color.green);
//Date d=new Date();
//s=d.toString();
DateFormat d=new SimpleDateFormat("hh:mm:ss:aa");
String ds=d.format(new Date()).toString();
Font f=new Font("Times New Roman",Font.BOLD,30);
g.setFont(f);
//g.drawRect(10,10,360,50);
g.drawString(ds,250,250);
}
}

Output:

C:\Users\STUDENT>d:
D:\>cd java
D:\java>javac digital.java
D:\java>appletviewer digital.java

Result:

3. To display Graphical shapes using Applet viewer


Graphical Shapes.java:

import java.awt.*;
import java.applet.*;
/*<applet code=house.class height=350 width=350></applet>*/
public class house extends Applet
{
public void init()
{
setBackground(Color.cyan);
}
public void paint(Graphics g)
{
//draw the roof
g.setColor(Color.red);
int x[]={100,160,220};
int y[]={100,50,100};
Polygon poly=new Polygon(x,y,3);
g.fillPolygon(poly);
//draw the body of the house
g.setColor(Color.blue);
g.fillRect(100,100,120,120);
g.setColor(Color.black);
g.drawLine(100,220,220,220);
//draw the door and windows
g.setColor(Color.white);
g.fillRect(145,170,30,50);
g.fillRect(120,120,20,25);
g.fillRect(180,120,20,25);
//draw sun
g.setColor(Color.orange);
g.fillOval(240,30,50,50);
//draw chimney
g.setColor(Color.black);
g.fillRect(120,55,10,30);
}
}
Output:

C:\Users\STUDENT>d:
D:\>cd java
D:\java>javac house.java
D:\java>appletviewer house.java

Result:

4. To Display Graphical bar chart by passing parameters in applet


Graphical Barchart.java:

import java.awt.*;
import java.applet.*;
/*<applet code=chart.class height=400 width=400>
<param name=c1 value=110>
<param name=c2 value=150>
<param name=c3 value=100>
<param name=c4 value=170>
<param name=label1 value=1991>
<param name=label2 value=1992>
<param name=label3 value=1993>
<param name=label4 value=1994>
<param name=col value=4>
</applet>*/
public class chart extends Applet
{
int n=0;
String label[];
int value[];
public void init()
{
setBackground(Color.pink);
try
{
int n=Integer.parseInt(getParameter("col"));
label=new String[n];
value=new int[n];
label[0]=getParameter("label1");
label[1]=getParameter("label2");
label[2]=getParameter("label3");
label[3]=getParameter("label4");
value[0]=Integer.parseInt(getParameter("c1"));
value[1]=Integer.parseInt(getParameter("c2"));
value[2]=Integer.parseInt(getParameter("c3"));
value[3]=Integer.parseInt(getParameter("c4"));
}
catch(NumberFormatException e){}
}
public void paint(Graphics g)
{
for(int i=0;i<4;i++)
{
g.setColor(Color.black);
g.drawString(label[i],20,i*50+30);
g.setColor(Color.red);
g.fillRect(50,i*50+10,value[i],40);
}
}
}

Output:

C:\Users\STUDENT>d:
D:\>cd java
D:\java>javac chart.java
D:\java>appletviewer chart.java

Result:

5. Audio Clip Applet


import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/*<applet code="audio1" width="300" height="300"></applet>*/

public class audio1 extends Applet implements ActionListener


{
Button play,stop;
AudioClip audioClip;
public void init()
{
play = new Button("Play");
add(play);
play.addActionListener(this);
stop = new Button("Stop");
add(stop);
stop.addActionListener(this);
audioClip=getAudioClip(getCodeBase(),"abc.mp3");
}
public void actionPerformed(ActionEvent ae)
{
Button source=(Button)ae.getSource();
if(source.getLabel()=="Play")
{
audioClip.play();
}
else if(source.getLabel()=="Stop")
{
audioClip.stop();
}
}
}

Output:

6. To find factorial value of N using AWT high level event handling


Factorial.java:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=factorial.class height=100 width=200></applet>*/
public class factorial extends Applet implements ActionListener
{
Label l1;
TextField t1,t2;
Button b1;
public void init()
{
setLayout(new GridLayout(2,2));
l1 = new Label("Enter the value");
add(l1);
t1=new TextField();
add(t1);
b1=new Button("Calculate");
add(b1);
b1.addActionListener(this);
t2=new TextField();
t2=new TextField();
add(t2);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
int f=1,i;
int n=Integer.parseInt(t1.getText());
for(i=1;i<=n;i++)
f=f*i;
t2.setText(String.valueOf(f));
}
}
}
Output:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac factorial.java

D:\java>appletviewer factorial.java

Result:

7. To illustrate window closing using AWT low level event handling


Windowclosing.java:

import java.awt.*;
import java.awt.event.*;
public class cwindow
{
public static void main(String args[])
{
frame1 f=new frame1();
f.setBounds(100,100,300,200);
f.show();
}
}
class frame1 extends Frame
{
public frame1()
{
setTitle("Close button");
setSize(300,200);
setBackground(Color.red);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
}

Output:
C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac cwindow.java
Note: cwindow.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

D:\java>java cwindow

Result:

8. TCP based Network Communication


tcpserver.java

import java.net.*;

import java.io.*;

class tcpserver

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

ServerSocket ss=new ServerSocket(3000);

Socket s=ss.accept();

System.out.println("The server is read now");

DataInputStream dis=new DataInputStream(s.getInputStream());

PrintStream ps=new PrintStream(s.getOutputStream());

DataInputStream din=new DataInputStream(System.in);

while(true)

String st=dis.readLine();

System.out.println(st);

System.out.println("Type the message:");

st=din.readLine();

ps. println("server message:"+st);

tcpclient.java
import java.net.*;
import java.io.*;
class tcpclient
{
public static void main(String args[])throws IOException
{
InetAddress in=InetAddress.getLocalHost();
Socket s=new Socket(in,3000);
System.out.println("The client is read now()");
DataInputStream dis=new DataInputStream(s.getInputStream());
DataInputStream din=new DataInputStream(System.in);
PrintStream ps=new PrintStream(s.getOutputStream());
while(true)
{
System.out.println("Type the message");
String st=din.readLine();
ps.println("client msg:"+st);
st=dis.readLine();
System.out.println(st);
}
}
}
Output:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac tcpserver.java

D:\java>javac tcpclient.java

D:\java>java tcpserver

RECEIVED : hai

Enter the text :

welcome

client command prompt:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac tcpclient.java

D:\java>java tcpclient

Enter the text :

hai

From SERVER: welcome

Enter the text


9. UDP based Network Communication

udpserver.java

import java.net.*;
import java.io.*;
class udpserver
{
public static void main(String args[])throws Exception
{
DatagramSocket ss=new DatagramSocket(9876);
byte[]send1=new byte[200];
byte[]receive1=new byte[200];
while(true)
{
DatagramPacket rp=new DatagramPacket(receive1,receive1.length);
ss.receive(rp);
String s1=new String(rp.getData());
System.out.println("RECEIVED"+s1);
InetAddress ip=rp.getAddress();
int port=rp.getPort();
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the text");
String s2=b.readLine();
send1=s2.getBytes();
DatagramPacket sp=new DatagramPacket(send1,send1.length,ip,port);
ss.send(sp);
}
}
}
udpclient.java:

import java.net.*;
import java.io.*;
class udpclient
{
public static void main(String args[])throws Exception
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
DatagramSocket ds=new DatagramSocket();
InetAddress ipaddress=InetAddress.getByName("localhost");
byte[] send1=new byte[200];
byte[] receive1=new byte[200];
while(true)
{
System.out.println("Enter the text");
String s1=b.readLine();
send1=s1.getBytes();
DatagramPacket sp= new DatagramPacket(send1,send1.length,ipaddress,9876);
ds.send(sp);
DatagramPacket rp=new DatagramPacket(receive1,receive1.length);
ds.receive(rp);
String s2=new String(rp.getData());
System.out.println("From SERVER:"+s2);
}
}
}
Output:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac udpserver.java

D:\java>javac udpclient.java

D:\java>java udpserver

RECEIVEDhai

enter text

welcome

client command prompt:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac udpclient.java

D:\java>java udpclient

enter the text

hai

from SERVER:welcome

enter the text


10. To find sum of digit using RMI

sum.java

import java.rmi.*;
import java.rmi.*;
public interface sum extends Remote
{
public int print(int n) throws RemoteException;
}

sersum.java

import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class sersum extends UnicastRemoteObject implements sum
{
public sersum() throws RemoteException
{
super();
}
public int print(int n) throws RemoteException
{
int s=0;
while(n!=0)
{
s=s+n%10;
n=n/10;
}
return s;
}
public static void main(String args[]) throws RemoteException
{
try
{
sersum s=new sersum();
Naming.rebind("sum",s);
System.out.println("Server Ready!!!");
}
catch(Exception e)
{
}
}
}

clisum.java

import java.rmi.*;
import java.io.*;
public class clisum
{
public static void main(String args[])throws IOException
{
try
{
sum s=(sum)Naming.lookup("sum");
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter the number n to find the Sum:");
int n=Integer.parseInt(d.readLine());
int sum1=s.print(n);
System.out.println("The Sum of digits:"+sum1);
}
catch(Exception e)
{
System.out.println("Error in input!!!");
}
}
}
Output:

D:\java>javac sum.java

D:\java>javac sersum.java

D:\java>javac clisum.java

Note: clisum.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

D:\java>start rmiregistry

D:\java>java sersum

Server Ready!!!

D:\java>java clisum

Enter the number n to find the Sum:

327

The Sum of digits:12


11. To find total amount using RMI

inter.java

import java.io.*;

import java.rmi.*;

public interface inter extends Remote

public int mul(int a, int b) throws RemoteException;

sertotal.java

import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class sertotal extends UnicastRemoteObject implements inter
{
public sertotal() throws RemoteException
{
super();
}
public int mul(int a,int b) throws RemoteException
{
return (a*b);
}
public static void main(String args[]) throws RemoteException
{
try
{
sertotal x=new sertotal();
Naming.rebind("Amount",x);
System.out.println("Server Ready!!!");
}
catch(Exception e)
{
}
}
}

clitotal.java
import java.rmi.*;
import java.io.*;
public class clitotal
{
public static void main(String args[])throws IOException
{
try
{
inter obj=(inter)Naming.lookup("Amount");
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter Price:");
int a=Integer.parseInt(d.readLine());
System.out.println("Enter Quantity:");
int b=Integer.parseInt(d.readLine());
System.out.println("The Total Amount:"+obj.mul(a,b));
}
catch(Exception e)
{
System.out.println("Error in input!!!");
}
}
}
Output:

D:\java>javac inter.java

D:\java>javac sertotal.java

D:\java>javac clitotal.java

Note: clisum.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

D:\java>start rmiregistry

D:\java>java sertotal

Server Ready!!!

D:\java>java clitotal

Enter Price:

40

Enter Quantity:

30

The Total Amount:1200


12. To find EB Bill Calculation using RMI

ebbill.java

import java.io.*;

import java.rmi.*;

public interface ebbill extends Remote

public double cal(int units) throws RemoteException;

serebbill.java

import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class serebbill extends UnicastRemoteObject implements ebbill
{
public serebbill() throws RemoteException
{
super();
}
public double cal(int units) throws RemoteException
{
double bill=0;
if(units<100)
{
bill=units*1.20;
}
else if(units<300)
{
bill=100*1.20+(units-100)*2;
}
else if(units>300)
{
bill=100*1.20+200*2+(units-300)*3;
}
return bill;
}

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


{
try
{
serebbill eb=new serebbill();
Naming.rebind("Bill",eb);
System.out.println("Server Ready!!!");
}
catch(Exception e)
{
}
}
}

cliebbill.java
import java.rmi.*;
import java.io.*;
public class cliebbill
{
public static void main(String args[])throws IOException
{
try
{
ebbill e=(ebbill)Naming.lookup("Bill");
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter the Service Number:");
int sno=Integer.parseInt(d.readLine());
System.out.println("Enter the Name:");
String name=d.readLine();
System.out.println("Enter the Date:");
String date=d.readLine();
System.out.println("Enter the Unit:");
int units=Integer.parseInt(d.readLine());
double amount=e.cal(units);
System.out.println("EB Bill Calculation:");
System.out.println("~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Service No:"+sno);
System.out.println("Name:"+name);
System.out.println("Date:"+date);
System.out.println("No of Units:"+units);
System.out.println("Amount to Pay:"+amount);
}
catch(Exception e)
{
System.out.println("Error in input!!!");
}
}
}
Output:

D:\java>javac ebbill.java

D:\java>javac serebbill.java

D:\java>javac cliebbill.java

Note: cliebbill.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

D:\java>start rmiregistry

D:\java>java serebbill

Server Ready!!!

D:\java>java cliebbill

Enter the Service Number: 70645

Enter the Name: Raja

Enter the Date: 12/10/2021

Enter the Unit: 598

EB Bill Calculation:

~~~~~~~~~~~~~~~~~~~~~

Service No:70645

Name:Raja

Date:12/10/2021

No of Units:598

Amount to Pay:1414.0
13. To find biggest element of a array using HTML/Java script

big.html

<html>
<body>
<script type="text/javascript">
var counter;
var number;
var largest=Number.NEGATIVE_INFINITY;
for (counter = 1; counter <= 5; counter++)
{
number = window.prompt("Enter Any Five Numbers :"+counter+".");
number = parseInt(number);
if (number > largest) {
largest = number;
}
}
document.writeln("<h1>Largest number is " +largest+ "</h1>");
</script>
</body>
</html>

Output:
14. To find palindrome for the given number using HTML/Java Script

Palindrome.html

<html>
<head>
<script>
function Palindrome()
{
var rem, temp, final = 0;
var number = Number(document.getElementById("N").value);
temp = number;
while(number>0)
{
rem = number%10;
number = parseInt(number/10);
final = final*10+rem;
}
if(final==temp)
{
window.alert("The inputed number is Palindrome");
}
else
{
window.alert("The inputed number is not palindrome");
}
}
</script>
</head>
<body>
<br>
<h1>Whether a number is Palindrome or not</h1>
Enter The Number :<input type="text" name="n" id = "N" required/>
<hr color="cyan">
<br>
<center><button onClick="Palindrome()">CHECK</button>
</body>
</html>
Output:
15. To find length of the string using Generic Servlet

length.html

<html>

<head>

<title>Length of th String</title>

</head>

<body>

<h1 align="center">Length of the String</h1>

<form name="form1" method="post" action="len">

Enter the String:<input type="text" name="str">

<input type="submit" value="Submit">

</form>

</body>

</html>

len.java

import java.io.*;

import javax.servlet.*;

public class len extends GenericServlet

public void service(ServletRequest request, ServletResponse response)throws ServletException,


IOException

String s=request.getParameter("str");

PrintWriter pw=response.getWriter();

pw.println("Length of the String:"+s.length());

web.xml

<servlet>
<servlet-name>len</servlet-name>

<servlet-class>len</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>len</servlet-name>

<url-pattern>/len</url-pattern>

</servlet-mapping>

Output:
16. To compute factorial value of N using HTTP Servlet

FactorialServlet.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Factorial</title>
</head>
<body>
<form method="post" action="Facts">
<table>
<tr><td>Enter a value to find its factorial</td><td><input type="text" name="text1"/></td></tr>
<tr><td></td><td><input type="submit" value="ok"/></td></tr>
</table>
</form>
</body>
</html>
Facts.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Facts extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{

int num = Integer.parseInt(request.getParameter("text1"));


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(this.fact(num));
}
long fact(long a)
{
if (a <= 1)
return 1;
else
{
a = a * fact(a - 1);
return a;
}
}
}
web.xml:

<servlet>
<servlet-name>Facts</servlet-name>
<servlet-class>Facts</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Facts</servlet-name>
<url-pattern>/Facts</url-pattern>
</servlet-mapping>
Output:
18. To create cookies using servlet and jsp program

user.html

<html>

<head>

<meta charset="UTF-8">

<title> Insert title here</title>

</head>

<body>

<h1 align="center"> Create Cookie for Username </h1>

<form action="serv1" method="post">

Username: <input type="text" name="uname"><br>

<input type="submit" value "Create">

</form>

</body>

</html>

serv1.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class serv1 extends HttpServlet

protected void doPost(HttpServletRequest request, HttpServletResponse response)throws


ServletException, IOException

String un=request.getParameter("uname");

String pw=request.getParameter("pass");

Cookie ck = new Cookie("name",un);

Cookie ck1 = new Cookie("password",pw);

response.addCookie(ck);
response.sendRedirect("home1.jsp");

home1.jsp

<html>

<head>

<title> Insert title here</title>

</head>

<body>

<h1>Retrieving Cookie from browsers</h1>

<br>

<%

Cookie[] cks=request.getCookies();

for(Cookie ck:cks)

String cn=ck.getName();

String cv=ck.getValue();

%>

Cookie name: <b><%=cn %></b><br>

Cookie Value: <b><%=cv %></b><br>

<%

out.println("Hello"+cv+" Welcome to our web page!");

%>

</body>

</html>
web.xml

<servlet>

<servlet-name> serv1</servlet-name>

<servlet-class> serv1 </servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>serv1</servlet-name>

<url-pattern>/serv1</url-pattern>

</servlet-mapping>

Output:
19. To Count numbers of visitors using Servlet

visit.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class visit extends HttpServlet

static int count=0;

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws IOException,ServletException

response.setContentType("text/html");

PrintWriter pw=response.getWriter();

pw.print("<body bgcolor=orange>");

if(count==0)

pw.print("<cemter>");

pw.print("<h1>welcome to the first time</h1>");

count++;

else

pw.print("<center>");

pw.print("<h1>you hava visited"+count+"times</h1>");

count++;

pw.print("</center>");

pw.print("<body>");

}
}

web.xml

<servlet>

<servlet-name>visit</servlet-name>

<servlet-class>visit</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>visit</servlet-name>

<url-pattern>/visit</url-pattern>

</servlet-mapping>

Output:
20. To create a form and validate a password using Servlet

login.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Servlet implementation class LoginController
*/
public class login extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String un=request.getParameter("username");
String pw=request.getParameter("password");
if(un.equals("admin") && pw.equals("admin"))
{
response.sendRedirect("success.html");
return;
}
else
{
response.sendRedirect("error.html");
return;
}
}
}

web.xml

<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

error.html.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Invalid username or password
</body>
</html>

Login.html.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Sample login Example (try with username as "admin" and password as "admin" without quart )
<br> <br>
<form action="login" method="post">
Enter username :<input type="text" name="username"> <br>
Enter password :<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Login success
</body>
</html>

Output:
21. To find cube of a number using java beans

number.html

<html>

<body>

<h2 align="center"> FIND CUBE OF GIVEN NUMBER</h2>

<form action="cube.jsp">

Enter a Number: <input type="text" name="num">

<input type="submit" value="click">

</form>

</body>

<html>

calculator.java

package pl;
public class calculator
{
public int cube(int n)
{
return n*n*n;
}
}

cube.jsp

<jsp:useBean id="obj" class="pl.calculator"/>

<h2 align="center">CUBE OF A NUMBER</h2>

<%

int n=Integer.parseInt(request.getParameter("num"));

int m=obj.cube(n);

out.print("<b>cube of "+n+" is:</b> "+m);

%>

Output:
22. To convert an image in RGB to a GrayScale

Grayscale.java

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Grayscale
{
public static void main(String args[])throws IOException
{
BufferedImage img = null;
File f = null; //read image
try
{
f = new File("Penguins.jpg");
img = ImageIO.read(f);
}
catch(IOException e)
{
System.out.println(e);
} //get image width and height
int width = img.getWidth();
int height = img.getHeight(); //convert to grayscale
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
int p = img.getRGB(x,y);
int a = (p>>24)&0xff;
int r = (p>>16)&0xff;
int g = (p>>8)&0xff;
int b = p&0xff; //calculate average
int avg = (r+g+b)/3; //replace RGB value with avg
p = (a<<24) | (avg<<16) | (avg<<8) | avg;
img.setRGB(x, y, p); } } //write image
try
{
f = new File("Output.jpg");
ImageIO.write(img, "jpg", f);
}
catch(IOException e)
{
System.out.println(e);
} //main() ends here
}
}//class ends here

Output:

c:\Windows\System32>d:
D:\>cd java
D:\java>javac Grayscale.java
D:\java>java Grayscale

Output:
23.To Develop chat server using java

Server.java

import java.io.*;

import java.net.*;

public class GossipServer

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

ServerSocket sersock = new ServerSocket(3000);

System.out.println("Server ready for chatting");

Socket sock = sersock.accept( );

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

OutputStream ostream = sock.getOutputStream();

PrintWriter pwrite = new PrintWriter(ostream, true);

InputStream istream = sock.getInputStream();

BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

String receiveMessage, sendMessage;

while(true)

if((receiveMessage = receiveRead.readLine()) != null)

System.out.println(receiveMessage);

sendMessage = keyRead.readLine();

pwrite.println(sendMessage);

pwrite.flush();

}
Client.java

import java.io.*;

import java.net.*;

public class GossipClient

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

Socket sock = new Socket("127.0.0.1", 3000);

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

OutputStream ostream = sock.getOutputStream();

PrintWriter pwrite = new PrintWriter(ostream, true);

InputStream istream = sock.getInputStream();

BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

System.out.println("Start the chitchat, type and press Enter key");

String receiveMessage, sendMessage;

while(true)

sendMessage = keyRead.readLine(); // keyboard reading

pwrite.println(sendMessage); // sending to server

pwrite.flush(); // flush the data

if((receiveMessage = receiveRead.readLine()) != null) //receive from server

System.out.println(receiveMessage); // displaying at DOS prompt

}
Output:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac GossipServer.java

D:\java>javac GossipClient.java

D:\java>java GossipServer

Server ready for chatting

Hai

Client command prompt:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac GossipClient.java

D:\java>java GossipClient

Start the chitchat, type and press Enter key

hai

You might also like