Nothing Special   »   [go: up one dir, main page]

Java Nabin

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 24

Q1. Write an Example of exception handling.

public class ExceptionHandlingExample


{ public static void main(String[] args)
{ divideNumbers(10, 2);
divideNumbers(10, 0); divideNumbers(10,
"abc");
}

public static void divideNumbers(int num1, Object num2)


{ try {
int result = num1 / Integer.parseInt(num2.toString());
System.out.println("Result: " + result);

} catch (ArithmeticException e) {

System.out.println("Error: Cannot divide by zero.");

} catch (NumberFormatException e) {

System.out.println("Error: Please provide an integer for division.");

} catch (Exception e) {

System.out.println("An unexpected error occurred: " + e.getMessage());

} finally {

System.out.println("Operation complete.");

} Output:

Q2. Write a program using swing components to input principle, time and rate.
To calculate the simple interest when clicks on button and the process
result to be displayed on text box.
import javax.swing.*; import
java.awt.event.ActionEvent; import
java.awt.event.ActionListener;

public class SimpleInterestCalculator extends JFrame {

private JTextField txtPrincipal;


private JTextField txtTime;
private JTextField txtRate; private
JTextField txtResult; private
JButton btnCalculate;

public SimpleInterestCalculator()
{ super("Simple Interest Calculator");

txtPrincipal = new JTextField(10);


txtTime = new JTextField(10); txtRate =
new JTextField(10); txtResult = new
JTextField(10);
txtResult.setEditable(false); btnCalculate =
new JButton("Calculate");

setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

add(new JLabel("Principal:"));

add(txtPrincipal); add(new
JLabel("Time (Years):"));
add(txtTime); add(new JLabel("Rate
(%):")); add(txtRate);
add(btnCalculate); add(new
JLabel("Simple Interest:"));
add(txtResult);

btnCalculate.addActionListener(new ActionListener() {

@Override public void


actionPerformed(ActionEvent e)
{ calculateInterest();
}

});

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack(); setVisible(true);
}

private void calculateInterest() {

try {

float principal = Float.parseFloat(txtPrincipal.getText());


float time = Float.parseFloat(txtTime.getText()); float
rate = Float.parseFloat(txtRate.getText()); float interest =
(principal * time * rate) / 100;
txtResult.setText(String.format("%.2f", interest));

} catch (NumberFormatException nfe) {

JOptionPane.showMessageDialog(this, "Please enter valid numbers", "Input


Error", JOptionPane.ERROR_MESSAGE);

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new SimpleInterestCalculator();

});

Output:
Q3.Write a program to input 10 number into an array short them
ascending order.

import java.util.Arrays; import


java.util.Scanner;

public class SortArray { public static


void main(String[] args) { int[]
numbers = new int[10];
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 10 numbers:"); for
(int i = 0; i < numbers.length; i++)
{ System.out.print("Number " + (i + 1) + ":
"); numbers[i] = scanner.nextInt();
}

Arrays.sort(numbers);

System.out.println("Sorted numbers in ascending order:");


for (int number : numbers) {
System.out.println(number);

scanner.close();

} Output:

Q4.Write an example of interface implementation.


interface Animal {
void eat(); void
sleep();
}

class Dog implements Animal {

public void eat() {

System.out.println("Dog is eating");

public void sleep() {

System.out.println("Dog is sleeping");

public class InterfaceExample { public


static void main(String[] args)
{ Dog myDog = new Dog();
myDog.eat(); myDog.sleep();
}

Output:
Q5. Write an example of thread using interface runnable.

public class ThreadExample implements Runnable


{ public void run() { for (int i = 0; i < 5; i++) {
System.out.println("Running in thread: " + i);
try {
Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println(e);

}
}

public static void main(String[] args) {

ThreadExample obj = new ThreadExample();


Thread thread = new Thread(obj); thread.start();
}

Output:

Q6.Write an example of thread using class Thread


class MyThread extends Thread {
public void run() { for (int i =
0; i < 5; i++) {
System.out.println("MyThread: " + i);
try {
Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println(e);

public class ThreadClassExample { public


static void main(String[] args)
{ MyThread t = new MyThread();
t.start();

Output:

Q7.Write an example of multi thread.

class ThreadOne extends Thread {


public void run()
{ for (int i = 1; i <= 5;
i++) {
System.out.println("Thread One: " + i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(e);

class ThreadTwo extends Thread {

public void run()


{ for (int i = 1; i <= 5;
i++) {
System.out.println("Thread Two: " + i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(e);

}
public class MultiThreadExample
{ public static void main(String[] args)
{ ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
t1.start(); t2.start();
}

Output:

Q8. Write an example user define package.

Step-1:

ProjectRoot/

└── mypackage/

└── MyPackageClass.java

Step-2:
package mypackage;

public class MyPackageClass


{ public void display() {
System.out.println("This is a method from MyPackageClass.");

Step-3:

import mypackage.MyPackageClass;

public class UserClass { public static


void main(String[] args) {
MyPackageClass myObj = new MyPackageClass(); myObj.display();

}
}

Output:
Q9. Write TCP socket program for client-server chatting.
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) {

Socket connectionSocket = welcomeSocket.accept();


BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));

DataOutputStream outToClient = new


DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence); capitalizedSentence
= clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}

TCPClient.java: import
java.io.*; import
java.net.*; class
TCPClient {

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();
}

Output:

Q10. Write an applet program with proofing event handling.


import java.applet.Applet; import
java.awt.*;
import java.awt.event.*;
public class EventHandlingApplet extends Applet implements ActionListener { Button
button;
boolean toggle = true;

public void init() {


button = new Button("Click Me");
add(button);
button.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{ toggle = !toggle;
if (toggle) {
button.setForeground(Color.red);
} else {
button.setForeground(Color.blue);
}
repaint();
}

public static void main(String[] args) {


EventHandlingApplet applet = new EventHandlingApplet();
applet.init();
Frame frame = new Frame("EventHandlingApplet");
frame.add(applet); frame.setSize(300, 200);
frame.setVisible(true);
}
}
Output:

Q11. Write an example of RMI.

import java.rmi.Remote; import


java.rmi.RemoteException; import
java.rmi.server.UnicastRemoteObject; import
java.rmi.registry.LocateRegistry; import
java.rmi.registry.Registry;

// Remote interface interface Hello


extends Remote {
String sayHello() throws RemoteException;

// Implementation class HelloImpl extends UnicastRemoteObject


implements Hello { public HelloImpl() throws RemoteException {
super();
}

public String sayHello()


{ return "Hello, world!";
}

public static void main(String args[]) {


try {
HelloImpl obj = new HelloImpl();

// Bind this object instance to the name "Hello"

Registry registry = LocateRegistry.createRegistry(1099); // Default port


registry.bind("Hello", obj);

System.out.println("Hello Server ready.");

} catch (Exception e) {

System.out.println("Hello Server exception: " + e.toString());


e.printStackTrace();
}

}
Output:
Q12. Write an example of GridLayout.

import javax.swing.*; import


java.awt.*;
public class GridLayoutExample extends JFrame {
public GridLayoutExample() { setLayout(new
GridLayout(3, 2, 5, 5)); add(new
JButton("Button 1")); add(new JButton("Button
2")); add(new JButton("Button 3"));
add(new JButton("Button 4")); add(new
JButton("Button 5")); add(new JButton("Button
6"));
pack();

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

public static void main(String[] args)


{ new GridLayoutExample();
}

Output:

Q13. Write an example of GridBagLayout.


import javax.swing.*; import
java.awt.*;

public class GridBagLayoutExample extends JFrame {


public GridBagLayoutExample() { setLayout(new
GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

c.fill = GridBagConstraints.HORIZONTAL;

c.gridx = 0;

c.gridy = 0; add(new
JButton("Button 1"), c);

c.gridx = 1;

c.gridy = 0; add(new
JButton("Button 2"), c);

c.fill = GridBagConstraints.HORIZONTAL;

c.ipady = 20;

c.gridx = 0;

c.gridy = 1;

c.gridwidth = 2; add(new
JButton("Button 3"), c);

c.fill = GridBagConstraints.HORIZONTAL;

c.gridx = 0;

c.gridy = 2;

c.gridwidth = 1; add(new
JButton("Button 4"), c);
c.gridx = 1;

c.gridy = 2;

add(new JButton("Button 5"), c);

pack();

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

public static void main(String[] args)


{ new GridBagLayoutExample();
}

Output:

Q14. Write a program to display the IP address and local host name by using
inetfactory methods.

import java.net.InetAddress;

public class NetworkInfo {


public static void main(String[] args) {
try {
InetAddress inetAddress = InetAddress.getLocalHost();

System.out.println("IP Address: " + inetAddress.getHostAddress());

System.out.println("Hostname : " + inetAddress.getHostName());

} catch (Exception e) {

e.printStackTrace();

Q15. Write a program for simple calculator design and event.


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

public class SimpleCalculator extends JFrame implements ActionListener { private


JTextField inputScreen; private JButton[] numberButtons = new JButton[10]; private
JButton addButton, subButton, mulButton, divButton, decButton, equButton, delButton,
clrButton; private JPanel panel;

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


private char operator;

public SimpleCalculator()
{ this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
); this.setTitle("Simple Calculator"); this.setSize(420,
550); this.setLayout(null);

inputScreen = new JTextField();


inputScreen.setBounds(50, 25, 300, 50);
inputScreen.setEditable(false);

addButton = new JButton("+");


subButton = new JButton("-"); mulButton
= new JButton("*"); divButton = new
JButton("/"); decButton = new
JButton("."); equButton = new
JButton("="); delButton = new
JButton("Delete"); clrButton = new
JButton("Clear");

addButton.addActionListener(this);
subButton.addActionListener(this); mulButton.addActionListener(this);
divButton.addActionListener(this); decButton.addActionListener(this);
equButton.addActionListener(this); delButton.addActionListener(this);
clrButton.addActionListener(this);

panel = new JPanel(); panel.setBounds(50,


100, 300, 300); panel.setLayout(new
GridLayout(4, 4, 10, 10));

panel.add(addButton); panel.add(subButton);
panel.add(mulButton); panel.add(divButton);
panel.add(new JLabel("")); // Dummy labels for layout spacing
panel.add(new JLabel("")); panel.add(new JLabel(""));
panel.add(delButton);

panel.add(clrButton);

for (int i = 0; i < 10; i++) {

numberButtons[i] = new JButton(String.valueOf(i));


numberButtons[i].addActionListener(this);
}

for (int i = 1; i < 10; i++)


{ panel.add(numberButtons[i]);
}

panel.add(decButton);
panel.add(numberButtons[0]); panel.add(equButton);

this.add(panel);
this.add(inputScreen);
}

@Override public void


actionPerformed(ActionEvent e) {
for (int i = 0; i < 10; i++) {

if (e.getSource() == numberButtons[i])
{ inputScreen.setText(inputScreen.getText().concat(String.valueOf(i)));
return;
}

if (e.getSource() == decButton)
{ inputScreen.setText(inputScreen.getText().concat("."));
} else if (e.getSource() == addButton) {
num1 = Double.parseDouble(inputScreen.getText());
operator = '+'; inputScreen.setText(""); } else if
(e.getSource() == subButton) { num1 =
Double.parseDouble(inputScreen.getText()); operator
= '-'; inputScreen.setText(""); } else if
(e.getSource() == mulButton) { num1 =
Double.parseDouble(inputScreen.getText()); operator
= '*'; inputScreen.setText(""); } else if
(e.getSource() == divButton) { num1 =
Double.parseDouble(inputScreen.getText()); operator
= '/'; inputScreen.setText(""); } else if
(e.getSource() == equButton) { num2 =
Double.parseDouble(inputScreen.getText());
switch(operator) { case '+':
result = num1 + num2;

break;
case '-':
result = num1 -
num2; break;
case '*':
result = num1 * num2;

break;
case '/':
result = num1 / num2;
break;
}

inputScreen.setText(String.valueOf(result));
num1 = result;
} else if (e.getSource() == clrButton)
{ inputScreen.setText("");
} else if (e.getSource() == delButton) { String string =
inputScreen.getText(); inputScreen.setText(""); if
(string.length() > 0)
{ inputScreen.setText(string.substring(0, string.length() -
1));
}

public static void main(String[] args)


{ new
SimpleCalculator().setVisible(true);
}

Output:

You might also like