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

Q1. WAP to find the largest of n natural numbers.

Input:
import java.util.Scanner;

public class LargestNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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


int n = scanner.nextInt();

int largest = findLargest(n);

System.out.println("The largest natural number among " + n + " natural numbers is: " + largest);
}

public static int findLargest(int n) {


int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = i + 1;
}

int largest = numbers[0];


for (int i = 1; i < n; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}

return largest;
}
}

Output:
Enter the value of n: 7
The largest natural number among 7 natural numbers is: 7

Q2. WAP to find whether a given number is prime or not.

Input:
import java.util.Scanner;

public class PrimeChecker {


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

boolean isPrime = true;

if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
}

Output:
Enter a number to check if it's prime: 17
17 is a prime number.

3. Write a menu driven program for following:


a. Display a Fibonacci series
b. Compute Factorial of a number
c. WAP to check whether a given number is odd or even.
d. WAP to check whether a given string is palindrome or not.

Input:
import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;

do {
System.out.println("Menu:");
System.out.println("1. Display Fibonacci Series");
System.out.println("2. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter the number of terms: ");
int terms = scanner.nextInt();
displayFibonacciSeries(terms);
break;
case 2:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please enter 1 or 2.");
}
} while (choice != 2);
}

public static void displayFibonacciSeries(int terms) {


int firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series:");
for (int i = 1; i <= terms; i++) {
System.out.print(firstTerm + " ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
System.out.println();
}
}

Output:
Menu:
1. Display Fibonacci Series
2. Exit
Enter your choice: 1
Enter the number of terms in Fibonacci series: 10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
Menu:
1. Display Fibonacci Series
2. Exit
Enter your choice: 2
Exiting program...

B. input:
import java.util.Scanner;

public class FactorialCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;

do {
System.out.println("Menu:");
System.out.println("1. Compute factorial of a number");
System.out.println("2. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch(choice) {
case 1:
System.out.print("Enter a number to compute factorial: ");
int number = scanner.nextInt();
long factorial = computeFactorial(number);
System.out.println("Factorial of " + number + " is: " + factorial);
break;
case 2:
System.out.println("Exiting program. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please enter 1 or 2.");
}
} while(choice != 2);

scanner.close();
}

public static long computeFactorial(int n) {


if (n == 0 || n == 1) {
return 1;
} else {

long factorial = 1;
for (int i = 2; i <= n; i++) {
factorial *= i;
}
return factorial;
}
}
}

Output:
Menu:
1. Compute factorial of a number
2. Exit
Enter your choice: 1
Enter a number to compute factorial: 5
Factorial of 5 is: 120
Menu:
1. Compute factorial of a number
2. Exit
Enter your choice: 2
Exiting program. Goodbye!

C. Input:
import java.util.Scanner;

public class OddEvenChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("Menu:");
System.out.println("1. Check if a number is odd or even");
System.out.println("2. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter a number to check: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
break;
case 2:
System.out.println("Exiting program...");
return;
default:
System.out.println("Invalid choice! Please enter 1 or 2.");
}
}
}
}

Output:
Menu:
1. Check if a number is odd or even
2. Exit
Enter your choice: 1
Enter a number to check: 15
15 is odd.
Menu:
1. Check if a number is odd or even
2. Exit
Enter your choice: 2
Exiting program...

D. input:
import java.util.Scanner;

public class PalindromeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("Menu:");
System.out.println("1. Check if a string is a palindrome");
System.out.println("2. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter a string to check if it's a palindrome: ");
scanner.nextLine(); // Clear the input buffer
String input = scanner.nextLine();
if (isPalindrome(input)) {
System.out.println("The string '" + input + "' is a palindrome.");
} else {
System.out.println("The string '" + input + "' is not a palindrome.");
}
break;
case 2:
System.out.println("Exiting program...");
break;
default:
System.out.println("Invalid choice. Please enter 1 or 2.");
break;
}
} while (choice != 2);
}

private static boolean isPalindrome(String str) {


str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
int left = 0;
int right = str.length() - 1;

while (left < right) {


if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}

Output:
Menu:
1. Check if a string is a palindrome
2. Exit
Enter your choice: 1
Enter a string to check if it's a palindrome: racecar
The string 'racecar' is a palindrome.
Menu:
1. Check if a string is a palindrome
2. Exit
Enter your choice: 1
Enter a string to check if it's a palindrome: hello
The string 'hello' is not a palindrome.
Menu:
1. Check if a string is a palindrome
2. Exit
Enter your choice: 2
Exiting program...

Q4.
WAP to print the sum and product of digits of an Integer and reverse the Integer.

Input:
import java.util.Scanner;

public class NumberOperations {


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

int sum = sumOfDigits(num);


int product = productOfDigits(num);
int reversed = reverseInteger(num);

System.out.println("Sum of digits: " + sum);


System.out.println("Product of digits: " + product);
System.out.println("Reversed number: " + reversed);
}

private static int sumOfDigits(int num) {


int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
return sum;
}

private static int productOfDigits(int num) {


int product = 1;
while (num != 0) {
product *= num % 10;
num /= 10;
}
return product;
}

private static int reverseInteger(int num) {


int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
return reversed;
}
}

Output:
Enter an integer: 1234
Sum of digits: 10
Product of digits: 24
Reversed number: 4321

Q5. Write a program to create an array of 10 integers. Accept values from the user in that
array.Input another number from the user and find out how many numbers are equal to
thenumber passed, how many are greater and how many are less than the number passed.

Input:
import java.util.Scanner;

public class NumberComparison {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Create an array of 10 integers


int[] numbers = new int[10];

// Accept values from the user and store them in the array
System.out.println("Enter 10 integers:");
for (int i = 0; i < numbers.length; i++) {
System.out.print("Enter value " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}

// Input another number from the user


System.out.print("Enter another number: ");
int inputNumber = scanner.nextInt();

// Count how many numbers are equal, greater, and less than the input number
int equalCount = 0;
int greaterCount = 0;
int lessCount = 0;
for (int num : numbers) {
if (num == inputNumber) {
equalCount++;
} else if (num > inputNumber) {
greaterCount++;
} else {
lessCount++;
}
}

// Output the results


System.out.println("Number of numbers equal to " + inputNumber + ": " + equalCount);
System.out.println("Number of numbers greater than " + inputNumber + ": " + greaterCount);
System.out.println("Number of numbers less than " + inputNumber + ": " + lessCount);
}
}

Output:
Enter 10 integers:
Enter value 1: 5
Enter value 2: 3
Enter value 3: 8
Enter value 4: 5
Enter value 5: 7
Enter value 6: 2
Enter value 7: 9
Enter value 8: 5
Enter value 9: 3
Enter value 10: 1
Enter another number: 5
Number of numbers equal to 5: 3
Number of numbers greater than 5: 4
Number of numbers less than 5: 3

Q6. Write a program that will prompt the user for a list of 5 prices. Compute the average of
the prices and find out all the prices that are higher than the calculated average.

Input:
import java.util.Scanner;

public class PriceAnalyzer {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter 5 prices


double[] prices = new double[5];
System.out.println("Enter 5 prices:");
for (int i = 0; i < prices.length; i++) {
System.out.print("Enter price " + (i + 1) + ": ");
prices[i] = scanner.nextDouble();
}

// Calculate the average of the prices


double sum = 0;
for (double price : prices) {
sum += price;
}
double average = sum / prices.length;

// Find prices higher than the average


System.out.println("\nPrices higher than the average:");
for (double price : prices) {
if (price > average) {
System.out.println(price);
}
}
}
}
Output:
Enter 5 prices:
Enter price 1: 10
Enter price 2: 15
Enter price 3: 20
Enter price 4: 25
Enter price 5: 30

Prices higher than the average:


20.0
25.0
30.0

Q7. Write a program in java to input N numbers in an array and print out the Armstrong
numbers from the set.

Input:
import java.util.Scanner;

public class ArmstrongNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

// Input the array elements


int[] numbers = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
System.out.print("Enter element " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}

// Print Armstrong numbers from the array


System.out.println("\nArmstrong numbers in the array:");
for (int num : numbers) {
if (isArmstrong(num)) {
System.out.println(num);
}
}
}

private static boolean isArmstrong(int num) {


int originalNum = num;
int sum = 0;
int digits = String.valueOf(num).length();

while (num > 0) {


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

return sum == originalNum;


}
}

Output:
Enter the number of elements in the array: 5
Enter the elements of the array:
Enter element 1: 153
Enter element 2: 370
Enter element 3: 947
Enter element 4: 371
Enter element 5: 820
Armstrong numbers in the array:
153
370
371

Q8. Write java program for the following matrix operations:


a. Addition of two matrices
b. Summation of two matrices
c. Transpose of a matrix
d. Input the elements of matrices from user.

Input:
import java.util.Scanner;

public class MatrixAddition {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the dimensions of the matrices


System.out.print("Enter the number of rows for both matrices: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns for both matrices: ");
int columns = scanner.nextInt();

// Input the elements of the first matrix


System.out.println("\nEnter the elements of the first matrix:");
int[][] matrix1 = inputMatrix(rows, columns, scanner);

// Input the elements of the second matrix


System.out.println("\nEnter the elements of the second matrix:");
int[][] matrix2 = inputMatrix(rows, columns, scanner);

// Perform addition of the matrices


int[][] resultMatrix = addMatrices(matrix1, matrix2);

// Print the result matrix


System.out.println("\nResultant Matrix after addition:");
printMatrix(resultMatrix);
}

private static int[][] inputMatrix(int rows, int columns, Scanner scanner) {


int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print("Enter element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}

private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {


int rows = matrix1.length;
int columns = matrix1[0].length;
int[][] result = new int[rows][columns];

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


for (int j = 0; j < columns; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

return result;
}

private static void printMatrix(int[][] matrix) {


for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}

Output:
Enter the number of rows for both matrices: 2
Enter the number of columns for both matrices: 2

Enter the elements of the first matrix:


Enter element at position [1][1]: 1
Enter element at position [1][2]: 2
Enter element at position [2][1]: 3
Enter element at position [2][2]: 4

Enter the elements of the second matrix:


Enter element at position [1][1]: 5
Enter element at position [1][2]: 6
Enter element at position [2][1]: 7
Enter element at position [2][2]: 8

Resultant Matrix after addition:


68
10 12

b. input:
import java.util.Scanner;

public class MatrixSum {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input dimensions of the matrices


System.out.print("Enter the number of rows for matrices: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns for matrices: ");
int cols = scanner.nextInt();

// Input elements for the first matrix


System.out.println("\nEnter elements for the first matrix:");
int[][] matrix1 = inputMatrix(rows, cols, scanner);

// Input elements for the second matrix


System.out.println("\nEnter elements for the second matrix:");
int[][] matrix2 = inputMatrix(rows, cols, scanner);

// Summation of matrices
int[][] sumMatrix = sumMatrices(matrix1, matrix2);

// Displaying the result


System.out.println("\nSummation of the two matrices:");
displayMatrix(sumMatrix);
}

private static int[][] inputMatrix(int rows, int cols, Scanner scanner) {


int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("Enter element [" + i + "][" + j + "]: ");
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}

private static int[][] sumMatrices(int[][] matrix1, int[][] matrix2) {


int rows = matrix1.length;
int cols = matrix1[0].length;
int[][] result = new int[rows][cols];

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


for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return result;
}

private static void displayMatrix(int[][] matrix) {


int rows = matrix.length;
int cols = matrix[0].length;

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


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

Output:
Result of matrix summation:
10 10 10
10 10 10
10 10 10

c. input:
import java.util.Scanner;

public class MatrixTranspose {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the dimensions of the matrix


System.out.print("Enter the number of rows in the matrix: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns in the matrix: ");
int cols = scanner.nextInt();

// Input the elements of the matrix


int[][] matrix = new int[rows][cols];
System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("Enter element at position (" + (i + 1) + "," + (j + 1) + "): ");
matrix[i][j] = scanner.nextInt();
}
}

// Compute the transpose of the matrix


int[][] transpose = new int[cols][rows];
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
transpose[i][j] = matrix[j][i];
}
}

// Print the transpose matrix


System.out.println("\nTranspose of the matrix:");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}

Output:
Enter the number of rows in the matrix: 3
Enter the number of columns in the matrix: 2
Enter the elements of the matrix:
Enter element at position (1, 1): 1
Enter element at position (1, 2): 2
Enter element at position (2, 1): 3
Enter element at position (2, 2): 4
Enter element at position (3, 1): 5
Enter element at position (3, 2): 6

Transpose of the matrix:


135
246

d. input:
import java.util.Scanner;

public class MatrixOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input dimensions of the matrices


System.out.print("Enter the number of rows of the matrices: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns of the matrices: ");
int cols = scanner.nextInt();

// Input elements of the first matrix


int[][] matrix1 = new int[rows][cols];
System.out.println("Enter the elements of the first matrix:");
inputMatrixElements(scanner, matrix1);

// Input elements of the second matrix


int[][] matrix2 = new int[rows][cols];
System.out.println("Enter the elements of the second matrix:");
inputMatrixElements(scanner, matrix2);

// Perform matrix addition


int[][] sum = addMatrices(matrix1, matrix2);

// Perform matrix subtraction


int[][] difference = subtractMatrices(matrix1, matrix2);

// Perform matrix multiplication


int[][] product = multiplyMatrices(matrix1, matrix2);

// Print the results


System.out.println("\nSum of matrices:");
printMatrix(sum);

System.out.println("\nDifference of matrices:");
printMatrix(difference);

System.out.println("\nProduct of matrices:");
printMatrix(product);
}

private static void inputMatrixElements(Scanner scanner, int[][] matrix) {


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print("Enter element [" + (i + 1) + "][" + (j + 1) + "]: ");
matrix[i][j] = scanner.nextInt();
}
}
}

private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {


int rows = matrix1.length;
int cols = matrix1[0].length;
int[][] sum = new int[rows][cols];

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


for (int j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

return sum;
}

private static int[][] subtractMatrices(int[][] matrix1, int[][] matrix2) {


int rows = matrix1.length;
int cols = matrix1[0].length;
int[][] difference = new int[rows][cols];

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


for (int j = 0; j < cols; j++) {
difference[i][j] = matrix1[i][j] - matrix2[i][j];
}
}

return difference;
}

private static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {


int rows1 = matrix1.length;
int cols1 = matrix1[0].length;
int cols2 = matrix2[0].length;
int[][] product = new int[rows1][cols2];

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


for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

return product;
}

private static void printMatrix(int[][] matrix) {


for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}

Q9. Write a java program that computes the area of a circle, rectangle and a Cylinder
usingfunction overloading.
Input:
public class AreaCalculator {
public static void main(String[] args) {
// Calculate area of a circle with radius 5
double circleArea = calculateArea(5.0);
System.out.println("Area of the circle with radius 5: " + circleArea);

// Calculate area of a rectangle with width 4 and height 6


double rectangleArea = calculateArea(4.0, 6.0);
System.out.println("Area of the rectangle with width 4 and height 6: " + rectangleArea);

// Calculate area of a cylinder with radius 3 and height 8


double cylinderArea = calculateArea(3.0, 8.0);
System.out.println("Area of the cylinder with radius 3 and height 8: " + cylinderArea);
}

// Method to calculate the area of a circle


public static double calculateArea(double radius) {
return Math.PI * radius * radius;
}

// Method to calculate the area of a rectangle


public static double calculateArea(double width, double height) {
return width * height;
}

// Method to calculate the lateral surface area of a cylinder


public static double calculateArea(double radius, double height) {
return 2 * Math.PI * radius * height;
}
}
Output:
Area of the circle with radius 5: 78.53981633974483
Area of the rectangle with width 4 and height 6: 24.0
Area of the cylinder with radius 3 and height 8: 150.79644737231007

Q10. Write a Java for the implementation of Multiple inheritance using interfaces to
calculate the area of a rectangle and triangle.
Input:
interface Rectangle {
double calculateArea(double length, double width);
}

interface Triangle {
double calculateArea(double base, double height);
}

class AreaCalculator implements Rectangle, Triangle {


@Override
public double calculateArea(double length, double width) {
return length * width;
}

@Override
public double calculateArea(double base, double height) {
return 0.5 * base * height;
}
}

public class Main {


public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();

// Calculate area of a rectangle with length 5 and width 4


double rectangleArea = calculator.calculateArea(5, 4);
System.out.println("Area of the rectangle: " + rectangleArea);

// Calculate area of a triangle with base 6 and height 8


double triangleArea = calculator.calculateArea(6, 8);
System.out.println("Area of the triangle: " + triangleArea);
}
}
Output:
Area of the rectangle: 20.0
Area of the triangle: 24.0

Q11. Write a java program to create a frame window in an Applet. Display your name,
address and qualification in the frame window.
Input:
import java.applet.Applet;
import java.awt.*;

public class FrameWindowApplet extends Applet {


public void init() {
Frame frame = new Frame("Personal Information");
frame.setSize(400, 200);

// Name, address, and qualification


Label nameLabel = new Label("Name: John Doe");
Label addressLabel = new Label("Address: 123 Main Street, Cityville");
Label qualificationLabel = new Label("Qualification: Bachelor of Science in Computer Science");

// Add components to the frame


frame.add(nameLabel, BorderLayout.NORTH);
frame.add(addressLabel, BorderLayout.CENTER);
frame.add(qualificationLabel, BorderLayout.SOUTH);

// Center the frame on the screen


Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screenSize.width - frame.getWidth()) / 2;
int y = (screenSize.height - frame.getHeight()) / 2;
frame.setLocation(x, y);

// Make the frame visible


frame.setVisible(true);
}
}
Output:
A frame window titled "Personal Information" will appear on the screen with your name, address, and qualification displayed inside it.

Q12. Write a java program to draw a line between two coordinates in a window.
Input:
import javax.swing.*;
import java.awt.*;

public class LineDrawing extends JPanel {


private int x1, y1, x2, y2;

public LineDrawing(int x1, int y1, int x2, int y2) {


this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(x1, y1, x2, y2);
}

public static void main(String[] args) {


int x1 = 50, y1 = 50; // Starting point
int x2 = 200, y2 = 150; // Ending point

JFrame frame = new JFrame("Line Drawing");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

LineDrawing lineDrawing = new LineDrawing(x1, y1, x2, y2);


frame.add(lineDrawing);

frame.setVisible(true);
}
}
Output:
A window titled "Line Drawing" will appear, displaying a line drawn between the coordinates (50, 50) and (200, 150).
Q13. Write a java program to display the following graphics in an applet window.a.
Rectangles
b. Circles
c. Ellipses
d. Arcs
e. Polygons
a. input:
import java.applet.Applet;
import java.awt.*;

public class RectangleApplet extends Applet {


public void paint(Graphics g) {
// Draw rectangles
g.drawRect(20, 20, 100, 50);
g.fillRect(150, 20, 100, 50);
g.drawRoundRect(20, 100, 100, 50, 10, 10);
g.fillRoundRect(150, 100, 100, 50, 20, 20);
}
}
Output:
an applet window displaying rectangles drawn using various methods like drawRect, fillRect, drawRoundRect, and fillRoundRect.
b. input:
import java.awt.*;
import java.applet.*;

public class CircleApplet extends Applet {


public void paint(Graphics g) {
g.setColor(Color.blue);
g.drawOval(50, 50, 100, 100); // Circle 1
g.setColor(Color.red);
g.drawOval(150, 50, 150, 150); // Circle 2
g.setColor(Color.green);
g.drawOval(100, 150, 200, 100); // Circle 3
}
}
Output:
three circles displayed in an applet window, one in blue, one in red, and one in green, as described in the program. Each circle is drawn
with different coordinates and dimensions.

c. input:
import java.awt.*;
import java.applet.*;

public class EllipseApplet extends Applet {


public void paint(Graphics g) {
g.setColor(Color.blue);
g.drawOval(50, 50, 150, 100); // Ellipse 1
g.setColor(Color.red);
g.drawOval(200, 50, 100, 150); // Ellipse 2
g.setColor(Color.green);
g.drawOval(100, 200, 200, 150); // Ellipse 3
}
}
Output:
three ellipses displayed in an applet window, one in blue, one in red, and one in green, as described in the program. Each ellipse is drawn
with different coordinates and dimensions.

d. input:
import java.awt.*;
import java.applet.*;

public class ArcApplet extends Applet {


public void paint(Graphics g) {
g.setColor(Color.blue);
g.drawArc(50, 50, 100, 100, 0, 90); // Arc 1
g.setColor(Color.red);
g.drawArc(150, 50, 150, 150, 45, 180); // Arc 2
g.setColor(Color.green);
g.drawArc(100, 150, 200, 100, 90, 270); // Arc 3
}
}
Output:
three arcs displayed in an applet window, one in blue, one in red, and one in green, as described in the program. Each arc is drawn with
different coordinates, dimensions, and start/end angles.

e. input:
import java.awt.*;
import java.applet.*;

public class PolygonApplet extends Applet {


public void paint(Graphics g) {
int[] xPoints = {50, 150, 200, 100};
int[] yPoints = {100, 50, 150, 200};
int numPoints = 4;

g.setColor(Color.blue);
g.drawPolygon(xPoints, yPoints, numPoints); // Polygon 1

int[] xPoints2 = {250, 350, 400};


int[] yPoints2 = {100, 50, 150};
int numPoints2 = 3;

g.setColor(Color.red);
g.drawPolygon(xPoints2, yPoints2, numPoints2); // Polygon 2
}
}
Output:
two polygons displayed in an applet window, one in blue and one in red, as described in the program. Each polygon is drawn with different
coordinates.

Q14. Write a program that reads two integer numbers for the variables a and b. If any other
character except number (0-9) is entered then the error is caught by Number Format
Exception object. After that ex. Get Message() prints the information about the error
occurring causes.
Input:
import java.util.Scanner;

public class NumberFormatExceptionExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter the value of a: ");
int a = Integer.parseInt(scanner.nextLine());

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


int b = Integer.parseInt(scanner.nextLine());

System.out.println("Sum of a and b: " + (a + b));


} catch (NumberFormatException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("Please enter valid integer numbers.");
}
}
}
Output:
Enter the value of a: 10
Enter the value of b: 20
Sum of a and b: 30

You might also like