0% found this document useful (0 votes)
177 views51 pages

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
177 views51 pages

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Life Cycle of an Applet

[Link]:

import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code=app height=500 width=500></applet>*/
public class app extends Applet
{
String msg;
public void init()
{
msg="int->";
setBackground([Link]);
[Link]("init()called");
}
public void start()
{
msg+="start->";
[Link]("start()called");
}
public void stop()
{
msg+="stop->";
[Link]("stop()called");
}
public void destory()
{
msg+="destory->";
[Link]("destroy()called");
}
public void paint(Graphics g)
{
msg+="paint->";
[Link]("paint()called");
[Link](msg,200,250);
}
}

Output:

C:\Users\STUDENT>d:
D:\>cd java
D:\java>javac [Link]
D:\java>appletviewer [Link]
init()called
start()called
paint()called
paint()called
stop()called

Result:
2. Digital Clock using Applet

[Link]:

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

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

Output:

C:\Users\STUDENT>d:
D:\>cd java
D:\java>javac [Link]
D:\java>appletviewer [Link]

Result:

3. To display Graphical shapes using Applet viewer


Graphical [Link]:

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

C:\Users\STUDENT>d:
D:\>cd java
D:\java>javac [Link]
D:\java>appletviewer [Link]

Result:

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


Graphical [Link]:

import [Link].*;
import [Link].*;
/*<applet code=[Link] 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([Link]);
try
{
int n=[Link](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]=[Link](getParameter("c1"));
value[1]=[Link](getParameter("c2"));
value[2]=[Link](getParameter("c3"));
value[3]=[Link](getParameter("c4"));
}
catch(NumberFormatException e){}
}
public void paint(Graphics g)
{
for(int i=0;i<4;i++)
{
[Link]([Link]);
[Link](label[i],20,i*50+30);
[Link]([Link]);
[Link](50,i*50+10,value[i],40);
}
}
}

Output:

C:\Users\STUDENT>d:
D:\>cd java
D:\java>javac [Link]
D:\java>appletviewer [Link]

Result:

5. Audio Clip Applet


import [Link].*;
import [Link].*;
import [Link].*;

/*<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);
[Link](this);
stop = new Button("Stop");
add(stop);
[Link](this);
audioClip=getAudioClip(getCodeBase(),"abc.mp3");
}
public void actionPerformed(ActionEvent ae)
{
Button source=(Button)[Link]();
if([Link]()=="Play")
{
[Link]();
}
else if([Link]()=="Stop")
{
[Link]();
}
}
}

Output:

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


[Link]:

import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code=[Link] 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);
[Link](this);
t2=new TextField();
t2=new TextField();
add(t2);
}
public void actionPerformed(ActionEvent ae)
{
if([Link]()==b1)
{
int f=1,i;
int n=[Link]([Link]());
for(i=1;i<=n;i++)
f=f*i;
[Link]([Link](f));
}
}
}
Output:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac [Link]

D:\java>appletviewer [Link]

Result:

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


[Link]:

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

Output:
C:\Users\STUDENT>d:

D:\>cd java

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

D:\java>java cwindow

Result:

8. TCP based Network Communication


[Link]

import [Link].*;

import [Link].*;

class tcpserver

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

ServerSocket ss=new ServerSocket(3000);

Socket s=[Link]();

[Link]("The server is read now");

DataInputStream dis=new DataInputStream([Link]());

PrintStream ps=new PrintStream([Link]());

DataInputStream din=new DataInputStream([Link]);

while(true)

String st=[Link]();

[Link](st);

[Link]("Type the message:");

st=[Link]();

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

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

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac [Link]

D:\java>javac [Link]

D:\java>java tcpserver

RECEIVED : hai

Enter the text :

welcome

client command prompt:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac [Link]

D:\java>java tcpclient

Enter the text :

hai

From SERVER: welcome

Enter the text


9. UDP based Network Communication

[Link]

import [Link].*;
import [Link].*;
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,[Link]);
[Link](rp);
String s1=new String([Link]());
[Link]("RECEIVED"+s1);
InetAddress ip=[Link]();
int port=[Link]();
BufferedReader b=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the text");
String s2=[Link]();
send1=[Link]();
DatagramPacket sp=new DatagramPacket(send1,[Link],ip,port);
[Link](sp);
}
}
}
[Link]:

import [Link].*;
import [Link].*;
class udpclient
{
public static void main(String args[])throws Exception
{
BufferedReader b=new BufferedReader(new InputStreamReader([Link]));
DatagramSocket ds=new DatagramSocket();
InetAddress ipaddress=[Link]("localhost");
byte[] send1=new byte[200];
byte[] receive1=new byte[200];
while(true)
{
[Link]("Enter the text");
String s1=[Link]();
send1=[Link]();
DatagramPacket sp= new DatagramPacket(send1,[Link],ipaddress,9876);
[Link](sp);
DatagramPacket rp=new DatagramPacket(receive1,[Link]);
[Link](rp);
String s2=new String([Link]());
[Link]("From SERVER:"+s2);
}
}
}
Output:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac [Link]

D:\java>javac [Link]

D:\java>java udpserver

RECEIVEDhai

enter text

welcome

client command prompt:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac [Link]

D:\java>java udpclient

enter the text

hai

from SERVER:welcome

enter the text


10. To find sum of digit using RMI

[Link]

import [Link].*;
import [Link].*;
public interface sum extends Remote
{
public int print(int n) throws RemoteException;
}

[Link]

import [Link].*;
import [Link].*;
import [Link].*;
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();
[Link]("sum",s);
[Link]("Server Ready!!!");
}
catch(Exception e)
{
}
}
}

[Link]

import [Link].*;
import [Link].*;
public class clisum
{
public static void main(String args[])throws IOException
{
try
{
sum s=(sum)[Link]("sum");
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter the number n to find the Sum:");
int n=[Link]([Link]());
int sum1=[Link](n);
[Link]("The Sum of digits:"+sum1);
}
catch(Exception e)
{
[Link]("Error in input!!!");
}
}
}
Output:

D:\java>javac [Link]

D:\java>javac [Link]

D:\java>javac [Link]

Note: [Link] 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

[Link]

import [Link].*;

import [Link].*;

public interface inter extends Remote

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

[Link]

import [Link].*;
import [Link].*;
import [Link].*;
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();
[Link]("Amount",x);
[Link]("Server Ready!!!");
}
catch(Exception e)
{
}
}
}

[Link]
import [Link].*;
import [Link].*;
public class clitotal
{
public static void main(String args[])throws IOException
{
try
{
inter obj=(inter)[Link]("Amount");
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter Price:");
int a=[Link]([Link]());
[Link]("Enter Quantity:");
int b=[Link]([Link]());
[Link]("The Total Amount:"+[Link](a,b));
}
catch(Exception e)
{
[Link]("Error in input!!!");
}
}
}
Output:

D:\java>javac [Link]

D:\java>javac [Link]

D:\java>javac [Link]

Note: [Link] 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

[Link]

import [Link].*;

import [Link].*;

public interface ebbill extends Remote

public double cal(int units) throws RemoteException;

[Link]

import [Link].*;
import [Link].*;
import [Link].*;
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();
[Link]("Bill",eb);
[Link]("Server Ready!!!");
}
catch(Exception e)
{
}
}
}

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

D:\java>javac [Link]

D:\java>javac [Link]

D:\java>javac [Link]

Note: [Link] 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

[Link]

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

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

[Link]

<html>
<head>
<script>
function Palindrome()
{
var rem, temp, final = 0;
var number = Number([Link]("N").value);
temp = number;
while(number>0)
{
rem = number%10;
number = parseInt(number/10);
final = final*10+rem;
}
if(final==temp)
{
[Link]("The inputed number is Palindrome");
}
else
{
[Link]("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

[Link]

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

[Link]

import [Link].*;

import [Link].*;

public class len extends GenericServlet

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


IOException

String s=[Link]("str");

PrintWriter pw=[Link]();

[Link]("Length of the String:"+[Link]());

[Link]

<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

[Link]:

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


"[Link]
<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>
[Link]:

import [Link].*;
import [Link].*;
import [Link].*;

public class Facts extends HttpServlet


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

int num = [Link]([Link]("text1"));


[Link]("text/html");
PrintWriter out = [Link]();
[Link]([Link](num));
}
long fact(long a)
{
if (a <= 1)
return 1;
else
{
a = a * fact(a - 1);
return a;
}
}
}
[Link]:

<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

[Link]

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

[Link]

import [Link].*;

import [Link].*;

import [Link].*;

public class serv1 extends HttpServlet

protected void doPost(HttpServletRequest request, HttpServletResponse response)throws


ServletException, IOException

String un=[Link]("uname");

String pw=[Link]("pass");

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

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

[Link](ck);
[Link]("[Link]");

[Link]

<html>

<head>

<title> Insert title here</title>

</head>

<body>

<h1>Retrieving Cookie from browsers</h1>

<br>

<%

Cookie[] cks=[Link]();

for(Cookie ck:cks)

String cn=[Link]();

String cv=[Link]();

%>

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

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

<%

[Link]("Hello"+cv+" Welcome to our web page!");

%>

</body>

</html>
[Link]

<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

[Link]

import [Link].*;

import [Link].*;

import [Link].*;

public class visit extends HttpServlet

static int count=0;

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws IOException,ServletException

[Link]("text/html");

PrintWriter pw=[Link]();

[Link]("<body bgcolor=orange>");

if(count==0)

[Link]("<cemter>");

[Link]("<h1>welcome to the first time</h1>");

count++;

else

[Link]("<center>");

[Link]("<h1>you hava visited"+count+"times</h1>");

count++;

[Link]("</center>");

[Link]("<body>");

}
}

[Link]

<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

[Link]

import [Link].*;
import [Link].*;
import [Link].*;
/**
* Servlet implementation class LoginController
*/
public class login extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String un=[Link]("username");
String pw=[Link]("password");
if([Link]("admin") && [Link]("admin"))
{
[Link]("[Link]");
return;
}
else
{
[Link]("[Link]");
return;
}
}
}

[Link]

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

[Link].

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

[Link].

<!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>
[Link]
<!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

[Link]

<html>

<body>

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

<form action="[Link]">

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

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

</form>

</body>

<html>

[Link]

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

[Link]

<jsp:useBean id="obj" class="[Link]"/>

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

<%

int n=[Link]([Link]("num"));

int m=[Link](n);

[Link]("<b>cube of "+n+" is:</b> "+m);

%>

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

[Link]

import [Link];
import [Link];
import [Link];
import [Link];
public class Grayscale
{
public static void main(String args[])throws IOException
{
BufferedImage img = null;
File f = null; //read image
try
{
f = new File("[Link]");
img = [Link](f);
}
catch(IOException e)
{
[Link](e);
} //get image width and height
int width = [Link]();
int height = [Link](); //convert to grayscale
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
int p = [Link](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;
[Link](x, y, p); } } //write image
try
{
f = new File("[Link]");
[Link](img, "jpg", f);
}
catch(IOException e)
{
[Link](e);
} //main() ends here
}
}//class ends here

Output:

c:\Windows\System32>d:
D:\>cd java
D:\java>javac [Link]
D:\java>java Grayscale

Output:
[Link] Develop chat server using java

[Link]

import [Link].*;

import [Link].*;

public class GossipServer

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

ServerSocket sersock = new ServerSocket(3000);

[Link]("Server ready for chatting");

Socket sock = [Link]( );

BufferedReader keyRead = new BufferedReader(new InputStreamReader([Link]));

OutputStream ostream = [Link]();

PrintWriter pwrite = new PrintWriter(ostream, true);

InputStream istream = [Link]();

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

String receiveMessage, sendMessage;

while(true)

if((receiveMessage = [Link]()) != null)

[Link](receiveMessage);

sendMessage = [Link]();

[Link](sendMessage);

[Link]();

}
[Link]

import [Link].*;

import [Link].*;

public class GossipClient

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

Socket sock = new Socket("[Link]", 3000);

BufferedReader keyRead = new BufferedReader(new InputStreamReader([Link]));

OutputStream ostream = [Link]();

PrintWriter pwrite = new PrintWriter(ostream, true);

InputStream istream = [Link]();

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

[Link]("Start the chitchat, type and press Enter key");

String receiveMessage, sendMessage;

while(true)

sendMessage = [Link](); // keyboard reading

[Link](sendMessage); // sending to server

[Link](); // flush the data

if((receiveMessage = [Link]()) != null) //receive from server

[Link](receiveMessage); // displaying at DOS prompt

}
Output:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac [Link]

D:\java>javac [Link]

D:\java>java GossipServer

Server ready for chatting

Hai

Client command prompt:

C:\Users\STUDENT>d:

D:\>cd java

D:\java>javac [Link]

D:\java>java GossipClient

Start the chitchat, type and press Enter key

hai

Common questions

Powered by AI

The conversion of an RGB image to Grayscale in Java, as demonstrated in the example, involves reading an image file into a BufferedImage object. The process iterates over each pixel, extracting the RGB components, and calculating the average value of the red, green, and blue components. This average is used to set the new grayscale color by setting each RGB component to the calculated average, effectively eliminating color information while retaining brightness levels. The modified pixel data is then written back to create a new grayscale image, which is saved to a file. This approach leverages Java's AWT and ImageIO classes for graphical manipulation and file operations .

Java RMI (Remote Method Invocation) facilitates executing methods on an object running on another JVM. It involves several crucial steps demonstrated in the examples. First, a remote interface is defined using the extends Remote keyword, specifying the method signatures, such as public int print(int n) throws RemoteException. The implementation of these methods is provided in a class that extends UnicastRemoteObject, handling computations like summing digits or multiplying numbers. A server binds this implementation object to a name using Naming.rebind(), making it accessible to clients. Clients lookup the remote objects using Naming.lookup() and invoke the remote methods, passing parameters and receiving results as if they were local method calls. This mechanism allows distributing computing resources and executing tasks across networked systems .

TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are two different network communication protocols, each having unique characteristics. In Java implementations, TCP is characterized by a connection-oriented protocol that requires establishing a connection between the server and the client before data transmission occurs, ensuring reliable communication. This is seen in the tcpserver and tcpclient Java classes, where a socket connection is established, and streams are used for reading and sending data . Conversely, UDP is connectionless, meaning data packets (datagrams) are sent without establishing a connection, allowing for potentially faster but less reliable communication, as seen in the udpserver and udpclient classes. Datagrams can be sent and received without prior handshaking, emphasizing speed and reduced overhead .

Rendering graphical shapes on a Java applet involves using the Graphics class to draw various shapes and elements. In the "house" applet example, the process begins in the paint() method where the Graphics object is used. Various shapes are drawn using specific functions: a Polygon object for the rooftop, fillRect() for rectangular components like the house body and windows, fillOval() for circular shapes like the sun, and drawLine() for lines. The setColor() function is frequently used to set different colors for distinct parts of the house, such as red for the roof and blue for the body. These components combine to create a visual representation of a house on the screen, showcasing the use of basic shapes to form complex graphics .

A digital clock is created using an applet by implementing the Runnable interface and rendering the current time repeatedly. The core elements of the implementation include initializing a thread in the init() method, which calls repaint() at regular intervals, such as every second. The paint() method handles drawing the current time string, formatted with DateFormat and displayed using the drawString() function within the Graphics object. The digital clock updates its display by sleeping for a given interval and calling repaint to refresh the graphics .

In applet-based animations such as a digital clock, synchronized threads ensure that time-dependent actions, such as updating the time display, occur without interference from other operations. By implementing the Runnable interface and using threading, the applet can periodically repaint its display in a controlled manner. The thread's run method typically includes a loop that calls repaint() at timed intervals, controlled using Thread.sleep(), to update the graphics. This approach ensures that the applet remains responsive and can continuously update the displayed time without being blocked by other processes or input events, maintaining smooth and accurate time animation .

In applets, parameters are passed using HTML <param> tags, which are then retrieved inside the applet using the getParameter() method. The applet structure involves an init() method to read these parameters (e.g., numerical data and labels for the bars) and store them in arrays. After capturing the values, the paint() method iterates over the data arrays to draw and fill rectangles representing each bar of the bar chart. Each rectangle starts with a certain offset and uses the color defined (often red or another distinct color) to make the bars visually distinct. Labels are also drawn relative to each bar to provide context .

The implementation of computing factorials using HTTP Servlets involves creating a servlet that receives HTTP POST requests with numerical input, processes the input to calculate the factorial, and returns the result. The servlet class extends HttpServlet and implements the doPost() method to handle incoming POST requests. It reads the input from the request object, performs the factorial computation recursively within a helper method, and sends the response to display the result. This approach leverages the stateless nature of HTTP and the scalability of servlets to handle multiple requests efficiently. Advantages include ease of deployment on web servers, scalability, and integration with web technologies, allowing for robust and responsive web-based applications .

High-level event handling in Java using AWT is implemented through interfaces like ActionListener, which enables handling user interactions with GUI components such as buttons. In the Audio Clip Applet, event handling is achieved by associating ActionListener with Button components for managing play and stop actions. The actionPerformed method is overridden to define specific tasks—playing or stopping audio based on button interaction. Similarly, in the Factorial Calculator Applet, an ActionListener attached to a Button handles calculation events, parsing input, computing factorials, and displaying results. These examples highlight how user inputs can trigger application logic defined in event handling methods, enabling interactive and dynamic GUI applications .

The life cycle of an applet in Java consists of several stages: init(), start(), paint(), stop(), and destroy(). These methods are invoked in a specific order during the applet's life cycle. The init() method initializes the applet, which is called once. The start() method is invoked every time the applet becomes active, typically when it is viewed or redisplayed. The paint() method is responsible for rendering the applet, drawing its graphics on the screen. The stop() method is called when the applet is no longer visible or active, and finally, the destroy() method is called to perform clean-up operations before the applet is destroyed. In the provided example, each method appends its name to a message string and outputs a message to the console to demonstrate its call order .

You might also like