0% found this document useful (0 votes)
6 views

java_3LabCycle_fixed

The document contains a series of Java programs demonstrating various file operations, applet graphics, event handling, and GUI applications. Key programs include creating and reading files, drawing graphics like traffic signals and Olympic symbols, and implementing mouse and keyboard events in applets. Additionally, it features a job resume form and a story display application using Swing, showcasing user input and different font styles.

Uploaded by

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

java_3LabCycle_fixed

The document contains a series of Java programs demonstrating various file operations, applet graphics, event handling, and GUI applications. Key programs include creating and reading files, drawing graphics like traffic signals and Olympic symbols, and implementing mouse and keyboard events in applets. Additionally, it features a job resume form and a story display application using Swing, showcasing user input and different font styles.

Uploaded by

t20655234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

DATE:12/05/2024

PROGRAM NO:18

AIM: Create a file and write some contents into a file. Read the contents and display it.

PROGRAM:
import java.io.*; class
FileOperations {
public static void main(String[] args) throws IOException {
FileOutputStream fout = new FileOutputStream("myfile.txt");
DataInputStream din = new DataInputStream(System.in);
System.out.println("Enter the content (press # to quit):");

char ch;
while ((ch = (char) din.read()) != '#') {
fout.write(ch);
}
fout.close();

FileInputStream fin = new FileInputStream("myfile.txt");


System.out.println("Total file size to read (in bytes): " + fin.available());

int content;
while ((content = fin.read()) != -1) {
System.out.print((char) content);
}
fin.close();
}
}
OUTPUT:
DATE:13/05/2024

PROGRAM NO:19

AIM: Perform file copy and append operations.

PROGRAM:
import java.io.*;
class Copy {
public static void main(String[] args) throws IOException {

FileInputStream fin = new FileInputStream("myfile.txt");


FileOutputStream fout = new FileOutputStream("myfile1.txt");
int ch;
while ((ch = fin.read()) != -1) {
fout.write((char) ch);
}
fin.close();
System.out.println("Press # to stop appending to the file.");
DataInputStream din = new DataInputStream(System.in);
fout = new FileOutputStream("myfile1.txt", true); // Open in append mode
char inputChar;
while ((inputChar = (char) din.read()) != '#') {
fout.write(inputChar);
}

fout.close();
}
}
OUTPUT:
DATE:13/05/2024

PROGRAM NO:20

AIM: Using applet, draw


1. Traffic Signal

2. Olympics symbol

3. Desktop computer with all components

PROGRAM:
1.

import java.applet.Applet;
import java.awt.*;
/*
<applet code="TrafficSignal.class" width="300" height="400">
</applet>
*/
public class TrafficSignal extends Applet {
public void paint(Graphics g) {
setBackground(Color.WHITE);

g.setColor(Color.BLACK);
g.fillRect(100, 50, 100, 300);

g.setColor(Color.BLACK);
g.fillRect(140, 350, 20, 150);

g.setColor(Color.RED);
g.fillOval(125, 75, 50, 50);

g.setColor(Color.YELLOW);
g.fillOval(125, 175, 50, 50);

g.setColor(Color.GREEN);
g.fillOval(125, 275, 50, 50);
}
}
2.

import java.applet.Applet;
import java.awt.*;
/*
<applet code="OlympicsSymbol.class" width="400" height="300">
</applet>
*/
public class OlympicsSymbol extends Applet {
public void paint(Graphics g) {
setBackground(Color.WHITE);

Color darkYellow = new Color(204, 204, 0); // Darker yellow

g.setColor(Color.BLUE);
g.drawOval(100, 100, 50, 50);
g.setColor(Color.BLACK);
g.drawOval(160, 100, 50, 50);

g.setColor(Color.RED);
g.drawOval(220, 100, 50, 50);

g.setColor(darkYellow);
g.drawOval(130, 140, 50, 50);

g.setColor(Color.GREEN);
g.drawOval(190, 140, 50, 50);
}
}
3.

import java.applet.Applet;
import java.awt.*;
/*
<applet code="DesktopComputer.class" width="600" height="400">
</applet>
*/
public class DesktopComputer extends Applet {
public void paint(Graphics g) {
setBackground(Color.WHITE);
g.setColor(Color.BLACK);
g.drawRect(50, 50, 200, 150);
g.setColor(Color.GRAY);
g.fillRect(51, 51, 198, 148);
g.setColor(Color.BLACK);
g.drawRect(120, 200, 60, 20);
g.fillRect(140, 220, 20, 30);

g.setColor(Color.BLACK);
g.drawRect(300, 100, 100, 200);
g.setColor(Color.GRAY);
g.fillRect(301, 101, 98, 198);
g.setColor(Color.BLACK);
g.fillRect(320, 120, 60, 30);
g.fillRect(320, 180, 60, 20);
g.fillRect(320, 230, 60, 50);

g.setColor(Color.BLACK);
g.drawRect(50, 250, 200, 55);
g.setColor(Color.LIGHT_GRAY);
g.fillRect(51, 251, 198, 53);

g.setColor(Color.BLACK);
g.drawOval(260, 280, 40, 60);
g.setColor(Color.GRAY);
g.fillOval(261, 281, 38, 58);
g.setColor(Color.BLACK);
g.drawLine(280, 285, 280, 310);
g.setColor(Color.RED);
g.fillOval(350, 250, 20, 20);
g.setColor(Color.BLACK);
g.drawOval(350, 250, 20, 20);

g.setColor(Color.BLACK);
g.fillRect(310, 150, 10, 5);
g.fillRect(310, 160, 10, 5);
g.fillRect(310, 170, 10, 5);

g.setColor(Color.BLACK);
for (int i = 0; i < 10; i++) {
g.drawRect(60 + i * 18, 260, 15, 15);
g.drawRect(60 + i * 18, 280, 15, 15);
}
}
}

OUTPUT:
1.
2.

3.
DATE:15/05/2024

PROGRAM NO:21

AIM: Display your name and perform addition and multiplication of two numbers
by passing parameters in the applet window.

PROGRAM:
import java.awt.*;
import java.applet.*;
/*
<applet code="Name.java" width=500 height=300>
<param name=num1 value=20>
<param name=num2 value=57>
</applet>
*/
public class Name extends Applet {
String name;
int num1, num2;

public void start() {


name = "Tressa";
num1 = Integer.parseInt(getParameter("num1"));
num2 = Integer.parseInt(getParameter("num2"));
}

public void paint(Graphics g) {

g.drawString("My name is " + name, 10, 40);

int additionResult = num1 + num2;


g.drawString("Addition of " + num1 + " and " + num2 + " is " + additionResult, 10, 80);
int multiplicationResult = num1 * num2;
g.drawString("Multiplication of " + num1 + " and " + num2 + " is " +
multiplicationResult, 10, 120);
}
}

OUTPUT:
DATE:15/05/2024

PROGRAM NO:22

AIM: Display an image in the applet window

PROGRAM:
import java.awt.*;
import java.applet.*;
/*<applet code="ImageDisplay.class" width="400" height="300">
</applet>*/

public class ImageDisplay extends Applet {

private Image image;

public void init() {

image = getImage(getCodeBase(), "image.jpg");


}

public void paint(Graphics g) {


int x = 100;
int y = 100;
g.drawImage(image, x, y, this);
}
}
OUTPUT:
DATE:16/05/2024

PROGRAM NO:23

AIM: Create a moving banner in an applet window

PROGRAM:
import java.awt.*;
import java.applet.*;
/*
<applet code="simpleBanner" width=300 height=50>
</applet>
*/
public class simpleBanner extends Applet implements Runnable
{
String msg="A simple moving Banner.";
Thread t=null;
int state;
boolean stopFlag;

public void init()


{
setBackground(Color.cyan);
setForeground(Color.red);
}

public void start()


{
t=new Thread(this);
stopFlag=false;
t.start();
}
public void run()
{
char ch;
for( ; ; )
{
try
{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
if(stopFlag)
break;
}
catch(InterruptedException e)
{

}
}
}

public void stop()


{
stopFlag=true;
t=null;
}

public void paint(Graphics g)


{
g.drawString(msg,50,30);
}
}

OUTPUT:
DATE:17/05/2024

PROGRAM NO:24

AIM: a) Implement all the mouse events and key events in an applet window.
b) Draw the structure of a house, Doors and windows are to be represented using

scrollbars. When the scrollbars are moved, the color of the house is to be changed.

PROGRAM:
a)
b) import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Event.class" width="400" height="300">
</applet> */

public class Event extends Applet implements MouseListener, MouseMotionListener,


KeyListener {

private int mouseX, mouseY;


private String mouseStatus = "";
private String keyStatus = "";

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
setFocusable(true); // Ensure the applet has focus to receive key events
}

public void paint(Graphics g) {


Font font = new Font("Arial", Font.PLAIN, 20);
g.setFont(font);
g.drawString("Mouse: " + mouseStatus, 20, 20);
g.drawString("Key: " + keyStatus, 20, 40);
}

public void mouseClicked(MouseEvent e) {


mouseStatus = "Clicked";
repaint();
}
public void mousePressed(MouseEvent e) {
mouseStatus = "Pressed";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

public void mouseReleased(MouseEvent e) {


mouseStatus = "Released";
repaint();
}

public void mouseEntered(MouseEvent e) {


mouseStatus = "Entered";
repaint();
}

public void mouseExited(MouseEvent e) {


mouseStatus = "Exited";
repaint();
}

public void mouseDragged(MouseEvent e) {


mouseStatus = "Dragging";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

public void mouseMoved(MouseEvent e) {


mouseStatus = "Moving";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

public void keyPressed(KeyEvent e) {


keyStatus = "Pressed: " + e.getKeyChar();
repaint();
}

public void keyReleased(KeyEvent e) {


keyStatus = "Released: " + e.getKeyChar();
repaint();
}

public void keyTyped(KeyEvent e) {


keyStatus = "Typed: " + e.getKeyChar();
repaint();
}
}
c)
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

// <applet code="HouseApplet.class" width="300" height="400"></applet>

public class HouseApplet extends Applet implements AdjustmentListener

{
Scrollbar redScrollbar, greenScrollbar, blueScrollbar;
Color clr;

public void init()

{
redScrollbar = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256);
greenScrollbar = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, 256);
blueScrollbar = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256);

redScrollbar.addAdjustmentListener(this);
greenScrollbar.addAdjustmentListener(this);
blueScrollbar.addAdjustmentListener(this);

add(redScrollbar);
add(greenScrollbar);
add(blueScrollbar);
}

public void adjustmentValueChanged(AdjustmentEvent e)


{
int red = redScrollbar.getValue();
int green = greenScrollbar.getValue();
int blue = blueScrollbar.getValue();

clr = new Color(red, green, blue);

repaint();
}
public void paint(Graphics g)
{

g.setColor(clr);
g.fillRect(75, 150, 150, 150);
g.setColor(Color.BLACK);
g.drawRect(75, 150, 150, 150);

g.setColor(Color.RED);
int[] xPoints = {75, 150, 225};
int[] yPoints = {150, 75, 150};
g.fillPolygon(xPoints, yPoints, 3);

g.setColor(Color.DARK_GRAY);
g.fillRect(140, 230, 40, 70);

g.setColor(Color.CYAN);
g.fillRect(90, 180, 30, 30);
g.fillRect(180, 180, 30, 30);

g.setColor(Color.BLACK);
g.drawLine(105, 180, 105, 210);
g.drawLine(90, 195, 120, 195);
g.drawLine(195, 180, 195, 210);
g.drawLine(180, 195, 210, 195);
}
}

OUTPUT:
a)

b)
DATE:17/05/2024

PROGRAM NO:25

AIM: Prepare a job resume with required fields.When you click on the submit button , the
summary of entered values are to be displayed in a text area.

PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JobResumeForm extends JFrame implements ActionListener {

private JTextField nameField, emailField, phoneField;


private JTextArea experienceArea;
private JButton submitButton;

public JobResumeForm() {
setTitle("Job Resume Form");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(5, 2));

JLabel nameLabel = new JLabel("Name:");


nameField = new JTextField();
JLabel emailLabel = new JLabel("Email:");
emailField = new JTextField();
JLabel phoneLabel = new JLabel("Phone:");
phoneField = new JTextField();
JLabel experienceLabel = new JLabel("Work Experience:");
experienceArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(experienceArea);
submitButton = new JButton("Submit");

add(nameLabel);
add(nameField);
add(emailLabel);
add(emailField);
add(phoneLabel);
add(phoneField);
add(experienceLabel);
add(scrollPane);
add(new JLabel()); add(submitButton);

submitButton.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == submitButton) {

String name = nameField.getText();


String email = emailField.getText();
String phone = phoneField.getText();
String experience = experienceArea.getText();
JTextArea summaryArea = new JTextArea();
summaryArea.setEditable(false);
summaryArea.append("Name: " + name + "\n");
summaryArea.append("Email: " + email + "\n");
summaryArea.append("Phone: " + phone + "\n");
summaryArea.append("Work Experience: \n" + experience);

JOptionPane.showMessageDialog(this, summaryArea, "Resume Summary",


JOptionPane.INFORMATION_MESSAGE);

nameField.setText("");
emailField.setText("");
phoneField.setText("");
experienceArea.setText("");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JobResumeForm().setVisible(true);
}
});
}
}
OUTPUT:
DATE:17/05/2024

PROGRAM NO:26

AIM: Develop a swing program that displays a story (minimum 5 sentences) in different
fonts using labels.

PROGRAM:
import javax.swing.*;
import java.awt.*;
public class StoryDisplay extends JFrame {

public StoryDisplay() {
setTitle("Story Display");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(5, 1));
String[] sentences = {
"Beneath the crystal waves of the Enchanted Sea, a mermaid named Lyra discovered a
sunken city.",
" Guided by a map etched in pearls, she ventured through the coral-covered ruins.",
"There, she found an ancient trident that pulsed with untold power.",
" As she grasped it, the spirit of an old king appeared, pleading for her to restore his
kingdom.",
" With the trident's magic, Lyra revived the city, bringing life and light back to the
depths."
};
Font[] fonts = {
new Font("Serif", Font.BOLD, 18),
new Font("SansSerif", Font.ITALIC, 20),
new Font("Monospaced", Font.PLAIN, 16),
new Font("Dialog", Font.BOLD + Font.ITALIC, 22),
new Font("Arial", Font.PLAIN, 18)
};
for (int i = 0; i < 5; i++) {
JLabel label = new JLabel(sentences[i]);
label.setFont(fonts[i]);
add(label);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new StoryDisplay().setVisible(true);
}
});
}
}

OUTPUT:
DATE:19/05/2024

PROGRAM NO:27

AIM: Develop a swing program with two text fields for accepting username and password.
When you click a submit button, a dialog box is to be displayed with a Welcome message by
specifying the username and password.

PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class LoginDialog extends JFrame implements ActionListener {


private JTextField usernameField;
private JPasswordField passwordField;

public LoginDialog() {
setTitle("Login");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(3, 2));

JLabel usernameLabel = new JLabel("Username:");


usernameField = new JTextField();
JLabel passwordLabel = new JLabel("Password:");
passwordField = new JPasswordField();
JButton submitButton = new JButton("Submit");

add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
add(new JLabel()); // Empty cell for spacing
add(submitButton);

submitButton.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


if (e.getActionCommand().equals("Submit")) {
String username = usernameField.getText();
char[] password = passwordField.getPassword();

String passwordString = new String(password);

if (username.isEmpty() || passwordString.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please enter both username and password.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}

JOptionPane.showMessageDialog(this, "Welcome, " + username + "!", "Login Successful",


JOptionPane.INFORMATION_MESSAGE);

usernameField.setText("");
passwordField.setText("");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LoginDialog().setVisible(true);
}
});
}
}

OUTPUT:
DATE:20/05/2024

PROGRAM NO:28

AIM: Using Swing, display 3 faces namely joyful, sad and angry faces while clicking 3
different named buttons

PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FaceButton extends JFrame {


public FaceButton() {
initUI();
}
private void initUI() {
JPanel panel = new JPanel(new GridLayout(3, 1));

JButton joyButton = new JButton("Joyful");


JButton sadButton = new JButton("Sad");
JButton angryButton = new JButton("Angry");

joyButton.addActionListener(e -> showFace(new JoyFace(), "Joyful"));


sadButton.addActionListener(e -> showFace(new SadFace(), "Sad"));
angryButton.addActionListener(e -> showFace(new AngryFace(), "Angry"));

panel.add(joyButton);
panel.add(sadButton);
panel.add(angryButton);

add(panel);
setTitle("Face Button");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

private void showFace(Face face, String title) {


JOptionPane.showMessageDialog(null, face, title, JOptionPane.PLAIN_MESSAGE);
}

private abstract class Face extends JPanel {


public Face() {
setPreferredSize(new Dimension(200, 200));
setBackground(Color.WHITE);
}

protected void drawFaceOutline(Graphics2D g2d, Color color) {


g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(5));
g2d.setColor(color);
g2d.fillOval(50, 50, 100, 100);
g2d.setColor(Color.BLACK);
g2d.drawOval(50, 50, 100, 100);
}
}

private class JoyFace extends Face {


protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
drawFaceOutline(g2d, Color.YELLOW);
drawEyes(g2d, Color.BLACK);
g2d.setStroke(new BasicStroke(3));
g2d.drawArc(75, 100, 50, 30, 180, 180);
}
}

private class SadFace extends Face {


protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
drawFaceOutline(g2d, Color.YELLOW);
drawEyes(g2d, Color.BLACK);
g2d.setStroke(new BasicStroke(3));
g2d.drawArc(75, 100, 50, 30, 0, 180);
}
}

private class AngryFace extends Face {


protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
drawFaceOutline(g2d, Color.RED);
drawEyes(g2d, Color.BLACK);
g2d.setStroke(new BasicStroke(3));
g2d.drawLine(70, 60, 85, 65);
g2d.drawLine(110, 65, 125, 60);
g2d.drawArc(80, 110, 40, 20, 0, 180);
}
}
private void drawEyes(Graphics2D g2d, Color color) {
g2d.setColor(color);
g2d.fillOval(75, 75, 20, 20);
g2d.fillOval(105, 75, 20, 20);
}

public static void main(String[] args) {


EventQueue.invokeLater(() -> {
FaceButton faceButton = new FaceButton();
faceButton.setVisible(true);
});
}
}

OUTPUT:
DATE:21/05/2024

PROGRAM NO:29

AIM: Using swing, create a simple calculator.

PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator implements ActionListener {


private JFrame frame;
private JTextField textField;
private JButton[] numberButtons;
private JButton[] functionButtons;
private JButton addButton, subButton, mulButton, divButton, decButton, equButton,
clrButton;
private JPanel buttonPanel;

private Font myFont = new Font("Ink Free", Font.BOLD, 30);

private double num1 = 0, num2 = 0, result = 0;


private char operator;public Calculator() {

frame = new JFrame("Calculator");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 450);
frame.setLayout(new BorderLayout());

textField = new JTextField();


textField.setFont(myFont);
textField.setEditable(false);
frame.add(textField, BorderLayout.NORTH);

numberButtons = new JButton[10];


for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
numberButtons[i].setFont(myFont);
numberButtons[i].setFocusable(false);
}

functionButtons = new JButton[7];


addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
decButton = new JButton(".");
equButton = new JButton("=");
clrButton = new JButton("Clr");

functionButtons[0] = addButton;
functionButtons[1] = subButton;
functionButtons[2] = mulButton;
functionButtons[3] = divButton;
functionButtons[4] = decButton;
functionButtons[5] = equButton;
functionButtons[6] = clrButton;

for (JButton button : functionButtons) {


button.addActionListener(this);
button.setFont(myFont);
button.setFocusable(false);
}

buttonPanel = new JPanel();


buttonPanel.setLayout(new GridLayout(5, 4, 10, 10));

buttonPanel.add(numberButtons[1]);
buttonPanel.add(numberButtons[2]);
buttonPanel.add(numberButtons[3]);
buttonPanel.add(addButton);
buttonPanel.add(numberButtons[4]);
buttonPanel.add(numberButtons[5]);
buttonPanel.add(numberButtons[6]);
buttonPanel.add(subButton);
buttonPanel.add(numberButtons[7]);
buttonPanel.add(numberButtons[8]);
buttonPanel.add(numberButtons[9]);
buttonPanel.add(mulButton);
buttonPanel.add(decButton);
buttonPanel.add(numberButtons[0]);
buttonPanel.add(equButton);
buttonPanel.add(divButton);
buttonPanel.add(clrButton);

frame.add(buttonPanel, BorderLayout.CENTER);

frame.setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}

public void actionPerformed(ActionEvent e) {


for (int i = 0; i < 10; i++) {
if (e.getSource() == numberButtons[i]) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
}
if (e.getSource() == decButton) {
textField.setText(textField.getText().concat("."));
}
if (e.getSource() == addButton) {
num1 = Double.parseDouble(textField.getText());
operator = '+';
textField.setText(textField.getText() + " + ");
}
if (e.getSource() == subButton) {
num1 =Double.parseDouble(textField.getText());
operator = '-';
textField.setText(textField.getText() + " - ");
}
if (e.getSource() == mulButton) {
num1 = Double.parseDouble(textField.getText());
operator = '*';
textField.setText(textField.getText() + " * ");
}
if (e.getSource() == divButton) {
num1 = Double.parseDouble(textField.getText());
operator = '/';
textField.setText(textField.getText() + " / ");
}
if (e.getSource() == equButton) {
String[] tokens = textField.getText().split(" ");
num1 = Double.parseDouble(tokens[0]);
operator = tokens[1].charAt(0);
num2 = Double.parseDouble(tokens[2]);

switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
textField.setText(String.valueOf(result));
num1 = result;
}
if (e.getSource() == clrButton) {
textField.setText("");
textField.repaint();
}
}
}

OUTPUT:
DATE:22/05/2024

PROGRAM NO:30

AIM: Develop a client server application using a) TCP and b) UDP where the server
performs some mathematical operation on a number received from the client side

PROGRAM:
a) TCP
import java.io.*;
import java.net.*;

public class TCPServer {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(1234); // Create server socket
System.out.println("Server started. Waiting for client...");

Socket socket = serverSocket.accept();


System.out.println("Client connected.");

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

String numberStr = in.readLine();


double number = Double.parseDouble(numberStr);

double result = number * number;

out.println(result);
System.out.println("Result sent to client: " + result);

in.close();
out.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;

public class TCPClient {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 1234); // Connect to server
System.out.println("Connected to server.");

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

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


System.out.print("Enter a number: ");
String numberStr = reader.readLine();

out.println(numberStr);

String resultStr = in.readLine();


double result = Double.parseDouble(resultStr);
System.out.println("Result received from server: " + result);

in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

OUTPUT:
b) UDP
import java.io.*;
import java.net.*;

public class UDPServer {


public static void main(String[] args) {
try {
DatagramSocket serverSocket = new DatagramSocket(1234); // Create server socket
System.out.println("Server started. Waiting for client...");

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);

serverSocket.receive(receivePacket);
String numberStr = new String(receivePacket.getData(), 0, receivePacket.getLength());
double number = Double.parseDouble(numberStr);
System.out.println("Number received from client: " + number);

double result = number * number;

byte[] sendData = String.valueOf(result).getBytes();

InetAddress clientAddress = receivePacket.getAddress();


int clientPort = receivePacket.getPort();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,


clientAddress, clientPort);

serverSocket.send(sendPacket);
System.out.println("Result sent to client: " + result);

serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
try {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost");

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


System.out.print("Enter a number: ");
String numberStr = reader.readLine();

byte[] sendData = numberStr.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,


serverAddress, 1234);

clientSocket.send(sendPacket);
System.out.println("Number sent to server: " + numberStr);

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);
clientSocket.receive(receivePacket);
String resultStr = new String(receivePacket.getData(), 0, receivePacket.getLength());
double result = Double.parseDouble(resultStr);
System.out.println("Result received from server: " + result);

clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

OUTPUT:

You might also like