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

OOP-I Programs

The document contains a series of Java programming exercises focused on Object Oriented Programming concepts. Each exercise includes a problem statement followed by a complete Java code solution that demonstrates various programming techniques such as conditionals, loops, methods, and array manipulation. The exercises cover topics like number classification, triangle validity, Fibonacci series, and basic arithmetic operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

OOP-I Programs

The document contains a series of Java programming exercises focused on Object Oriented Programming concepts. Each exercise includes a problem statement followed by a complete Java code solution that demonstrates various programming techniques such as conditionals, loops, methods, and array manipulation. The exercises cover topics like number classification, triangle validity, Fibonacci series, and basic arithmetic operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Object Oriented Programming - Java

(Subject Code: 3140705) GTU

Programs

Q.1 Write a program to print if a number is positive, negative or zero.

import java.util.*;

class MyProgram {
public static void main(String[] args) {
int x;
Scanner sc = new Scanner(System.in);
x = sc.nextInt();
if (x > 0) {
System.out.println("Number is positive.");
} else if (x < 0) {
System.out.println("Number is negative.");
} else {
System.out.println("Number is zero.");
}
sc.close();
}
}

Q.2 Write a program which reads two numbers and based on the difference
between them, prints either the following message DIFFERENCE IS POSITIVE or
DIFFERENCE IS NEGATIVE.

import java.util.Scanner;

public class DifferenceChecker {


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

// Read the first number


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

// Read the second number


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

// Calculate the difference


int difference = num1 - num2;

// Check if the difference is positive or negative


if (difference > 0) {
System.out.println("Difference is positive.");
} else if (difference < 0) {
System.out.println("Difference is negative.");
} else {
System.out.println("The numbers are equal, so the difference is zero.");
}
scanner.close();
}
}

Q.3 Write a program to print if a number is odd or even.

import java.util.*;
public class MyProgram {
public static void main (String[] args) {
int x;
Scanner sc = new Scanner(System.in);
x = sc.nextInt();
if( x % 2 == 1 ) {
System.out.println("number is a odd");
}
if( x % 2 == 0 ) {
System.out.println("number is a even");
}
sc.close();
}
}
Q.4 A year is entered through the keyboard, write a program to determine
whether the year is leap year or not.

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

// Prompt the user to enter a year


System.out.print("Enter a year: ");
int year = scanner.nextInt();

// Check if the year is a leap year


if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}

scanner.close();
}
}

Q.5 Write a program to check whether a triangle is valid or not, when the three
angles of the triangle are entered through the keyboard. A triangle is valid if the
sum of all the three angles is equal to 180 degrees.

import java.util.Scanner;

public class TriangleValidityChecker {


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

// Prompt the user to enter three angles


System.out.println("Enter the three angles of the triangle:");
System.out.print("Angle 1: ");
int angle1 = scanner.nextInt();
System.out.print("Angle 2: ");
int angle2 = scanner.nextInt();
System.out.print("Angle 3: ");
int angle3 = scanner.nextInt();

// Check if the triangle is valid


if (isValidTriangle(angle1, angle2, angle3)) {
System.out.println("The triangle with angles " + angle1 + ", " + angle2 + ", and " +
angle3 + " is valid.");
} else {
System.out.println("The triangle with angles " + angle1 + ", " + angle2 + ", and " +
angle3 + " is not valid.");
}
scanner.close();
}
// Function to check if the triangle is valid
public static boolean isValidTriangle(int angle1, int angle2, int angle3) {
// Check if the sum of angles is equal to 180 degrees
return (angle1 + angle2 + angle3)==180 && angle1 > 0 && angle2 > 0 && angle3 > 0;
}
}

Q.6 Write a program to print the first n Fibonacci numbers.

class Fibonacci {

public static void main(String[]args) {


int a, b, c, n;
a=b=1;
for(n=1;n<=10;n++)
{
System.out.print(" "+a);
c=a+b;
a=b;
b=c;
}
}
}

Q.7 Write a program to find the maximum number from the given three integers.
import java.util.Scanner;

public class MaximumNumberFinder {


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

// Prompt the user to enter three integers


System.out.println("Enter three integers:");
System.out.print("Number 1: ");
int num1 = scanner.nextInt();
System.out.print("Number 2: ");
int num2 = scanner.nextInt();
System.out.print("Number 3: ");
int num3 = scanner.nextInt();

// Find the maximum number among the three


int max = num1; // Assume the first number is the maximum initially
if (num2 > max) {
max = num2;
}
if (num3 > max) {
max = num3;
}

// Display the maximum number


System.out.println("The maximum number is: " + max);

scanner.close();
}
}

Q.8 Write a menu driven program that allows users to enter five numbers and
then choose between finding the smallest, largest, sum or average. Use switch
case to determine the action to take. Provide an error message if an invalid
choice is entered.

import java.util.Scanner;

public class NumberProcessor {


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

// Array to store the entered numbers


double[] numbers = new double[5];

// Prompt the user to enter five numbers


System.out.println("Enter five numbers:");
for (int i = 0; i < 5; i++) {
System.out.print("Number " + (i + 1) + ": ");
numbers[i] = scanner.nextDouble();
}

// Display menu options


System.out.println("\nChoose an operation:");
System.out.println("1. Find the smallest number");
System.out.println("2. Find the largest number");
System.out.println("3. Calculate the sum");
System.out.println("4. Calculate the average");

// Read the user's choice


System.out.print("Enter your choice (1-4): ");
int choice = scanner.nextInt();

// Perform the chosen operation using switch case


switch (choice) {
case 1:
double smallest = findSmallest(numbers);
System.out.println("The smallest number is: " + smallest);
break;
case 2:
double largest = findLargest(numbers);
System.out.println("The largest number is: " + largest);
break;
case 3:
double sum = calculateSum(numbers);
System.out.println("The sum of the numbers is: " + sum);
break;
case 4:
double average = calculateAverage(numbers);
System.out.println("The average of the numbers is: " + average);
break;
default:
System.out.println("Invalid choice! Please enter a number between 1 and 4.");
}
scanner.close();
}
// Function to find the smallest number
public static double findSmallest(double[] numbers) {
double smallest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
return smallest;
}
// Function to find the largest number
public static double findLargest(double[] numbers) {
double largest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
return largest;
}
// Function to calculate the sum of numbers
public static double calculateSum(double[] numbers) {
double sum = 0;
for (double number : numbers) {
sum += number;
}
return sum;
}
// Function to calculate the average of numbers
public static double calculateAverage(double[] numbers) {
double sum = calculateSum(numbers);
return sum / numbers.length;
}
}
Q.9 Write a program to print odd numbers between 1 to n.

import java.util.*;

class WhileDemo {
public static void main(String[] args) {
int n, i = 1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number:");
n = sc.nextInt();
while (i <= n) {
if (i % 2 == 1)
System.out.println(i);
i++;
}
sc.close();
}
}

Q.10 Write a program to print factors of a given number.

import java.util.*;

class WhileDemo {
public static void main(String[] args) {
int i = 1, n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number: ");
n = sc.nextInt();
System.out.print("Factors: ");
while (i <= n) {
if (n % i == 0)
System.out.print(i + " ");
i++;
}
sc.close();
}
}
Q.11 Write a program that calculates and prints the sum of the even integers
from 1 to 10.

public class EvenSumCalculator {


public static void main(String[] args) {
int sum = 0;

// Loop through integers from 1 to 10


for (int i = 1; i <= 10; i++) {
// Check if the number is even
if (i % 2 == 0) {
// Add the even number to the sum
sum += i;
}
}

// Print the sum of even integers


System.out.println("Sum of even integers from 1 to 10: " + sum);
}
}

Q.12 Write a program to check whether the entered number is prime or not.

import java.util.Scanner;

public class PrimeChecker {


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

// Prompt the user to enter a number


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

// Check if the number is prime


boolean isPrime = checkPrime(number);

// Display the result


if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
scanner.close();
}

// Function to check if a number is prime


public static boolean checkPrime(int number) {
if (number <= 1) {
return false; // 1 and below are not prime
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false; // If divisible by any number other than 1 and itself, it's not
prime
}
}
return true; // If not divisible by any number other than 1 and itself, it's prime
}
}

Q.13 Write a program to store 5 numbers in an array and print them.

import java.util.*;

class ArrayDemo1 {
public static void main(String[] args) {
int i, n;
int[] a = new int[5]; // Creating an integer array of length 5
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Length:");
n = sc.nextInt(); // Taking input for the length of the array
for (i = 0; i < n; i++) {
System.out.print("Enter a[" + i + "]:");
a[i] = sc.nextInt(); // Taking input for each element of the array
}
for (i = 0; i < n; i++)
System.out.println(a[i]); // Printing out each element of the array
}
}
Q.14 Write a program to print elements of an array in reverse order.

import java.util.*;

public class RevArray {


public static void main(String[] args) {
int i, n;
int[] a;
Scanner sc = new Scanner(System.in);

System.out.print("Enter Size of an Array:");


n = sc.nextInt(); // Taking input for the size of the array

a = new int[n]; // Creating an integer array of size n

// Taking input for each element of the array


for (i = 0; i < n; i++) {
System.out.print("Enter a[" + i + "]:");
a[i] = sc.nextInt();
}

System.out.println("Reverse Array");
// Printing out the elements of the array in reverse order
for (i = n - 1; i >= 0; i--)
System.out.println(a[i]);
}
}

Q.15 Write a program to count positive number, negative number and zero from
an array of n size.

import java.util.*;

class ArrayDemo1 {
public static void main(String[] args) {
int n, pos = 0, neg = 0, z = 0;
int[] a = new int[5]; // Creating an integer array of length 5
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Length:");
n = sc.nextInt(); // Taking input for the length of the array

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


System.out.print("Enter a[" + i + "]:");
a[i] = sc.nextInt(); // Taking input for each element of the array

// Counting positive, negative, and zero elements


if (a[i] > 0)
pos++;
else if (a[i] < 0)
neg++;
else
z++;
}

// Printing out the counts of positive, negative, and zero elements


System.out.println("Positive no=" + pos);
System.out.println("Negative no=" + neg);
System.out.println("Zero no=" + z);
}
}

Q.16 Write a program to find the smallest and largest element from an array.

import java.util.*;

public class LargestSmallestFromArray {


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

// Input the size of the array


System.out.print("Enter the size of the array: ");
int size = sc.nextInt();
int[] array = new int[size];

// Input elements of the array


System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
System.out.print("Enter element " + (i + 1) + ": ");
array[i] = sc.nextInt();
}
// Finding the largest and smallest elements
int largest = array[0];
int smallest = array[0];

for (int i = 1; i < size; i++) {


if (array[i] > largest) {
largest = array[i];
}
if (array[i] < smallest) {
smallest = array[i];
}
}

// Output the largest and smallest elements


System.out.println("Largest element: " + largest);
System.out.println("Smallest element: " + smallest);
}
}

Q.17 Write a program to demonstrate the usage of method to perform addition.

class MethodDemo {
public static void main(String[] args) {
int a = 10, b = 20, c;
MethodDemo md = new MethodDemo();
c = md.add(a, b); // Calling the add method with parameters a and b
System.out.println("a + b = " + c);
}
// Method to add two integers
int add(int i, int j) {
return i + j; // Returning the sum of the two integers
}
}

Q.18 Write a program to calculate the power of a number using method.

import java.util.*;

public class PowerMethDemo1 {


public static void main(String[] args) {
int num, pow, res;
Scanner sc = new Scanner(System.in);

// Input number and power from the user


System.out.print("Enter num: ");
num = sc.nextInt();
System.out.print("Enter pow: ");
pow = sc.nextInt();

// Create an instance of PowerMethDemo1 class and call the power method


PowerMethDemo1 pmd = new PowerMethDemo1();
res = pmd.power(num, pow);
// Print the result
System.out.println("Answer = " + res);
}
// Method to calculate the power of a number
int power(int a, int b) {
int i, r = 1;
for (i = 1; i <= b; i++) {
r = r * a;
}
return r;
}
}

Q.19 Write a program to demonstrate method overloading.

public class MethodOverloadingExample {


// Method to add two integers
public static int add(int a, int b) {
return a + b;
}
// Method to add three integers
public static int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two doubles


public static double add(double a, double b) {
return a + b;
}
// Method to concatenate two strings
public static String add(String a, String b) {
return a + b;
}

public static void main(String[] args) {


// Test method overloading
System.out.println("Sum of 5 and 7: " + add(5, 7));
System.out.println("Sum of 5, 7, and 9: " + add(5, 7, 9));
System.out.println("Sum of 5.5 and 7.3: " + add(5.5, 7.3));
System.out.println("Concatenation of 'Hello' and 'World': " + add("Hello", "World"));
}
}

Q.20 Write a program which declares an integer array of 10 elements. Initialize


array and define following methods with the specified header:
(i) public static int add(int [] array) print addition of all elements of array.
(ii) public static int max(int [] array) print the maximum element of the array.
(iii) public static int search(int [] array, int key) search element key in array and
return index of it. If an element is not found, the method will return -1.

import java.util.Scanner;

public class ArrayOperations {


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

// Declare and initialize an integer array of 10 elements


int[] array = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
// Print the addition of all elements of the array
System.out.println("Sum of all elements: " + add(array));
// Print the maximum element of the array
System.out.println("Maximum element: " + max(array));

// Prompt the user to enter a key to search in the array


System.out.print("Enter the element to search: ");
int key = scanner.nextInt();
// Search for the key in the array and print the result
int index = search(array, key);
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found in the array.");
}
scanner.close();
}
// Method to calculate the sum of all elements in the array
public static int add(int[] array) {
int sum = 0;
for (int num : array) {
sum += num;
}
return sum;
}
// Method to find the maximum element in the array
public static int max(int[] array) {
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
// Method to search for an element in the array and return its index
// Returns -1 if the element is not found
public static int search(int[] array, int key) {
for (int i = 0; i < array.length; i++) {
if (array[i] == key) {
return i; // Element found, return its index
}
}
return -1; // Element not found
}
}

Q.21 Write a program that defines a class named StopWatch.


The class contains: • Private data fields startTime and endTime with getter
methods. 2 • no-arg constructor that initializes startTime with the current time.
• A method named start() that resets the startTime to the current time. • A
method named stop() that sets the endTime to the current time. • A method
named getElapsedTime() that returns the elapsed time for the stopwatch in
milliseconds. • Declare object of StopWatch to demonstrate stop watch.
Hint: Use System.currentTimeMillis() to get current time in milliseconds.

public class StopWatch {


private long startTime;
private long endTime;

// Constructor to initialize startTime with the current time


public StopWatch() {
startTime = System.currentTimeMillis();
}
// Method to reset startTime to the current time
public void start() {
startTime = System.currentTimeMillis();
}
// Method to set endTime to the current time
public void stop() {
endTime = System.currentTimeMillis();
}
// Method to calculate and return the elapsed time in milliseconds
public long getElapsedTime() {
return endTime - startTime;
}

// Getter method for startTime


public long getStartTime() {
return startTime;
}
// Getter method for endTime
public long getEndTime() {
return endTime;
}

public static void main(String[] args) {


// Create an object of StopWatch
StopWatch stopwatch = new StopWatch();
// Start the stopwatch
stopwatch.start();

// Simulate some process by sleeping the thread for a while


try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
// Stop the stopwatch
stopwatch.stop();
// Print the elapsed time
System.out.println("Elapsed Time: " + stopwatch.getElapsedTime() + "
milliseconds");
}
}

Q.22 Create a two dimensional array. Instantiate and Initialize it.

public class TwoDArrayExample {


public static void main(String[] args) {
// Create a two-dimensional array
int[][] twoDArray;

// Instantiate the array with dimensions 3x3


twoDArray = new int[3][3];

// Initialize the array elements


twoDArray[0][0] = 1;
twoDArray[0][1] = 2;
twoDArray[0][2] = 3;
twoDArray[1][0] = 4;
twoDArray[1][1] = 5;
twoDArray[1][2] = 6;
twoDArray[2][0] = 7;
twoDArray[2][1] = 8;
twoDArray[2][2] = 9;

// Print the elements of the array


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

Q.23 Write a program using class Person to display name and age with method.

class MyProgram {
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
p1.name = "modi";
p1.age = 71;
p2.name = "bachchan";
p2.age = 80;
p1.displayName();
p2.displayName();
p1.displayAge();
p2.displayAge();
}
}

class Person {
String name;
int age;

public void displayName() {


System.out.println("name=" + name);
}

public void displayAge() {


System.out.println("age=" + age);
}
}

Q.24 Write a program using class Rectangle to calculate the area with method.

import java.util.*;
class MyProgram {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Scanner sc = new Scanner(System.in);
System.out.print("Enter height: ");
r1.height = sc.nextFloat();
System.out.print("Enter width: ");
r1.width = sc.nextFloat();
r1.calArea();
}
}

class Rectangle {
float height;
float width;
public void calArea() {
System.out.println("Area = " + height * width);
}
}

Q.25 Design a java class Rectangle which contains following field and methods:
(i) Field: length, width: int (ii) Default Constructor: initialize all fields with 0 value
(iii) Method: int getArea() will return area of rectangle.

public class Rectangle {


// Fields
private int length;
private int width;

// Default Constructor
public Rectangle() {
// Initialize all fields with 0 value
this.length = 0;
this.width = 0;
}

// Parameterized Constructor
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
// Method to calculate the area of the rectangle
public int getArea() {
return length * width;
}
// Getters and Setters
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public static void main(String[] args) {
// Create a Rectangle object using default constructor
Rectangle rectangle1 = new Rectangle();
// Display area of rectangle
System.out.println("Area of rectangle1: " + rectangle1.getArea());
// Create a Rectangle object using parameterized constructor
Rectangle rectangle2 = new Rectangle(5, 4);
// Display area of rectangle
System.out.println("Area of rectangle2: " + rectangle2.getArea());
}
}

Q.26 Create a class called Employee that includes: I. Three instance variables— id
(type String), name (type String) and monthly_salary (double). II. A default
constructor that initializes the three instance variables. III. A setter and a getter
method for each instance variable (for example for id variable void setId(String
id), String getId( )). IV. displayEmployee() method for displaying employee details.
Write a driver class named EmployeeTest that demonstrates class Employee’s
capabilities. Create two Employee objects and display each object’s yearly salary.
Then give each Employee a 10% raise and display each Employee’s yearly salary
again.

class Employee {
private String id;
private String name;
private double monthlySalary;
// Default constructor
public Employee() {
id = "";
name = "";
monthlySalary = 0.0;
}
// Setter methods
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}

public void setMonthlySalary(double monthlySalary) {


this.monthlySalary = monthlySalary;
}
// Getter methods
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getMonthlySalary() {
return monthlySalary;
}
// Method to display employee details
public void displayEmployee() {
System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);
System.out.println("Monthly Salary: $" + monthlySalary);
}
// Method to calculate and display yearly salary
public void displayYearlySalary() {
double yearlySalary = monthlySalary * 12;
System.out.println("Yearly Salary for " + name + ": $" + yearlySalary);
}
// Method to give a 10% raise
public void giveRaise() {
monthlySalary *= 1.10; // Increase salary by 10%
}
}
public class EmployeeTest {
public static void main(String[] args) {
// Create two Employee objects
Employee employee1 = new Employee();
Employee employee2 = new Employee();
// Set details for employee1
employee1.setId("EMP001");
employee1.setName("John Doe");
employee1.setMonthlySalary(5000.0);
// Set details for employee2
employee2.setId("EMP002");
employee2.setName("Jane Smith");
employee2.setMonthlySalary(6000.0);
// Display yearly salary for each employee
System.out.println("Yearly Salary Before Raise:");
employee1.displayYearlySalary();
employee2.displayYearlySalary();
System.out.println();
// Give a 10% raise to each employee
employee1.giveRaise();
employee2.giveRaise();
// Display yearly salary after raise
System.out.println("Yearly Salary After Raise:");
employee1.displayYearlySalary();
employee2.displayYearlySalary();
}
}
Q.27 Write a program that creates a Random object with seed 1000 and displays
the first 100 random integers between 1 and 49 using the NextInt (49) method.

import java.util.Random;

public class RandomIntegers {


public static void main(String[] args) {
// Create a Random object with seed 1000
Random random = new Random(1000);
// Display the first 100 random integers between 1 and 49
System.out.println("First 100 random integers between 1 and 49:");
for (int i = 0; i < 100; i++) {
int randomNumber = random.nextInt(49) + 1;
// Generate a random integer between 1 and 49
System.out.print(randomNumber + " ");
if ((i + 1) % 10 == 0) { // Print 10 numbers per line
System.out.println();
}
}
}
}

Q.28 Write a method to enter two integers and compute the gcd of two integers.

public class GCDCalculator {


public static void main(String[] args) {
// Test the method
int num1 = 48;
int num2 = 18;
int gcd = findGCD(num1, num2);
System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
}
// Method to compute the GCD of two integers
public static int findGCD(int num1, int num2) {
// Ensure num1 is greater than or equal to num2
if (num2 > num1) {
int temp = num1;
num1 = num2;
num2 = temp;
}
// Apply Euclidean algorithm to find GCD
while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1; // GCD is stored in num1
}
}

Q.29 Write a test program that prompts the user to enter ten numbers, invoke a
method to reverse the numbers, and display the numbers.

import java.util.Scanner;

public class NumberReverser {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[10];
// Prompt the user to enter ten numbers
System.out.println("Enter ten numbers:");
for (int i = 0; i < 10; i++) {
numbers[i] = scanner.nextInt();
}
// Reverse the numbers
reverseNumbers(numbers);
// Display the reversed numbers
System.out.println("Reversed numbers:");
for (int number : numbers) {
System.out.print(number + " ");
}
scanner.close();
}
// Method to reverse the numbers
public static void reverseNumbers(int[] numbers) {
int left = 0;
int right = numbers.length - 1;
while (left < right) {
// Swap the elements at positions left and right
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
// Move the pointers towards the center
left++;
right--;
}
}
}

Q.30 The employee list for a company contains employee code, name,
designation and basic pay. The employee is given HRA of 10% of the basic pay
and DA of 45% of the basic pay. The total pay of the employee is calculated as
Basic pay+HRA+ DA. Write a class to define the details of the employee. Write a
constructor to assign the required initial values. Add a method to calculate HRA,
DA and Total pay and print them out. Write another class with a main method.
Create objects for three different employees and calculate the HRA, DA and total
pay.

class Employee {
private int employeeCode;
private String name;
private String designation;
private double basicPay;

// Constructor to assign initial values


public Employee(int employeeCode, String name, String designation, double
basicPay) {
this.employeeCode = employeeCode;
this.name = name;
this.designation = designation;
this.basicPay = basicPay;
}
// Method to calculate HRA
public double calculateHRA() {
return 0.10 * basicPay;
}
// Method to calculate DA
public double calculateDA() {
return 0.45 * basicPay;
}
// Method to calculate total pay
public double calculateTotalPay() {
return basicPay + calculateHRA() + calculateDA();
}
// Method to display employee details and calculated values
public void displayDetails() {
System.out.println("Employee Code: " + employeeCode);
System.out.println("Name: " + name);
System.out.println("Designation: " + designation);
System.out.println("Basic Pay: $" + basicPay);
System.out.println("HRA: $" + calculateHRA());
System.out.println("DA: $" + calculateDA());
System.out.println("Total Pay: $" + calculateTotalPay());
System.out.println();
}
}
public class EmployeeTest {
public static void main(String[] args) {
// Create objects for three different employees
Employee employee1 = new Employee(1001, "John Doe", "Manager", 50000);
Employee employee2 = new Employee(1002, "Jane Smith", "Engineer", 40000);
Employee employee3 = new Employee(1003, "Alice Johnson", "Assistant", 30000);

// Display details for each employee


System.out.println("Employee Details:");
employee1.displayDetails();
employee2.displayDetails();
employee3.displayDetails();
}
}

Q.31 Write a Java program to count the number of words in a given string.
public class WordCounter {
public static void main(String[] args) {
String str = "Hello world, how are you?";
// Call the method to count the number of words
int wordCount = countWords(str);

// Display the count of words


System.out.println("Number of words in the string: " + wordCount);
}
public static int countWords(String str) {
// Trim leading and trailing spaces
str = str.trim();
// If the string is empty, return 0
if (str.isEmpty()) {
return 0;
}
// Split the string into words using one or more whitespace characters as delimiter
String[] words = str.split("\\s+");
// Return the count of words
return words.length;
}
}

Q.32 Write a Java program to count the number of occurrences of substring in a


given string.
public class SubstringCounter {
public static void main(String[] args) {
String str = "hello world hello hello";
// Substring to search for
String substring = "hello";
// Call the method to count occurrences of substring in the given string
int count = countSubstringOccurrences(str, substring);
// Display the count of occurrences
System.out.println("Number of occurrences of '" + substring + "' in the string: " +
count);
}
public static int countSubstringOccurrences(String str, String substring) {
int count = 0;
int index = 0;
// Iterate through the string and count occurrences of substring
while ((index = str.indexOf(substring, index)) != -1) {
count++;
index += substring.length();
}
return count;
}
}
Q.33 Write aJava program using class Cube and calculate the area of two objects.

class Cube {
private double side;
// Constructor to initialize the side of the cube
public Cube(double side) {
this.side = side;
}
// Method to calculate the surface area of the cube
public double calculateSurfaceArea() {
return 6 * side * side;
}
}
public class CubeAreaCalculator {
public static void main(String[] args) {
// Create two cube objects with different side lengths
Cube cube1 = new Cube(5.0);
Cube cube2 = new Cube(3.0);
// Calculate the surface area of each cube
double surfaceArea1 = cube1.calculateSurfaceArea();
double surfaceArea2 = cube2.calculateSurfaceArea();
// Display the surface area of each cube
System.out.println("Surface area of cube 1: " + surfaceArea1);
System.out.println("Surface area of cube 2: " + surfaceArea2);
}
}

You might also like