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

Java Code2

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

Java Code2

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

Question1:

import java.util.Scanner;

public class CharCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String inputString = scanner.nextLine();

int[] charCount = new int[256]; // Assuming ASCII characters

// Count occurrences of each character


for (int i = 0; i < inputString.length(); i++) {
charCount[(int)inputString.charAt(i)]++;
}

// Print character counts


System.out.println("Character Counts:");
for (int i = 0; i < 256; i++) {
if (charCount[i] > 0) {
System.out.println((char)i + ": " + charCount[i]);
}
}
}
}
Output:
Question2:
public class NumPrint{
public static void main(String[] args) {
for (int i = 1; i <= 50; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("TF");
} else if (i % 3 == 0) {
System.out.println("T");
} else if (i % 5 == 0) {
System.out.println("F");
} else {
System.out.println(i);
}
}
}
}
Output:
Question3:
import java.util.Scanner;

public class StrOperation {


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

// i. Convert string into integer and vice versa


System.out.println("Enter a number as string:");
String numAsString = scanner.nextLine();
int num = Integer.parseInt(numAsString);
System.out.println("String converted to integer: " + num);

System.out.println("Enter an integer:");
int intValue = scanner.nextInt();
String intAsString = Integer.toString(intValue);
System.out.println("Integer converted to string: " + intAsString);

scanner.nextLine(); // Consume newline

// ii. Convert string into lower to upper and vice versa


System.out.println("Enter a string:");
String inputString = scanner.nextLine();
String upperCaseString = inputString.toUpperCase();
String lowerCaseString = inputString.toLowerCase();
System.out.println("Uppercase: " + upperCaseString);
System.out.println("Lowercase: " + lowerCaseString);
// iii. Extract number of characters from a string
int numberOfCharacters = inputString.length();
System.out.println("Number of characters: " + numberOfCharacters);

// iv. Compare two string and print the result


System.out.println("Enter first string:");
String str1 = scanner.nextLine();
System.out.println("Enter second string:");
String str2 = scanner.nextLine();
if (str1.equals(str2)) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}

// v. Search a substring in a string and replace it with another string


System.out.println("Enter a string:");
String originalString = scanner.nextLine();
System.out.println("Enter the substring to search:");
String substring = scanner.nextLine();
System.out.println("Enter the replacement string:");
String replacement = scanner.nextLine();
String modifiedString = originalString.replace(substring, replacement);
System.out.println("Modified string: " + modifiedString);

// vi. Count number of vowels, digits, special character, lower and upper alphabets, words in
an input string
int vowels = 0, digits = 0, specialCharacters = 0, lowerCaseChars = 0, upperCaseChars = 0,
words = 0;
for (char ch : inputString.toCharArray()) {
if (Character.isLetter(ch)) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
vowels++;
} else {
if (Character.isUpperCase(ch)) {
upperCaseChars++;
} else {
lowerCaseChars++;
}
}
} else if (Character.isDigit(ch)) {
digits++;
} else {
specialCharacters++;
}
}
words = inputString.split("\\s+").length;
System.out.println("Number of vowels: " + vowels);
System.out.println("Number of digits: " + digits);
System.out.println("Number of special characters: " + specialCharacters);
System.out.println("Number of lowercase characters: " + lowerCaseChars);
System.out.println("Number of uppercase characters: " + upperCaseChars);
System.out.println("Number of words: " + words);
scanner.close();
}
}
Output:
Question5:
// Define the Shape class
abstract class Shape {
// Abstract methods
abstract double getPeri();
abstract double getArea();
}

// Define the Circle subclass


class Circle extends Shape {
// Instance variable
private double radius;

// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Override the getPeri() method


@Override
double getPeri() {
return 2 * Math.PI * radius;
}

// Override the getArea() method


@Override
double getArea() {
return Math.PI * radius * radius;
}
}

// Main class to test the Shape and Circle classes


public class Main {
public static void main(String[] args) {
// Create a Circle object
Circle circle = new Circle(6);

// Calculate and print perimeter and area of the circle


System.out.println("Perimeter of the circle: " + circle.getPeri());
System.out.println("Area of the circle: " + circle.getArea());
}
}
Output:
Question6:
// Define the Bank class
class Bank {
// Instance variable
protected double balance;

// Constructor
public Bank() {
balance = 0.0;
}

// Deposit method
public void deposit(double amount) {
balance += amount;
System.out.println("Amount deposited: Rs. " + amount);
System.out.println("Current balance: Rs. " + balance);
}

// Withdraw method
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Amount withdrawn: Rs. " + amount);
System.out.println("Current balance: Rs. " + balance);
} else {
System.out.println("Withdrawal not possible, insufficient funds");
}
}
}

// Define the CustAccount subclass


class CustAccount extends Bank {
// Override the withdraw method
@Override
public void withdraw(double amount) {
if (balance >= amount && balance - amount >= 250) {
balance -= amount;
System.out.println("Amount withdrawn: Rs. " + amount);
System.out.println("Current balance: Rs. " + balance);
} else {
System.out.println("Withdrawal not possible, balance is less than Rs. 250");
}
}
}

// Main class to test the Bank and CustAccount classes


public class Main2 {
public static void main(String[] args) {
// Create a CustAccount object
CustAccount account = new CustAccount();
// Deposit and withdraw money
account.deposit(500);
account.withdraw(200);
account.withdraw(300);
}
}
Output:
Question7:
// Define the Animal abstract class
abstract class Animal {
// Abstract method
abstract void sound();
}

// Define the Tiger subclass


class Tiger extends Animal {
// Implement the sound method for a tiger
@Override
void sound() {
System.out.println("Tiger says: Roar");
}
}

// Define the Dog subclass


class Dog extends Animal {
// Implement the sound method for a dog
@Override
void sound() {
System.out.println("Dog says: Bark");
}
}

// Main class to test the Animal, Tiger, and Dog classes


public class MainAnimal {
public static void main(String[] args) {
// Create a Tiger object and make it sound
Tiger tiger = new Tiger();
tiger.sound();

// Create a Dog object and make it sound


Dog dog = new Dog();
dog.sound();
}
}
Output:
Question8:
// Define the Sortable interface
interface Sortable {
// Method to sort an array of integers
void sort(int[] array);
}

// Define the Bubble class that implements the Sortable interface


class Bubble implements Sortable {
// Implement the sort method using Bubble Sort algorithm
@Override
public void sort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap array[j] and array[j+1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}

// Define the Selection class that implements the Sortable interface


class Selection implements Sortable {
// Implement the sort method using Selection Sort algorithm
@Override
public void sort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
// Swap array[i] and array[minIndex]
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
}

// Main class to test the Sortable, Bubble, and Selection classes


public class MainSort {
public static void main(String[] args) {
int[] array = {5, 3, 8, 1, 2, 7, 4, 6};

// Create a Bubble object and sort the array using Bubble Sort
Sortable bubbleSort = new Bubble();
bubbleSort.sort(array);
System.out.println("Array sorted using Bubble Sort:");
printArray(array);

// Create a Selection object and sort the array using Selection Sort
Sortable selectionSort = new Selection();
selectionSort.sort(array);
System.out.println("Array sorted using Selection Sort:");
printArray(array);
}

// Utility method to print the elements of an array


private static void printArray(int[] array) {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
}
Output:
Question9:
import java.util.Scanner;

public class PercentCalculate {


public static void main(String[] args) {
try {
// Check if command-line arguments are provided
if (args.length != 1) {
System.out.println("Usage: java PercentageCalculator <max-marks>");
return;
}

// Parse max-marks from command-line arguments


int maxMarks = Integer.parseInt(args[0]);

// Accept input from the user for marks obtained


Scanner scanner = new Scanner(System.in);
System.out.print("Enter marks obtained: ");
int marksObtained = scanner.nextInt();

// Calculate percentage
double percentage = 0;
try {
percentage = (double) marksObtained / maxMarks * 100;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
return;
}
// Display the calculated percentage
System.out.println("Percentage: " + percentage + "%");
} catch (NumberFormatException e) {
System.out.println("Error: Invalid input. Please provide valid integer for max-marks.");
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}
Output:
Question10:
import java.util.Scanner;

// Custom exception class for invalid employee details


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

// EmployeeDetails class
public class EmployeeDetails {
// Method to accept and validate employee details
public void acceptDetails() {
try {
Scanner scanner = new Scanner(System.in);

// Accept employee id
System.out.print("Enter employee id: ");
int empId = scanner.nextInt();
scanner.nextLine(); // Consume newline

// Accept employee name


System.out.print("Enter employee name (in uppercase): ");
String empName = scanner.nextLine();
if (!empName.matches("[A-Z]+")) {
throw new InvalidEmployeeDetailsException("Employee name should be in uppercase
and contain only alphabets.");
}
// Accept employee designation
System.out.print("Enter employee designation (Manager/Clerk/Peon): ");
String empDesignation = scanner.nextLine();
if (!empDesignation.equals("Manager") && !empDesignation.equals("Clerk") &&
!empDesignation.equals("Peon")) {
throw new InvalidEmployeeDetailsException("Invalid employee designation. Please
enter Manager, Clerk, or Peon.");
}

// Accept department id
System.out.print("Enter department id (1-5): ");
int deptId = scanner.nextInt();
if (deptId < 1 || deptId > 5) {
throw new InvalidEmployeeDetailsException("Department id should be an integer
between 1 and 5.");
}

// Print employee details


System.out.println("Employee details:");
System.out.println("Employee Id: " + empId);
System.out.println("Employee Name: " + empName);
System.out.println("Employee Designation: " + empDesignation);
System.out.println("Department Id: " + deptId);
} catch (InvalidEmployeeDetailsException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}

// Main method to create an instance of EmployeeDetails and call acceptDetails method


public static void main(String[] args) {
EmployeeDetails employeeDetails = new EmployeeDetails();
employeeDetails.acceptDetails();
}
}
Output:
Question4:
import java.util.Scanner;

public class Employee {


private final int pan;
private final String name;
private final double taxincome;
private double tax;

public Employee(int pan, String name, double taxincome) {


this.pan = pan;
this.name = name;
this.taxincome = taxincome;
}

public void cal() {


if (taxincome <= 250000)
tax = 0;
else if (taxincome <= 500000)
tax = (taxincome - 250000) * 0.1;
else if (taxincome <= 1000000)
tax = 30000 + ((taxincome - 500000) * 0.2);
else
tax = 50000 + ((taxincome - 1000000) * 0.3);
}

public void display() {


System.out.println("Pan Number\tName\tTax-Income\tTax");
System.out.printf("%d\t%s\t%.2f\t%.2f%n", pan, name, taxincome, tax);
}

public static void main(String[] args) {


Scanner in = new Scanner(System.in);

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


int pan = 0;
try {
pan = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid PAN number.");
System.exit(1);
}

System.out.print("Enter Name: ");


String name = in.nextLine();

double taxincome = 0;
boolean validIncome = false;
while (!validIncome) {
System.out.print("Enter taxable income: ");
try {
taxincome = Double.parseDouble(in.nextLine());
if (taxincome < 0) {
System.out.println("Taxable income cannot be negative.");
} else {
validIncome = true;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input for taxable income.");
}
}

Employee emp = new Employee(pan, name, taxincome);


emp.cal();
emp.display();

in.close();
}
}
Output:

You might also like