java all programs
java all programs
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.
c. WAP for printing Fibonacci series. Accept the term using command line arguments.
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);
}}
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);
}
}
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.");
}
}
}
}
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.");
}
}
}
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.");
}}}}
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());
}
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;
}
}
class Employee {
private String name;
private int id;
private double salary;
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 {
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);
scanner.close();
}
}
Exp 6 : Multidimensional Array
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);
}
}
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();
}
}
}
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.");
}
}
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);
}}
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);
}}
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)
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);
}
}
}
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();
}
}
}
import java.io.*;
class thread
{
public static void main(String args[]){
odd o = new odd();
even e = new even();
o.start();
e.start();
}
}
Exp 15 : Applets