Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

1. i)Write a java program that prints all real solutions to the quadratic equation ax 2 +bx+c=0.

import java.io.*;
import java.util.Scanner;

public class Quadratic {


public static void main(String[] args)
{
int a,b,c;
double root1,root2;
System.out.println(" Enter the cofficients: ");
Scanner in = new Scanner(System.in);
a = in.nextInt();
b = in.nextInt();
c=in.nextInt();
double d =b*b-4*a*c;
System.out.println(" Determinant = "+d);

if(d>0)
{
root1=(-b+Math.sqrt(d))/(2*a);
root2=(-b-Math.sqrt(d))/(2*a);
System.out.println("The root are real and difference");
System.out.format("root1=%.2f and root2%.2f",root1,root2);
}

else if(d==0)
{
root1=root2=-b/(2*a);
System.out.println("The root are real and equal");
System.out.format("root1=root2=%.2f ",root1);
}
else
{
double real=-b/(2*a);
double imaginary =Math.sqrt(-d)/(2*a);
System.out.println("The root are imaginary");
System.out.format("root1=%.2f + %.2f ",real,imaginary);
System.out.format("/n root2=%.2f .%2fi ",real,imaginary);
}
}
}

ii) Fibonacci series is a series of integers, where Nth term is equal to the sum of N-1 th and N-2 th (last two
terms). The first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent term is the sum
of the previous two terms. Write a program in Java to print Fibonacci series without recursion.

import java.util.Scanner;

public class Fibonacci {


public static void main(String args[ ]) {
Scanner input=new Scanner(System.in);
int i,a=0,b=1,c=0,n;

System.out.print("Enter value of n: ");


n = input.nextInt();
System.out.print("Fibonaccie Series is:");
System.out.print(a);
System.out.print(" "+b);
for(i=0;i<n-2;i++) {
c=a+b;
a=b;
b=c;
System.out.print(" "+c);
}
System.out.println();
System.out.print(n+"th number of the series is: "+c);
}
}

2. i) Write a java program for sorting a given list of names in ascending order.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NameSorter {


public static void main(String[] args) {
List<String> names = new ArrayList<>();

names.add("John");
names.add("Alice");
names.add("Bob");
names.add("Eve");
names.add("Charlie");

Collections.sort(names);

System.out.println("Sorted Names in Ascending Order:");


for (String name : names) {
System.out.println(name);
}
}
}

ii) Write a program that prompts the user for an integer and then prints out all prime
numbers up to that integer.

import java.util.*;
class PrimeNumbers
{
public static void main(String[] args)
{
int n;
int flag;
Scanner s=new Scanner(System.in);
System.out.print("Enter a number: ");
n = s.nextInt();
System.out.print("The prime numbers are : ");

for(int i=2;i<n;i++)
{
if(i%j==0)
flag=1;

if(flag==0)
System.out.print(i+" ");
}
}
}
3. i) Write a Java program to Multiply two given matrices.

import java.io.*
import java.util.*;

public class matrix


{
public static void main(String args[])
{
int p,q,r,s;
Scanner n = new Scanner(System.in);

System.out.println("Enter row of first matrix:");


p = n.nextInt();
System.out.println("Enter column of first matrix:");
q = n.nextInt();
System.out.println("Enter row of second matrix:");
r = n.nextInt();
System.out.println("Enter column of first matrix:");
s=n.nextInt();

if(q!=r)
{
System.out.println("Matrix multiplication is not possible");
}
else
{
int a[][]=new int[p][q];
int b[][]=new int[r][s];
int c[][]=new int[p][s];

System.out.println("Enter the elements of first matrix:");

for(int i=0;i<p;i++)
{
for(int j=0;j<q;j++)
{
a[i][j]=n.nextInt();
}
}

System.out.println("First matrix:");

for(int i=0;i<p;i++)
{
for(int j=0;j<q;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}

System.out.println("Enter the elements of first matrix:");

for(int i=0;i<r;i++)
{
for(int j=0;j<s;j++)
{
b[i][j]=n.nextInt();
}
}

System.out.println("Second matrix:"); for(int i=0;i<p;i++)


{
for(int j=0;j<q;j++)
{
System.out.print(b[I][j]+" ");
}
System.out.println();
}

System.out.println("The multiplied matrix is:");


for(int i=0;i<p;i++)
{
for(int j=0;j<s;j++)
{
c[i][j]=0;

for(int k=0;k<q;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}
}

ii) Write a java program to find the number is Armstrong number.

import java.util.Scanner;

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();

if (isArmstrongNumber(number)) {
System.out.println(number + " is an Armstrong number.");
}
else {
System.out.println(number + " is not an Armstrong number.");
}
}

public static boolean isArmstrongNumber(int number) {


int originalNumber = number;
int numberOfDigits = String.valueOf(number).length();
int sum = 0;

while (number > 0) {


int digit = number % 10;
sum += Math.pow(digit, numberOfDigits);
number /= 10;
}

return originalNumber == sum;


}
}

4. Prepare an Electricity bill using Java. Create a class with the following members: Consumer number,
Consumer name, previous month reading, current month reading, type of EB connection.
Calculate the domestic connection bill amount using the following tariff:

First 150 units – Rs. 2per unit


151-250 units – Rs. 3.50 per unit
251- 500 units – Rs. 4.50 per unit
>500 units – Rs. 6 per unit

import java.io.*;
import java.util.*;

class EbBill
{
public static void main(String args[])
{
double amt;
Scanner sc = new Scanner(System.in);

System.out.println("Enter you cno:");


int cno = sc.nextInt();

System.out.println("Enter you name:");


String name = sc.next();

System.out.println("Enter your previous reading:");


int preading = sc.nextInt();

System.out.println("Enter your current reading:");


int creading = sc.nextInt();

System.out.println("Enter your
connection\n1.Domestic\n2.Commercial:");
int type = sc.nextInt();

double units = creading - preading;


doubled dunits;
dunits = units - 100;

switch(type)
{
case 1:
{
if(dunits <= 150)
amt = units * 2;

else if(dunits <= 250 && dunits > 150)


amt = 100 + (dunits * 3.50);

else if(dunits <= 500 && dunits >=251)


amt = 100 + (dunits * 4.50);
else
amt = 100 + (dunits * 6);

System.out.println("Customer no:"+cno+"\nCustomer
name:"+name+"\nunits:"+units+"\nBill amt:"+amt);
break;
}
default:
System.out.println("Customer no"+cno+"\nCustomername"+name);
}
sc.close();
}
}
5. Develop a Java application using packages to implement the following currency converter
– Dollar to Indian Rupees, Euro to Indian Rupees, and vice versa.

CONV-1:

package pack1;
import java.util.*;

public class Conv1


{
Scanner sc=new Scanner(System.in);

public void convert1(int inr)


{
System.out.println("Enter the type of conversion\n 1.INRUSD\n 2.INR-EURO\n
3.INR-YEN\n");
int type=sc.nextInt();

switch(type)
{
case 1:
double usd;
usd=inr/83.0;
System.out.println("INR="+inr+" is USD="+usd);
break;
case 2:
double eur;
eur=inr/90.0;
System.out.println("INR="+inr+" is EUR="+eur);
break;
case 3:
double yen;
yen=inr*1.76;
System.out.println("INR="+inr+" is YEN="+yen);
break;
}
}

public void convert2(char choice)


{
if(choice=='a')
{
System.out.println("Enter USD value");
double usd = sc.nextInt();
double inr;
inr = usd * 83;
System.out.println("USD="+usd+" is INR="+inr);
}
else if(choice=='b')
{
System.out.println("Enter EUR value");
double eur = sc.nextInt();
double inr;
inr = eur * 90;
System.out.println("EUR="+eur+" is INR="+inr);
}
else
{
System.out.println("Enter YEN value");
double yen = sc.nextInt();
double inr;
inr = yen * 1.76;
System.out.println("YEN="+yen+" is INR="+inr);
}
}
}

CURRENCY:

import pack1.Conv1;
import java.util.*;

public class Currency


{
public static void main(String args[])
{
char opt;
Conv1 c1 = new Conv1();
Conv2 c2 = new Conv2();
Conv3 c3 = new Conv3();
Scanner sc = new Scanner(System.in);

System.out.println("Select the option\na.INR-others\nb.othersINR\n");


opt=sc.next().charAt(0);

if(opt=='a')
{
System.out.println("Enter the INR value in Rs.");
int inr = sc.nextInt();
c1.convert1(inr);
}

else
{
System.out.println("Select the option\na.USD\nb.EUR\nc.YEN\n");
char choice = sc.next().charAt(0);
c1.convert2(choice);
}
}
}

6. i) Develop a Java application using packages to implement the following time converter (hours to
minutes, seconds and vice versa)
package timeconverter;

public class TimeConverter {


public static int hoursToMinutes(int hours) {
return hours * 60;
}

public static int hoursToSeconds(int hours) {


return hours * 3600;
}

public static int minutesToHours(int minutes) {


return minutes / 60;
}

public static int secondsToHours(int seconds) {


return seconds / 3600;
}

public static void main(String[] args) {


int hours = 2;
int minutes = 120;
int seconds = 7200;
System.out.println(hours + " hours is equal to " + hoursToMinutes(hours) + "
minutes.");
System.out.println(hours + " hours is equal to " + hoursToSeconds(hours) + "
seconds.");
System.out.println(minutes + " minutes is equal to " + minutesToHours(minutes) +
" hours.");
System.out.println(seconds + " seconds is equal to " + secondsToHours(seconds) +
" hours.");
}
}

ii) Write a Java program for sorting a given list of names in ascending order

import java.util.*;

class StringSorting
{
void sortStrings()
{
Scanner s = new Scanner(System.in);

System.out.println("Enter number of strings: ");


int n = s.nextInt();
String[] str = new String[n];
System.out.println("Enter strings: ");

for(int i = 0; i < n; i++)


{ str[i] = new String(s.next()); }

for(int i = 0; i < n; i++)


{
for(int j = i+1; j < n; j++)
{
if(str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j]; str[j] = temp;
}
}
}

System.out.println("Sorted list of strings is:");


for(int i = 0; i < n ; i++)
{
System.out.println(str[i]);
}
}
}

class Strings
{
public static void main(String[] args)
{
StringSorting obj = new StringSorting();
obj.sortStrings();
}
}
7. Develop a java application with Employee class with Emp_name, Emp_id, Address, Mail_id, Mobile_no
as members. Inherit the classes, Programmer, Associate Professor from employee class. Add Basic Pay (BP)
as the member of all the inherited classes with 98% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1%
of BP for staff club fund. Generate pay slips for the employees with their gross and net salary.

import java.io.*;
import java.util.*;
import java.lang.*;

class Employee
{
String name, address,mail, mobile;
int id;
float da,hra,pf,scf,gross,net;
float b;

void getData()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter name:");
name = sc.next();

System.out.println("Enter id:");
id = sc.nextInt();

System.out.println("Enter address:");
address = sc.next();

System.out.println("Enter mail:");
mail = sc.next();

System.out.println("Enter mobile no:");


mobile = sc.next();
}

void calc(float basic)


{
b = basic;
da = basic * 139/100;
hra = basic * 139/100;
pf = basic * 139/100;
scf = basic * 139/100;
gross = basic * 139/100;
net = gross - pf;
}

void display()
{
System.out.println("EMPLOYEE DETAILS");
System.out.println("Employee name:" + name);
System.out.println("Employee ID:" + id);
System.out.println("Employee address:" + address);
System.out.println("Employee mobile number:" + mobile);
System.out.println("Employee mail:" + mail);
System.out.println("Basic pay:" + b);
System.out.println("DA:" + da);
System.out.println("HRA:" + hra);
System.out.println("PF:" + pf);
System.out.println("Staff Club Fund:" + scf);
System.out.println("Gross Salary:" + gross);
System.out.println("Net Salary:" + net);
}
}
class programmer extends employee
{
float bp;
programmer()
{
bp=7500;
}
}

class ap extends employee


{
float bp;
ap()
{
bp=15000;
}
}

class asso extends employee


{
float bp; asso()
{
bp=23000;
}
}

class prof extends employee


{
float bp;
prof()
{
bp=30000;
}
}
public class emp
{
public static void main(String args[])
{
int choice;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the choice:");
choice=sc.nextInt();

switch(choice)
{
case 1:
System.out.println("Enter the Programmer details:");
programmer ob1=new programmer();
ob1.getData();
ob1.calc(ob1.bp);
ob1.display();
break;
case 2:
System.out.println("Enter the Assistant Professor details:");
ap ob2=new ap();
ob2.getData();
ob2.calc(ob2.bp);
ob2.display();
break;
case 3:
System.out.println("Enter the Associative Professor details:");
asso ob3=new asso();
ob3.getData();
ob3.calc(ob3.bp);
ob3.display();
break;
}
}
}

8. Write a Java Program to create an abstract class named Shape that contains two integers and an empty
method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each one
of the classes extends the class Shape. Each one of the classes contains only the method print Area () that
prints the area of the given shape.

import java.io.*;
import java.util.*;

abstract class shape


{
public int x,y;
public abstract void printArea();
}

class rectangle extends shape


{
public void printArea()
{
float area; area=x*y;
System.out.println("Area of rectangle is"+area);
}
}

class triangle extends shape


{
public void printArea()
{
float area; area=(x*y)/2;
System.out.println("Area of triangle is"+area);
}
}

class circle extends shape


{
public void printArea()
{
float area; area=(22*x*x)/7;
System.out.println("Area of circle is"+area);
}
}

public class calculate


{
public static void main(String args[])
{
Scanner a=new Scanner(System.in);
System.out.println("Enter values");

int x1=a.nextInt();
int y1=a.nextInt();

rectangle r=new rectangle();


r.x=x1;
r.y=y1;
r.printArea();

triangle t=new triangle();


t.x=x1;
t.y=y1;
t.printArea();
circle c=new circle();
c.x=x1;
c.printArea();
}
}

9. Write a Java program that simulates a traffic light. The program lets the user select one of three lights:
Red, Yellow or Green with radio buttons. On selecting a button an appropriate message with “STOP “or
“READY” or “GO” should appear above the buttons in selected color. Initially, there is no message shown.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class Traffic_Signal extends JFrame implements ItemListener


{
JRadioButton jr1;
JRadioButton jr2;
JRadioButton jr3;

JTextField j1 = new JTextField(10);


ButtonGroup b = new ButtonGroup();
String msg = " ";

// Initially setting the co-ordinates to 0,0,0


int x = 0, y = 0, z = 0;
public Traffic_Signal(String msg)
{
super(msg);
setLayout(new FlowLayout());

jr1 = new JRadioButton("Red");


jr2 = new JRadioButton("Yellow");
jr3 = new JRadioButton("Green");

jr1.addItemListener(this);
jr2.addItemListener(this);
jr3.addItemListener(this);

add(jr1);
add(jr2);
add(jr3);
b.add(jr1);
b.add(jr2);
b.add(jr3);
add(j1);

// To add a window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}

// To change colors of traffic signal


public void itemStateChanged(ItemEvent ie)
{
// If it is red
if (ie.getSource() == jr1) {
if (ie.getStateChange() == 1) {
msg = "Stop!";
x = 1;
// Repainting the box with original one
// Practically black
repaint();
}
else {
msg = "";
}
}

// If state is Orange or technically jr2


if (ie.getSource() == jr2) {
if (ie.getStateChange() == 1) {

msg = "Get Ready to go!";


y = 1;
repaint();
}
else {
msg = "";
}
}

// If state is Green
if (ie.getSource() == jr3) {
if (ie.getStateChange() == 1) {

msg = "Go!!";
z = 1;
repaint();
}
else {
msg = "";
}
}
j1.setText(msg);
}

// handling the paint graphics and


public void paint(Graphics g)
{
g.drawRect(100, 105, 110, 270);
g.drawOval(120, 150, 60, 60);
g.drawOval(120, 230, 60, 60);
g.drawOval(120, 300, 60, 60);

// Case: Red
if (x == 1) {
g.setColor(Color.RED);
g.fillOval(120, 150, 60, 60);
g.setColor(Color.WHITE);
g.fillOval(120, 230, 60, 60);
g.setColor(Color.WHITE);
g.fillOval(120, 300, 60, 60);
x = 0;
}

// Case: Orange
if (y == 1) {
g.setColor(Color.WHITE);
g.fillOval(120, 150, 60, 60);
g.setColor(Color.YELLOW);
g.fillOval(120, 230, 60, 60);
g.setColor(Color.WHITE);
g.fillOval(120, 300, 60, 60);
y = 0;
}

// Case: Green
if (z == 1) {
g.setColor(Color.WHITE);
g.fillOval(120, 150, 60, 60);
g.setColor(Color.WHITE);
g.fillOval(120, 230, 60, 60);
g.setColor(Color.GREEN);
g.fillOval(120, 300, 60, 60);
z = 0;
}
}

public static void main(String args[])


{
JFrame jf = new Traffic_Signal("Traffic Light");
jf.setSize(500, 500);
jf.setVisible(true);
}
}

10. ii) Write a Java program that reads a file and displays a file.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {


public static void main(String[] args) {
String filePath = "example.txt"; // Replace with the path to your text file

try {
File file = new File(filePath);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);

String line;

while ((line = bufferedReader.readLine()) != null) {


System.out.println(line);
}

bufferedReader.close();
}
catch (IOException e) {
System.err.println("An error occurred while reading the file: " +
e.getMessage());
}
}
}

11. i) Write a java program to find factorial of a number. User is allowed to enter a number into the text
field whose factorial is to be determined. The result will get displayed in another text field.

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

public class FactorialCalculator extends JFrame {


private JTextField inputField, resultField;
private JButton calculateButton;
public FactorialCalculator() {
setTitle("Factorial Calculator");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 2));

JLabel inputLabel = new JLabel("Enter a number:");


inputField = new JTextField(10);
calculateButton = new JButton("Calculate");
JLabel resultLabel = new JLabel("Factorial:");

resultField = new JTextField(10);


resultField.setEditable(false);

calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
try {
int number = Integer.parseInt(inputField.getText());
long factorial = calculateFactorial(number);
resultField.setText(Long.toString(factorial));
}
catch (NumberFormatException ex) {
resultField.setText("Invalid input");
}
}
});

add(inputLabel);
add(inputField);
add(calculateButton);
add(resultLabel);
add(resultField);
}

private long calculateFactorial(int number) {


if (number < 0)
{
return -1; // Handle negative input
}
else if (number == 0 || number == 1)
{
return 1; // Factorial of 0 and 1 is 1
}
else
{
long factorial = 1;
for (int i = 2; i <= number; i++)
{
factorial *= i;
}
return factorial;
}
}

public static void main(String[] args) {


FactorialCalculator calculator = new FactorialCalculator();
calculator.setVisible(true);
}
}
OUTPUT:

ii) Write a Java program to implement user defined exception handling

class MyownException2 extends Exception


{
private int value;
MyownException2(int x)
{
value = x;
}
public String toString()
{
return "MyownException2[" + value + "]";
}
}
class DemoException
{
static void compute(int x) throws MyownException2
{
System.out.println("Called compute(" + x + ")");
if(x>10)
throw new MyownException2(x);
System.out.println("Normal exit");
}
public static void main(String args[])
{
try {
compute(1);
compute(20);
}
catch (MyownException2 e) {
System.out.println("Caught " + e);
}
}
}

12. ii) Develop a GUI program to demo simple calculator.

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

public class SimpleCalculator extends JFrame {


private JTextField display;
private String currentInput;
private double firstOperand;
private String operator;

public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
display = new JTextField();
display.setEditable(false);
add(display, BorderLayout.NORTH);

JPanel buttonPanel = new JPanel();


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

String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};

for (String label : buttonLabels) {


JButton button = new JButton(label);
button.addActionListener(new ButtonClickListener());
buttonPanel.add(button);
}

add(buttonPanel, BorderLayout.CENTER);

currentInput = "";
firstOperand = 0;
operator = "";

setVisible(true);
}

private class ButtonClickListener implements ActionListener {


public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();

if (Character.isDigit(command.charAt(0)) || command.equals(".")) {
currentInput += command;
display.setText(currentInput);
}

else if (command.equals("=")) {
calculateResult();
}

else {
if (!currentInput.isEmpty())
{
firstOperand = Double.parseDouble(currentInput);
operator = command;
currentInput = "";
}
}
}

private void calculateResult() {


if (!currentInput.isEmpty()) {
double secondOperand = Double.parseDouble(currentInput);
double result = 0;

switch (operator) {
case "+":
result = firstOperand + secondOperand;
break;
case "-":
result = firstOperand - secondOperand;
break;
case "*":
result = firstOperand * secondOperand;
break;
case "/":
if (secondOperand != 0) {
result = firstOperand / secondOperand;
} else {
display.setText("Error: Division by zero");
return;
}
break;
}

display.setText(Double.toString(result));
currentInput = "";
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleCalculator calculator = new SimpleCalculator();
}
});
}
}

13. i) Develop a Java GUI program to Draw a Circle on a Frame.


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

public class DrawCircle extends JFrame


{
public DrawCircle()
{
setTitle("Draw Circle");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void paint(Graphics g)


{
super.paint(g);
g.setColor(Color.YELLOW);
g.fillOval(100, 100, 100, 100); // Parameters: (x, y, width, height)
}

public static void main(String[] args)


{
DrawEllipse ellipse = new DrawEllipse();
}
}

ii) Develop a Java Program to demo string Palindrome.

class Main
{
public static void main(String[] args)
{
String str = "Radar", reverseStr = "";
int strLength = str.length();

for (int i = (strLength - 1); i >=0; --i)


{
reverseStr = reverseStr + str.charAt(i);
}

if (str.toLowerCase().equals(reverseStr.toLowerCase()))
{
System.out.println(str + " is a Palindrome String.");
}

else
{
System.out.println(str + " is not a Palindrome String.");
}
}
}

14. i) Develop a Java GUI program to Draw a Rectangle on a Frame.


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

public class DrawRectangle extends JFrame


{
public DrawRectangle()
{
setTitle("Draw Rectangle");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void paint(Graphics g)


{
super.paint(g);
g.setColor(Color.GREEN);
g.fillOval(100, 100, 250, 100); // Parameters: (x, y, width, height)
}

public static void main(String[] args)


{
DrawRectangle rectangle = new DrawRectangle();
}
}

15. ii) Develop a Java GUI program to Draw an Ellipse on a Frame.

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

public class DrawEllipse extends JFrame


{
public DrawEllipse()
{
setTitle("Draw Ellipse");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void paint(Graphics g)


{
super.paint(g);
g.setColor(Color.BLUE);
g.fillOval(100, 100, 200, 100); // Parameters: (x, y, width, height)
}

public static void main(String[] args)


{
DrawEllipse ellipse = new DrawEllipse();
}
}

16. ii) Develop a Java GUI program to Draw a Square on a Frame.

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

public class DrawSquare extends JFrame


{
public DrawSquare()
{
setTitle("Draw Square");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void paint(Graphics g)


{
super.paint(g);
g.setColor(Color.RED);
g.fillOval(100, 100, 100, 100); // Parameters: (x, y, width, height)
}

public static void main(String[] args)


{
DrawSquare square = new DrawSquare();
}
}

17. i) Write a Java program to implement an Array Index Out of Bounds Exception.
public class ArrayIndexOutOfBoundsDemo
{
public static void main(String[] args)
{
int[] numbers = {1, 2, 3, 4, 5};

try {
int value = numbers[6]; // Attempt to access an index that doesn't exist
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out of Bounds Exception caught: " +
e.getMessage());
}
}
}
ii) Develop a Java GUI program to Draw 3 circles on same line using Red, Green and Blue
colors on a Frame.

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

public class DrawCircles extends JFrame {


public DrawCircles() {
setTitle("Draw Circles");
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void paint(Graphics g) {


super.paint(g);
g.setColor(Color.RED);
g.fillOval(50, 50, 50, 50);

g.setColor(Color.GREEN);
g.fillOval(150, 50, 50, 50);

g.setColor(Color.BLUE);
g.fillOval(250, 50, 50, 50);
}

public static void main(String[] args)


{
DrawCircles circles = new DrawCircles();
}
}

You might also like