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

java all programs

The document contains various Java programming exercises focused on data input methods, control statements, loops, class design, method overloading, and package creation. It includes code examples for calculating factorials, Fibonacci series, grade calculation, bank account management, employee salary management, area calculation, and basic arithmetic operations using packages. Additionally, it covers binary search implementation in a one-dimensional array.

Uploaded by

daanial d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

java all programs

The document contains various Java programming exercises focused on data input methods, control statements, loops, class design, method overloading, and package creation. It includes code examples for calculating factorials, Fibonacci series, grade calculation, bank account management, employee salary management, area calculation, and basic arithmetic operations using packages. Additionally, it covers binary search implementation in a one-dimensional array.

Uploaded by

daanial d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 19

Exp 1 : Program on various ways to accept data through keyboard

a. WAP to calculate Factorial of a number using manual input.

import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int n = scanner.nextInt();
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println("Factorial of " + number + " is " + factorial);
}}

b. WAP to accept input using command line arguments. Print the count of input
takenand its values.

public class CommandLineArgs {


public static void main(String[] args) {
int count = args.length;
System.out.println("Count of input arguments: " + count);
System.out.println("Input values:");
for (String arg : args) {
System.out.println(arg);
}}}

c. WAP for printing Fibonacci series. Accept the term using command line arguments.

public class FibonacciSeries {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Please provide the number of terms in the Fibonacci
series.");
return;}
int terms;
try {
terms = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid integer.");
return;
}
if (terms <= 0) {
System.out.println("Please enter a positive integer.");
return;
}
System.out.println("Fibonacci series up to " + terms + " terms:");
int a = 0, b = 1;
for (int i = 1; i <= terms; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}}}

d. WAP to print the count of digits from the input taken. Accept input using
Scanner class.
import java.util.Scanner;
public class CountDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scanner.nextLine();
int digitCount = 0;
for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
digitCount++;
}
}
System.out.println("Count of digits: " + digitCount);
}}

Exp 2 : Operators control statements and loops

a. WAP to print the grade for an input test score: using the if- else ladder

· Percentage · Grade
· 0-60 · F
· 61-70 · D
· 71-80 · C
· 81-90 · B
· 91-100 · A

import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the test score (0-100): ");
int score = scanner.nextInt();
String grade;
if (score < 0 || score > 100) {
grade = "Invalid score! Please enter a score between 0 and 100.";
} else if (score >= 0 && score <= 60) {
grade = "F";
} else if (score >= 61 && score <= 70) {
grade = "D";
} else if (score >= 71 && score <= 80) {
grade = "C";
} else if (score >= 81 && score <= 90) {
grade = "B";
} else { // score between 91 and 100
grade = "A";
}
System.out.println("Grade: " + grade);
}
}

b. Switch-case: menu driven calculator.

import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Menu Driven Calculator");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Exit");
while (true) {
System.out.print("Choose an operation (1-5): ");
int choice = scanner.nextInt();
if (choice == 5) {
System.out.println("Exiting...");
break;
}
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
double result;
switch (choice) {
case 1:
result = num1 + num2;
System.out.println("Result: " + result);
break;
case 2:
result = num1 - num2;
System.out.println("Result: " + result);
break;
case 3:
result = num1 * num2;
System.out.println("Result: " + result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
System.out.println("Result: " + result);
} else {
System.out.println("Error: Division by zero.");
}
break;
default:
System.out.println("Invalid choice. Please select again.");
}
}
}
}

c. WAP to find whether the entered number is Armstrong no or not.

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 num = scanner.nextInt();
int n = num;
int sum = 0;
while (n != 0) {
int d = n % 10;
sum = sum+ d*d*d;
n = n/10;
}
if (sum == originalNumber) {
System.out.println(num + " is an Armstrong number.");
} else {
System.out.println(num + " is not an Armstrong number.");
}
}
}

Exp 3 : To understand the working of a class

a. WAP to design a class to represent bank account. It should include the following
members; Name of depositor, Account Number, Type of Account and balance amount in
the account.
It should also has methods to
i) To assign initial values.
ii) To deposit an amount.
iii) To withdraw an amount after checking balance.
iv) To display the name and balance.

import java.util.Scanner;
class BankAccount {
private String depositorName;
private String accountNumber;
private String accountType;
private double balance;
public BankAccount(String name, String accNumber, String accType, double
initialBalance) {
this.depositorName = name;
this.accountNumber = accNumber;
this.accountType = accType;
this.balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}
public void withdraw(double amount) {
if (amount > balance) {
System.out.println("Insufficient balance. Withdrawal failed.");
} else if (amount > 0) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Withdrawal amount must be positive.");
}
}
public void display() {
System.out.println("Depositor Name: " + depositorName);
System.out.println("Account Balance: " + balance);
}
}
public class BankAccountTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter depositor's name: ");
String name = scanner.nextLine();
System.out.print("Enter account number: ");
String accNumber = scanner.nextLine();
System.out.print("Enter account type: ");
String accType = scanner.nextLine();
System.out.print("Enter initial balance: ");
double initialBalance = scanner.nextDouble();
BankAccount account = new BankAccount(name, accNumber, accType,
initialBalance);
while (true) {
System.out.println("\nMenu:");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Display Account Details");
System.out.println("4. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
account.display();
break;
case 4:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please select again.");
}}}}

b. WAP to define Employee class having data members ename, eno,basic,salary,


TA,DA,HRA. Accept this for 5 employees using array of object and display this in
descending order of their gross salary. Define following methods :
i) setData( ) - for input
ii) int grossSal( ) - for calculating salary
iii) void show( ) - to display all values along with gross salary. Use
BufferedReader class for accepting input.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
class Employee {
private String ename;
private int eno;
private double basic;
private double TA;
private double DA;
private double HRA;
public void setData() throws IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter employee name: ");
ename = reader.readLine();
System.out.print("Enter employee number: ");
eno = Integer.parseInt(reader.readLine());
System.out.print("Enter basic salary: ");
basic = Double.parseDouble(reader.readLine());
System.out.print("Enter TA (Travel Allowance): ");
TA = Double.parseDouble(reader.readLine());
System.out.print("Enter DA (Dearness Allowance): ");
DA = Double.parseDouble(reader.readLine());
System.out.print("Enter HRA (House Rent Allowance): ");
HRA = Double.parseDouble(reader.readLine());
}
public double grossSal() {
return basic + TA + DA + HRA;
}
public void show() {
System.out.printf("Name: %s, Employee Number: %d, Basic: %.2f, TA: %.2f,
DA: %.2f, HRA: %.2f, Gross Salary: %.2f%n", ename, eno, basic, TA, DA, HRA,
grossSal());
}
}
public class EmployeeManagement {
public static void main(String[] args) {
Employee[] employees = new Employee[5];
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
for (int i = 0; i < 5; i++) {
System.out.println("Entering data for employee " + (i + 1) + ":");
employees[i] = new Employee();
employees[i].setData();
}
} catch (IOException e) {
System.out.println("Error reading input: " + e.getMessage());
}

// Sort employees based on gross salary in descending order


Arrays.sort(employees, new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return Double.compare(e2.grossSal(), e1.grossSal());
}
});

// Display employee details


System.out.println("\nEmployee details in descending order of gross
salary:");
for (Employee employee : employees) {
employee.show();
}
}
}

Exp 4 : Constructor and method overloading

a. WAP on method overloading to calculate area of circle, rectangle and


triangle.

class AreaCalculator {
public double area(double radius) {
return 3.14 * radius * radius; // Using 3.14 for π
}
public double area(double length, double width) {
return length * width;
}
public double area(double base, double height) {
return 0.5 * base * height;
}
}

public class AreaCalculatorTest {


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

double circleRadius = 5.0;


System.out.println("Area of Circle with radius " + circleRadius + ": " +
calculator.area(circleRadius));

double rectangleLength = 10.0;


double rectangleWidth = 5.0;
System.out.println("Area of Rectangle with length " + rectangleLength + "
and width " + rectangleWidth + ": " + calculator.area(rectangleLength,
rectangleWidth));

double triangleBase = 8.0;


double triangleHeight = 4.0;
System.out.println("Area of Triangle with base " + triangleBase + " and
height " + triangleHeight + ": " + calculator.area(triangleBase, triangleHeight));
}
}

b. Program on constructor and constructor overloading

class Employee {
private String name;
private int id;
private double salary;

// Constructor with one parameter


public Employee(String name) {
this.name = name;
this.id = 0; // Default ID
this.salary = 0.0; // Default salary
}

// Constructor with two parameters


public Employee(String name, int id) {
this.name = name;
this.id = id;
this.salary = 0.0; // Default salary
}

// Constructor with three parameters


public Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}

// Method to display employee details


public void display() {
System.out.printf("Name: %s, ID: %d, Salary: %.2f%n", name, id, salary);
}
}

public class EmployeeTest {


public static void main(String[] args) {
// Using different constructors
Employee emp1 = new Employee("Alice");
Employee emp2 = new Employee("Bob", 101);
Employee emp3 = new Employee("Charlie", 102, 50000.0);

// Display employee details


emp1.display();
emp2.display();
emp3.display();
}
}

Exp 5 : Packages in Java

a. Create a package (say) ABC, WAP operation.java in ABC (add (), subtract(),
multiply(), divide()). WAP Import package.java that imports the package ABC.

package ABC;
public class Operations {

// Method to add two numbers


public int add(int a, int b) {
return a + b;
}

// Method to subtract two numbers


public int subtract(int a, int b) {
return a - b;
}

// Method to multiply two numbers


public int multiply(int a, int b) {
return a * b;
}

// Method to divide two numbers


public double divide(int a, int b) {
if (b == 0) {
System.out.println("Error: Division by zero.");
return 0;
}
return (double) a / b;
}
}

Main class:

import ABC.Operations;
import java.util.Scanner;
public class ImportPackage {
public static void main(String[] args) {
Operations ops = new Operations();
Scanner scanner = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();

System.out.println("Addition: " + ops.add(num1, num2));


System.out.println("Subtraction: " + ops.subtract(num1, num2));
System.out.println("Multiplication: " + ops.multiply(num1, num2));
System.out.println("Division: " + ops.divide(num1, num2));

scanner.close();
}
}
Exp 6 : Multidimensional Array

a.WAP to perform Binary search in 1-D array of 10 elements.

import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = {3, 8, 15, 23, 42, 56, 78, 89, 95, 101};
System.out.print("Enter the element to search for: ");
int target = scanner.nextInt();
int result = binarySearch(array, target);
if (result == -1) {
System.out.println("Element not found in the array.");
} else {
System.out.println("Element found at index: " + result);
}
}

public static int binarySearch(int[] array, int target) {


int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (array[mid] == target) {
return mid;
}
if (array[mid] < target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return -1;
}
}

b.WAP to perform matrix multiplication.

import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows of the first matrix: ");
int rows1 = scanner.nextInt();
System.out.print("Enter the number of columns of the first matrix (and rows of the
second matrix): ");
int cols1 = scanner.nextInt();
System.out.print("Enter the number of columns of the second matrix: ");
int cols2 = scanner.nextInt();
int[][] matrix1 = new int[rows1][cols1];
int[][] matrix2 = new int[cols1][cols2];
int[][] result = new int[rows1][cols2];
System.out.println("Enter elements of the first matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i] = scanner.nextInt();
}
}
System.out.println("Enter elements of the second matrix:");
for (int i = 0; i < cols1; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i] = scanner.nextInt();
}
}
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
System.out.println("The resultant matrix is:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}

Exp 7 : String Operations

a. WAP to count number of occurrences of given character using string class.

import java.util.Scanner;
public class CharacterCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
System.out.print("Enter a character to count: ");
char characterToCount = scanner.next().charAt(0);
int count = 0;
for (int i = 0; i < inputString.length(); i++) {
if (inputString.charAt(i) == characterToCount) {
count++;
}
}
System.out.println("The character '" + characterToCount + "' occurs " +
count + " times.");

}
}

b.WAP to count no of vowels using string class.

import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
int vowelCount = 0;
String vowels = "AEIOUaeiou"; // String containing all vowels
for (int i = 0; i < inputString.length(); i++) {
char currentChar = inputString.charAt(i);
if (vowels.indexOf(currentChar) != -1) {
vowelCount++;
} }
System.out.println("The number of vowels in the string is: " + vowelCount);
}}

Exp 8 : String Operations And Vector Class

a. WAP to reverse a complete sentence using string buffer class.

import java.util.Scanner;
public class ReverseSentence {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
StringBuffer stringBuffer = new StringBuffer(sentence);
String reversedSentence = stringBuffer.reverse().toString();
System.out.println("Reversed sentence: " + reversedSentence);
}}

b. WAP to use methods of vector class.

import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");
System.out.println("Initial vector: " + vector);
vector.add(1, "Orange");
System.out.println("After adding 'Orange' at index 1: " + vector);
vector.remove("Banana");
System.out.println("After removing 'Banana': " + vector);
boolean containsCherry = vector.contains("Cherry");
System.out.println("Vector contains 'Cherry': " + containsCherry);
int size = vector.size();
System.out.println("Size of the vector: " + size);
System.out.println("Elements in the vector:");
for (String fruit : vector) {
System.out.println(fruit);
}}}
Exp 9 : Constructor and method overloading

a. WAP to implement three classes namely Student, Test and Result. Student class
has member as rollno,Test class has members as sem1_marks and sem2_marks and Result
class has member as total.(multilevel)

// Base class: Student


class Student {
String name;
int rollNo;
// Constructor to initialize student details
Student(String name, int rollNo) {
this.name = name;
this.rollNo = rollNo;
}
// Method to display student details
void displayStudentDetails() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
}}
// First Derived Class: Marks (extends Student)
class Marks extends Student {
int subject1, subject2, subject3;
Marks(String name, int rollNo, int subject1, int subject2, int subject3) {
super(name, rollNo); // Calling Student constructor
this.subject1 = subject1;
this.subject2 = subject2;
this.subject3 = subject3;
}
void displayMarks() {
System.out.println("Marks in Subject 1: " + subject1);
System.out.println("Marks in Subject 2: " + subject2);
System.out.println("Marks in Subject 3: " + subject3);
}}
class Percentage extends Marks {
// Constructor to initialize student details and marks
Percentage(String name, int rollNo, int subject1, int subject2, int subject3) {
super(name, rollNo, subject1, subject2, subject3); // Calling Marks constructor
}
void displayPercentage() {
int totalMarks = subject1 + subject2 + subject3;
float percentage = (totalMarks / 3.0f); // Assuming each subject is out of 100
System.out.println("Total Percentage: " + percentage + "%");
}
}
public class multiinheritance {
public static void main(String[] args) {
Percentage student = new Percentage("John", 101, 85, 90, 88);
student.displayStudentDetails(); // From Student class
student.displayMarks(); // From Marks class
student.displayPercentage(); // From Percentage class
}}

Exp 10 : Packages in Java

a. Write a abstract class program to calculate area of circle, rectangle and


triangle.

abstract class Shape {


abstract void calculateArea();
}

class Circle extends Shape {


double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
void calculateArea() {
double area = Math.PI * radius * radius;
System.out.println("Area of Circle: " + area);
}
}

class Rectangle extends Shape {


double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
void calculateArea() {
double area = length * width;
System.out.println("Area of Rectangle: " + area);
}
}

class Triangle extends Shape {


double base, height;
Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
void calculateArea() {
double area = 0.5 * base * height;
System.out.println("Area of Triangle: " + area);
}
}
public class abstract_demo {
public static void main(String[] args) {
Circle circle = new Circle(5.0); // Circle with radius 5.0
Rectangle rectangle = new Rectangle(4.0, 6.0); // Rectangle with length 4.0 and
width 6.0
Triangle triangle = new Triangle(3.0, 4.0); // Triangle with base 3.0 and height
4.0
circle.calculateArea(); // Calls Circle's calculateArea method
rectangle.calculateArea(); // Calls Rectangle's calculateArea method
triangle.calculateArea(); // Calls Triangle's calculateArea method
}}
Exp 11 : Multiple Inheritance in Java

interface Test {
int attendance = 0;
int fmarks = 0;
int getTW();}
class Student {
String name;
int rollNo;
public Student(String name, int rollNo) {
this.name = name;
this.rollNo = rollNo;}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
}}
class TestImpl extends Student implements Test {
int attendance;
int fmarks;
public TestImpl(String name, int rollNo, int attendance, int fmarks) {
super(name, rollNo);
this.attendance = attendance;
this.fmarks = fmarks;
}
@Override
public int getTW() {
return (attendance + fmarks) / 2;
}
public void displayTestInfo() {
System.out.println("Attendance: " + attendance);
System.out.println("Final Marks: " + fmarks);
}}
class Result extends TestImpl {
int total;
public Result(String name, int rollNo, int attendance, int fmarks) {
super(name, rollNo, attendance, fmarks);
this.total = getTW(); // Calculate the total
}
public void displayResult() {
super.displayInfo(); // Display student info
super.displayTestInfo(); // Display test info
System.out.println("Total Weightage (TW): " + total);
}}
public class Main {
public static void main(String[] args) {
Result studentResult = new Result("John Doe", 101, 80, 85);
studentResult.displayResult();}}
Exp 12 : Exception Handling

a. WAP for exception handling using try/catch, throw, and finally demonstrating
different inbuilt exceptions (IO, Arithmetic…)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ExceptionHandlingDemo {
public static void main(String[] args) {
// Demonstrating ArithmeticException
try {
int result = divide(10, 0); // This will throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
} finally {
System.out.println("Finished Arithmetic Exception Handling.");
}
// Demonstrating IOException
try {
readFile("nonexistentfile.txt"); // This will throw IOException
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
} finally {
System.out.println("Finished IOException Handling.");
}
}
// Method to demonstrate ArithmeticException
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return a / b;
}
// Method to demonstrate IOException
public static void readFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
System.out.println("File content: " + line);
reader.close();
}
}
Exp 13 : User Defined Exceptions
a. Define an user defined exception called “NoMatchException” that is thrown when a
string is not equal to “India”. Write a program that uses this exception.
class NoMatchException extends Exception
{
private String str;
NoMatchException(String str1)
{
str=str1;
}
public String toString()
{
return "NoMatchException --> String is not India and string is "+str;
}
}
class NoMatcher
{
public static void main(String args[ ])
{
String str1= new String("India");
String str2= new String("Pakistan");
try
{
if(str1.equals("India"))
System.out.println(" String is : "+str1);
else
throw new NoMatchException(str1);
if(str2.equals("India"))
System.out.println("\n String is : "+str2);
else
throw new NoMatchException(str2);
}
catch(NoMatchException e)
{
System.out.println("\nCaught ...."+e);
}
}
}

b. WAP to create Prime number exception while calculating factorial.

// Custom exception for prime number


class PrimeNumberException extends Exception {
public PrimeNumberException(String message) {
super(message);
}
}

public class FactorialCalculator {

// Method to check if a number is prime


public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

// Method to calculate factorial


public static long factorial(int n) throws PrimeNumberException {
if (isPrime(n)) {
throw new PrimeNumberException("Cannot calculate factorial for a prime
number: " + n);
}
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

public static void main(String[] args) {


java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.print("Enter a number to calculate its factorial: ");
int number = scanner.nextInt();

try {
long result = factorial(number);
System.out.println("The factorial of " + number + " is " + result);
} catch (PrimeNumberException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
}

Exp 14 : User Defined Exceptions

a. WAP to print even and odd no using two threads.

import java.io.*;

class odd extends Thread


{
public void run()
{
try
{
for (int i=1; i<10;i=i+2)
{
System.out.println("Odd thread "+1);
Thread.sleep(500);
}
catch(Exception e)
{ System.out.print(e);
}
}}

class even extends Thread


{
public void run()
{
try
{
for (int j=2; j<=10;j=j+2)
{
System.out.println("Even thread "+j);
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

class thread
{
public static void main(String args[]){
odd o = new odd();
even e = new even();
o.start();
e.start();
}
}

Exp 15 : Applets

a. WAP to display smiling face using applet


import java.applet.*;
import java.awt.*;
/*<applet code ="Smiley" width=600 height=600></applet>*/
public class Smiley extends Applet {
public void paint(Graphics g){
g.drawOval(80, 70, 150, 150);
g.setColor(Color.BLACK);
g.fillOval(120, 120, 15, 15);
g.fillOval(170, 120, 15, 15);
g.drawArc(130, 180, 50, 20, 180, 180);}}

b. WAP to design Login form using awt components.


import java.awt.*;
import java.awt.event.*;
class MyLoginWindow extends Frame{
TextField name,pass;
Button b1,b2;
MyLoginWindow(){
setLayout(new FlowLayout());
this.setLayout(null);
Label n=new Label("Name:",Label.CENTER);
Label p=new Label("password:",Label.CENTER);
name=new TextField(20);
pass=new TextField(20);
pass.setEchoChar('#');
b1=new Button("submit");
b2=new Button("cancel");
this.add(n);
this.add(name);
this.add(p);
this.add(pass);
this.add(b1);
this.add(b2);
n.setBounds(70,90,90,60);
p.setBounds(70,130,90,60);
name.setBounds(200,100,90,20);
pass.setBounds(200,140,90,20);
b1.setBounds(100,260,70,40);
b2.setBounds(180,260,70,40);
}
public static void main(String args[]){
MyLoginWindow ml=new MyLoginWindow();
ml.setVisible(true);
ml.setSize(400,400);
ml.setTitle("my login window");}}

You might also like