0% found this document useful (0 votes)
19 views54 pages

2 - 23BIT092 - Hil Kalathiya

hil

Uploaded by

cisojep689
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)
19 views54 pages

2 - 23BIT092 - Hil Kalathiya

hil

Uploaded by

cisojep689
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/ 54

Name : HIL KALATHIYA B.

TECH (ICT)
Roll No: 23BIT092

PANDIT DEENDAYAL ENERGY UNIVERSITY


SCHOOL OF TECHNOLOGY

Object Oriented Concept


&Programming Lab (20IC203P)

PRACTICALS
B.Tech. (Information and
Communication Technology)
Semester 2

SUBMITTED TO: SUBMITTED BY:

ISHAAN MEHTA HlL KALATHIYA (23BIT092)

Name: Hil Kalathiya Roll No: 23BIT092 1 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Exp
. Title of Lab Work( Module-1) Page Signature
No.
1 Introduction to JAVA 05
Write a Program in JAVA to generate first n prime
2 numbers. 10

3 Write a program to enter two numbers and perform 11


mathematical operations on them
4 Write a program to calculate percentage marks of 12
students if marks of 6 subjects are given.
5 Write program in java to find maximum number of 13
three numbers using condition operator.
Write a program accepting a line and check how many
6 14
vowels and consonants it.

7 Write a program to count the number of words that 16


start with capital letters.
8 Counting Vowels in Sentences Until User Quits 18

9 Write an interactive program to print a string entered in 20


a pyramid form
10 Write an interactive program to print a diamond shape. 22

11 Write a Java Program to find area of Geometric figures 24


using method Overloading.
12 Write a program in Java to create a simple scientific 26
calculator using Math Class.
13 Write a program in Java to sort the elements of list so 30
that they are in ascending order.
14 Write a program in Java to multiply two matrixes. 31

Name: Hil Kalathiya Roll No: 23BIT092 2 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Exp
. Title of Lab Work(Module-2) Page Signature
No.
(LAB-3)

a) Create a Distance class with two coordinate data


members, a constructor to initialize them, and a method
to calculate the distance between two points.
1 b) Create a TIME class with hours, minutes, and seconds. 34
Implement constructors to initialize the object to zero or
constant values, a method to add two TIME objects, and
a method to display time in HH:MM:SS format. Use the
main function to create two TIME objects, add them, and
display the result.
(LAB -4)
Write a Java program with an abstract Shape class
2 containing two integers and an empty printArea() 38
method. Create Rectangle, Triangle, and Circle classes
that extend Shape and implement printArea() to
calculate and print their respective areas.
(LAB -4)
Write a Java program with an abstract Vehicle class
containing abstract methods startEngine() and
3 stopEngine(). Create subclasses Car and Motorcycle that 40
extend Vehicle and implement the engine methods. Add
functions in each subclass to define specific
characteristics like company name, model number, and
number of wheels.
(LAB -5)
Design a Java program with an Employee base class
4 (name, address, salary, job title) and two subclasses: 43
Manager and Developer. Implement salary increments:
10% for Managers and 8% for Developers.
(LAB -6)
Write a Java program with an abstract interface
Polygon containing abstract methods calcArea(),
calcPeri(), and a concrete method display() to display
6 area and perimeter. Create a Square class implementing 46
Polygon with a float side and constructor to initialize the
side. Create a Rectangle class implementing Polygon
with float length and float breadth, along with a
constructor to initialize them. Outside the package,

Name: Hil Kalathiya Roll No: 23BIT092 3 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

create a class that imports the package, instantiates


objects of Square and Rectangle, and calls the methods
to calculate and display the area and perimeter.
(LAB -7)
Write a Java program with an interface Playable that
contains a method play() which takes no arguments and
7 returns void. Create three classes Football, Volleyball, 50
and Basketball that implement the Playable interface
and override the play() method to simulate playing the
respective sports.
(LAB -8)
Write a Java program that prompts the user to enter a
paragraph and performs the following operations:
a. Count the total number of sentences in the paragraph
and the total number of words in each sentence. b.
8 Calculate the total number of characters in the 52
paragraph and find the occurrence of each character,
displaying the information in a formatted way. c. Allow
the user to search for a specific word in the paragraph,
printing the position of the word if found, or an
appropriate message if not.

9
10
11
12
13
14

Name: Hil Kalathiya Roll No: 23BIT092 4 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 1: Introduction to JAVA

Q1: Hello World!


Introduction:
Java is a high-level, object-oriented programming language known for its platform
independence, meaning code written in Java can run on any system with a Java Virtual
Machine (JVM). It follows the "Write Once, Run Anywhere" (WORA) principle, offering
strong memory management and multi-threading capabilities. Java is widely used for
developing web applications, Android apps, enterprise software, and more.

Program:

class hello {
public static void main(String[] args){
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
System.out.println("Hello World!");
System.out.println("Jay Swaminarayan!");
}
}

Output:

Conclusions:
This code demonstrates how to define a basic Java class with a main method that prints
multiple lines of text to the console using System.out.println().

Name: Hil Kalathiya Roll No: 23BIT092 5 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Q2: Declaration, Initialization and printing of variables of all


data types.

Introduction:
Java is a high-level, object-oriented programming language known for its platform
independence, meaning code written in Java can run on any system with a Java Virtual
Machine (JVM). It follows the "Write Once, Run Anywhere" (WORA) principle, offering
strong memory management and multi-threading capabilities. Java is widely used for
developing web applications, Android apps, enterprise software, and more.

Program:
class variable {
public static void main(String[] args){
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
int i = 59;
float j = 3.567f;
char c = 'H';
System.out.println("THe Value Of integer 'i' is : " + i);
System.out.println("The Value Of float 'j' is : " + j);
System.out.println("The Value Of character 'c' is : " + c);
}
}

Output:

Conclusions:
This code illustrates how to declare and initialize variables of different data types
(int, float, and char) in Java. It shows how to concatenate text and variables using
the + operator within System.out.println() statements. Additionally, it highlights the
importance of type-specific suffixes (like f for float values) to avoid compilation
errors.

Name: Hil Kalathiya Roll No: 23BIT092 6 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Q3: Use scanner class to input all data types and print.
Introduction:
This code illustrates how to declare and initialize variables of different data types (int,
float, and char) in Java. It shows how to concatenate text and variables using the +
operator within System.out.println() statements. Additionally, it highlights the
importance of type-specific suffixes (like f for float values) to avoid compilation errors.

Program:
import java.util.Scanner;
class scan{
public static void main(String arg[]){
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner my = new Scanner(System.in);
System.out.print("Enter Your Name : ");
String s = my.nextLine();
System.out.print("Enter Some Integer : ");
int i = my.nextInt();
System.out.print("Enter Some Float : ");
float j = my.nextFloat();
System.out.println(s);
System.out.println(i);
System.out.println(j);

}
}

Output:

Conclusions:
This code demonstrates how to use the Scanner class to take user input of different data
types, including String, int, and float. It also highlights the importance of appropriate
methods like nextLine(), nextInt(), and nextFloat() for reading specific types of input.

Name: Hil Kalathiya Roll No: 23BIT092 7 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Q4: If else question: If greater than 18, you are an adult, If less
than 18, you are minor.

Introduction:
This code illustrates how to declare and initialize variables of different data types (int,
float, and char) in Java. It shows how to concatenate text and variables using the +
operator within System.out.println() statements. Additionally, it highlights the
importance of type-specific suffixes (like f for float values) to avoid compilation errors.

Program:
import java.util.Scanner;
class else_if {
public static void main(String[] arg){
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner a = new Scanner(System.in);
System.out.print("Enter Your Age:");
int age = a.nextInt();
if(age<18){
System.out.println("You minor now.\n you cannot drive a
car.");
}
else{
System.out.println("You are major now.\n you can drive a
car.");
}
}

Output:

Conclusions:
This code teaches the use of if-else conditional statements to make decisions based
on user input. It demonstrates how to compare integer values (like age) and execute
different code blocks based on the condition, enabling dynamic program behavior.

Name: Hil Kalathiya Roll No: 23BIT092 8 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Q5: Print “CODING IS FUN, ENJOY IT”.

Program:
class fun{
public static void main(String[] args){
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
System.out.println("CODING IS FUN, ENJOY IT.");
}
}

Output:

Name: Hil Kalathiya Roll No: 23BIT092 9 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 2: Write a Program in JAVA to generate first n


prime numbers.
Introduction:
Loops in Java allow for repeating a block of code multiple times based on a condition.
Common loop types include for, while, and do-while—where for is used when the
number of iterations is known, while repeats if a condition is true, and do-while
guarantees at least one execution. Loops help in reducing redundancy and improving
code efficiency.

Program:
import java.util.Scanner;
class prime{
public static void main(String[] args){
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner pr = new Scanner(System.in);
System.out.print("Enter a number : ");
int prime = pr.nextInt();
for(int i=2; i<prime; i++){
if (prime%i==0){
System.out.println("This number is not prime number");
break;
}
}
pr.close();
}
}
Output:

Conclusions:
This code checks if a given number is not a prime number by using a for loop to find any
divisor. If a divisor is found, the program prints a message and exits using break.

Name: Hil Kalathiya Roll No: 23BIT092 10 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 3: Write a program to enter two numbers and


perform mathematical operations on them.
Introduction:
In Java, arithmetic operations involve basic mathematical calculations like addition (+),
subtraction (-), multiplication (*), division (/), and modulo (%). These operators can be
used with primitive data types such as int, float, and double. Arithmetic expressions
follow operator precedence, with multiplication, division, and modulo evaluated before
addition and subtraction.

Program:
import java.util.Scanner;
import java.util.Scanner;
class math{
public static void main(String[] args){
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner math = new Scanner(System.in);
System.out.print("Enter the number a:");
float a = math.nextFloat();
System.out.print("Enter the number b:");
float b = math.nextFloat();
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Modulus: " + (a % b));
math.close();
}
}
Output:

Conclusions:
This code demonstrates how to perform and display basic arithmetic operations
(addition, subtraction, multiplication, division, and modulus) on user-input numbers in
Java.

Name: Hil Kalathiya Roll No: 23BIT092 11 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 4: Write a program to calculate percentage


marks of students if marks of 6 subject are given.
Introduction:
Type casting in Java refers to converting a variable from one data type to another, either
implicitly (automatic widening) or explicitly (narrowing using a cast). Widening occurs
when a smaller type (like int) is converted to a larger type (like double), while narrowing
requires explicit casting (e.g., (int) 3.14). It ensures compatibility between data types but
may lead to precision loss or overflow during narrowing.
Program:
class percent {
public static void main(String arg[]) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
int maths = 70, physics = 80, chemistry = 75, DLD = 90, EEE = 80,
Social = 95, total = 600;
float perc;
perc = (float) ((maths + physics + chemistry + DLD + EEE +
Social) * 100) / total;
System.out.println("The percentage of the Student is : " + perc);
}
}

Output:

Conclusions:
This code demonstrates how to calculate the percentage by summing marks from
different subjects and applying the percentage formula. It also highlights the use of type
casting to ensure correct division and avoid integer truncation in the calculation.

Name: Hil Kalathiya Roll No: 23BIT092 12 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 5: Write program in java to find maximum


number of three number using condition operator.
Introduction:
In Java, conditional (ternary) operator is a shorthand for if-else statements,
represented as condition ? expression1 : expression2. It evaluates a boolean condition
and returns expression1 if the condition is true, otherwise it returns expression2. This
operator is useful for writing concise conditional expressions in a single line.

Program:
import java.util.*;

class max {
public static void main(String agr[]) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner hil = new Scanner(System.in);
System.out.print("Enter Number A: ");
int a = hil.nextInt();
System.out.print("Enter Number B: ");
int b = hil.nextInt();
System.out.print("Enter Number C: ");
int max, c = hil.nextInt();
max = a>b?a>c?a:c:b>c?b:c;
System.out.println("Maximum Number is : " + max);
hil.close();
}
}

Output:

Conclusions:
This code demonstrates the use of the conditional (ternary) operator to find the
maximum of three numbers. It showcases how nested ternary operators can efficiently
replace multiple if-else conditions to evaluate expressions in a compact way.

Name: Hil Kalathiya Roll No: 23BIT092 13 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 6: Write a program accept a line and check


that how many vowels and consonants it contains.
Introduction:
This code demonstrates string traversal using a for loop to classify characters as
vowels or consonants. It converts the input to lowercase to ensure case-insensitive
comparison and uses conditional statements to increment counters based on the
character type. This approach efficiently counts and displays the total vowels and
consonants in the given input.

Program:
import java.util.*;

class VowConso {
public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner hil = new Scanner(System.in);
System.out.print("Enter the Line : ");
String line = hil.nextLine();
int conso = 0, vowel = 0;
line = line.toLowerCase();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == 'a'
|| line.charAt(i) == 'e'
|| line.charAt(i) == 'i'
|| line.charAt(i) == 'o'
|| line.charAt(i) == 'u') {
conso++;
} else {
vowel++;
}
}
System.out.println("Total number of Vowels Are : " + vowel);
System.out.println("Total number of Consonants Are : " + conso);
hil.close();
}
}

Name: Hil Kalathiya Roll No: 23BIT092 14 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Output:

Conclusions:
This code efficiently counts the number of vowels and consonants in a given string by
iterating through each character. It ensures case-insensitivity by converting the input to
lowercase before comparison.

Name: Hil Kalathiya Roll No: 23BIT092 15 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 7: Write a program to count the number of


capital letters.
Introduction:
A program to count capital letters involves iterating through a string and checking each
character using conditions like Character.isUpperCase(). This process ensures that only
uppercase letters are identified and counted. It demonstrates string traversal,
conditional statements, and character handling in Java.

Program:
import java.util.*;

class capital {
public static void main(String[] arg) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner hil = new Scanner(System.in);
int cap = 0, small = 0, num = 0;
System.out.print("Enterr a One line: ");
String line = hil.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) >= 65 && line.charAt(i) <= 90) {
cap++;
} else if (line.charAt(i) >= 97 && line.charAt(i) <= 122) {
small++;
} else if (line.charAt(i) >= 48 && line.charAt(i) <= 57) {
num++;
}
}
System.out.println("Number of capital letters in this string are:
" + cap);
System.out.println("Number of small letters in this string are: "
+ small);
System.out.println("Number of Digites in this string are: " +
num);
hil.close();
}
}

Name: Hil Kalathiya Roll No: 23BIT092 16 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Output:

Conclusions:
This code demonstrates string traversal using a for loop and counts capital letters,
small letters, and digits by comparing ASCII values. It showcases the use of character-
level conditions to classify and track different types of characters in each input.

Name: Hil Kalathiya Roll No: 23BIT092 17 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 8: Counting Vowels in Sentences Until User


Quits
Introduction:
This code illustrates the use of a method to count vowels in multiple lines of user input
until the user decides to quit. It employs a while loop for continuous input and checks
each character against a set of vowels using conditional statements. The program also
demonstrates string manipulation by converting the input to lowercase for case-
insensitive comparison and emphasizes the importance of resource management by
closing the Scanner after use.

Program:
import java.util.Scanner;

class vowel {

public static int countVowel() {


int count = 0;
Scanner hil = new Scanner(System.in); // Initialize scanner once

while (true) {
System.out.print("Enter a one-liner or 'Quit': ");
String line = hil.nextLine();

if (line.equalsIgnoreCase("quit")) {
break; // Exit loop on 'quit'
}
line = line.toLowerCase();
int length = line.length();

for (int j = 0; j < length; j++) {


char ch = line.charAt(j);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==
'u') {
count++;
}
}
}
hil.close(); // Close scanner after the loop
return count;
}
public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
int count = countVowel();
System.out.println("The number of vowels is: " + count);
}
}

Name: Hil Kalathiya Roll No: 23BIT092 18 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Output:

Conclusions:
This code counts the total number of vowels entered across multiple inputs using a
while loop until the user types "quit" to exit. It demonstrates method usage by
encapsulating the vowel counting logic inside countVowel(). The program highlights
string traversal to inspect each character and ensures case-insensitive comparison
by converting input to lowercase.

Name: Hil Kalathiya Roll No: 23BIT092 19 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 9: Write an interactive program to print a


string entered in a pyramid form.
Introduction:
This code demonstrates the use of nested loops to print a pattern based on a user-
provided string. It employs spacing logic in the first for loop to align characters in a
triangular format and uses the second loop to print characters incrementally. This
showcases string manipulation, loop control, and formatted output for pattern
generation.

Program:
import java.util.Scanner;

public class partten {


public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
int length = input.length();
for (int i = 0; i < length; i++) {
for (int j = 0; j < length - i - 1; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print(input.charAt(k) + " ");
}
System.out.println();
}
scanner.close();
}
}

Output:

Name: Hil Kalathiya Roll No: 23BIT092 20 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Conclusions:
This code counts the total number of vowels entered across multiple inputs using a This
code generates a triangular pattern by progressively printing characters from the input string with
proper alignment. It demonstrates the use of nested loops for structured formatting and pattern
creation.

Name: Hil Kalathiya Roll No: 23BIT092 21 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 10: Write an interactive program to print


diamond shape.
Introduction:
This code generates a diamond pattern using nested loops, where the user provides the height
of the diamond. It demonstrates loop control by first printing the upper half with decreasing
spaces and increasing stars, followed by the lower half with increasing spaces and decreasing
stars. Conditional checks within the loops ensure proper placement of stars and spaces,
resulting in a symmetric diamond shape.

Program:
import java.util.Scanner;

public class partten {


public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = scanner.nextInt();
scanner.close();

printDiamond(n);
}
public static void printDiamond(int n) {
int space = n - 1;

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


for (int j = 1; j <= space; j++) {
System.out.print(" ");
}
space--;
for (int j = 1; j <= 2 * i - 1; j++) {
if (j % 2 == 0) {
System.out.print(" ");
} else {
System.out.print("*");
}
}
System.out.println();
}
space = 1;
for (int i = 1; i <= n - 1; i++) {
for (int j = 1; j <= space; j++) {
System.out.print(" ");

Name: Hil Kalathiya Roll No: 23BIT092 22 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

}
space++;
for (int j = 1; j <= 2 * (n - i) - 1; j++) {
if (j % 2 == 0) {
System.out.print(" ");
} else {
System.out.print("*");
}
}
System.out.println();
}
}
}

Output:

Conclusions:
This code teaches how to use nested loops to create symmetrical patterns and control
spacing for alignment. It also shows the use of conditional logic within loops to alternate
between stars and spaces for structured formatting.

Name: Hil Kalathiya Roll No: 23BIT092 23 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 11: Write a Java Program to find Geometric


figures using the method Overloading.
Introduction:
This code demonstrates method overloading in Java, where multiple methods share the
same name but differ in parameters or argument types. It showcases how the area()
method is overloaded to calculate areas for different shapes—rectangle, circle, and
triangle. Method overloading improves code readability and reusability by enabling
multiple behaviours under a single method name.

Program:
public class overloading {
// Method to calculate the area of a rectangle
public double area(double length, double width) {
return length * width;
}
// Method to calculate the area of a circle
public double area(double radius) {
return Math.PI * radius * radius;
}
// Method to calculate the area of a triangle
public double area(double base, double height, boolean isTriangle) {
if (isTriangle) {
return 0.5 * base * height;
}
return 0.0;
}
public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
overloading obj = new overloading();
// Calculate the area of a rectangle
double rectangleArea = obj.area(5.0, 3.0);
System.out.println("Area of Rectangle: " + rectangleArea);
// Calculate the area of a circle
double circleArea = obj.area(4.0);
System.out.println("Area of Circle: " + circleArea);
// Calculate the area of a triangle
double triangleArea = obj.area(6.0, 4.0, true);
System.out.println("Area of Triangle: " + triangleArea);
}
}

Name: Hil Kalathiya Roll No: 23BIT092 24 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Output:

Conclusions:
This code teaches how to use method overloading to perform multiple operations under
the same method name based on different parameter lists. It emphasizes the
importance of polymorphism for creating flexible and maintainable code.

Name: Hil Kalathiya Roll No: 23BIT092 25 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 12: Write a program in Java to create a simple


scientific calculator using Math Class.
Introduction:
This program implements a scientific calculator in Java using the Math class for various
mathematical operations like power, square root, and trigonometric functions. It allows the user
to perform basic arithmetic (addition, subtraction, multiplication, and division) and advanced
calculations (exponents, sine, cosine, tangent). Switch-case control structure is used to
handle the selected operations, ensuring smooth user interaction. The calculator uses a while
loop to repeatedly perform operations until the user chooses to exit.

Program:
import java.util.Scanner;

public class sci {


public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Scientific Calculator");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Power");
System.out.println("6. Square Root");
System.out.println("7. Sine");
System.out.println("8. Cosine");
System.out.println("9. Tangent");
System.out.println("10. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
if (choice == 10) {
break;
}
double num1, num2, result = 0;
switch (choice) {
case 1:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
result = num1 + num2;
break;

Name: Hil Kalathiya Roll No: 23BIT092 26 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

case 2:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
result = num1 - num2;
break;
case 3:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
result = num1 * num2;
break;
case 4:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Cannot divide by zero.");
continue;
}
break;
case 5:
System.out.print("Enter base number: ");
num1 = scanner.nextDouble();
System.out.print("Enter exponent: ");
num2 = scanner.nextDouble();
result = Math.pow(num1, num2);
break;
case 6:
System.out.print("Enter number: ");
num1 = scanner.nextDouble();
result = Math.sqrt(num1);
break;
case 7:
System.out.print("Enter angle in radians: ");
num1 = scanner.nextDouble();
result = Math.sin(num1);
break;
case 8:
System.out.print("Enter angle in radians: ");
num1 = scanner.nextDouble();
result = Math.cos(num1);
break;

Name: Hil Kalathiya Roll No: 23BIT092 27 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

case 9:
System.out.print("Enter angle in radians: ");
num1 = scanner.nextDouble();
result = Math.tan(num1);
break;
default:
System.out.println("Invalid choice.");
continue;
}
System.out.println("Result: " + result);
}
scanner.close();
}
}

Output:

Name: Hil Kalathiya Roll No: 23BIT092 28 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Conclusions:
This code teaches how to implement a menu-driven program using a while loop and
switch-case statements for user input-based operations. It demonstrates the use of
the Math class for advanced calculations like power, square root, and trigonometric
functions. Additionally, it reinforces handling division by zero and interactive input
validation.

Name: Hil Kalathiya Roll No: 23BIT092 29 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 13: Write a program in Java to sort the


elements of list so that they are in ascending
order.
Introduction:
In Java, a List is an ordered collection from the java.util package that allows duplicate elements
and maintains insertion order. The most commonly used implementations are ArrayList
(dynamic array) and LinkedList (doubly-linked list). Lists support various operations like adding,
removing, sorting, and accessing elements using index-based access.

Program:
import java.util.ArrayList;
import java.util.Collections;

public class sort {


public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. :
23BIT092\n");
ArrayList<Integer> list = new ArrayList<>();
list.add(5);
list.add(3);
list.add(8);
list.add(1);
list.add(9);

System.out.println("Original list: " + list);

Collections.sort(list);

System.out.println("Sorted list: " + list);


}
}
Output:

Conclusions:
This code demonstrates how to store integers in an ArrayList and sort them in ascending
order

Name: Hil Kalathiya Roll No: 23BIT092 30 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 14: Write a program in Java to multiply two


matrixes.
Introduction:
This program performs matrix multiplication by multiplying two 2D arrays. It uses nested
loops to calculate the product by summing the element-wise multiplication of rows from
the first matrix with columns of the second. The result is stored in a new matrix,
demonstrating basic operations on multidimensional arrays in Java.
Program:
public class MatrixMultiplication {
public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int[][] matrix2 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};

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

System.out.println("Product of the matrices is: ");


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

public static int[][] multiplyMatrices(int[][] firstMatrix, int[][]


secondMatrix) {
int rows1 = firstMatrix.length;
int cols1 = firstMatrix[0].length;
int cols2 = secondMatrix[0].length;

int[][] product = new int[rows1][cols2];

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

Name: Hil Kalathiya Roll No: 23BIT092 31 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

for (int j = 0; j < cols2; j++) {


for (int k = 0; k < cols1; k++) {
product[i][j] += firstMatrix[i][k] *
secondMatrix[k][j];
}
}
}

return product;
}
}

Output:

Conclusions:
This code demonstrates how to perform matrix multiplication using nested loops to
compute the product of two 2D arrays. It illustrates the process of summing the products
of corresponding elements from the rows of the first matrix and the columns of the
second matrix.

Name: Hil Kalathiya Roll No: 23BIT092 32 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

2. Second module

Name: Hil Kalathiya Roll No: 23BIT092 33 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 3
(a) Write a Java program to create a class Distance which
consists of two coordinates as data members and a
constructor which initializes the values of coordinates and
a method which calculates the distance between two
coordinates.

Introduction:
The provided Java code calculates the Euclidean distance between two points in a 2D
plane. It uses a distance class to encapsulate the coordinates of the points and provides
a method calculateDistance that applies the distance formula: (sqrt{(x2 - x1)^2 + (y2 -
y1)^2}). The main method collects user input for the coordinates, creates an instance of
the distance class, and prints the calculated distance.
Program:
import java.util.Scanner;

public class distance {


private double x1, y1, x2, y2;

public distance(double x1, double y1, double x2, double y2) {


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

public double calculateDistance() {


return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1),
2));
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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


double x1 = scanner.nextDouble();

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


double y1 = scanner.nextDouble();

Name: Hil Kalathiya Roll No: 23BIT092 34 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

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


double x2 = scanner.nextDouble();

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


double y2 = scanner.nextDouble();

distance distance = new distance(x1, y1, x2, y2);


System.out.println("The distance between the coordinates is: " +
distance.calculateDistance());

scanner.close();
}
}

Output:

Conclusions:
This code demonstrates how to calculate the Euclidean distance between two points in a 2D
plane using mathematical operations. It teaches the use of constructors for initializing object
data and encapsulating logic within a class. Additionally, it shows how to take user input through
the Scanner class and perform calculations using Java’s Math library.

Name: Hil Kalathiya Roll No: 23BIT092 35 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

(b) Design a program with a TIME class that initializes


hours, minutes, and seconds using constructors, adds two
TIME objects, and displays the result in HH:MM:SS format.

Introduction:
This code demonstrates constructors for initializing objects with default or specific
values, as well as object-oriented programming (OOP) concepts like encapsulation. It
utilizes method overloading with the add() method to sum two TIME objects by handling
hours, minutes, and seconds properly. The display() method ensures formatted output
in HH:MM:SS format.
Program:
import java.util.Scanner;

class time {
private int hours;
private int minutes;
private int seconds;

public time() {
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
}

public time(int hours, int minutes, int seconds) {


this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}

public time add(time t) {


time result = new time();
result.seconds = this.seconds + t.seconds;
result.minutes = this.minutes + t.minutes + result.seconds / 60;
result.hours = this.hours + t.hours + result.minutes / 60;
result.seconds %= 60;
result.minutes %= 60;
return result;
}

public void display() {


System.out.printf("%02d:%02d:%02d\n", hours, minutes, seconds);
}

Name: Hil Kalathiya Roll No: 23BIT092 36 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter first time (hours, minutes, seconds):


");
int h1 = scanner.nextInt();
int m1 = scanner.nextInt();
int s1 = scanner.nextInt();
time t1 = new time(h1, m1, s1);

System.out.println("Enter second time (hours, minutes, seconds):


");
int h2 = scanner.nextInt();
int m2 = scanner.nextInt();
int s2 = scanner.nextInt();
time t2 = new time(h2, m2, s2);

time t3 = t1.add(t2);
System.out.print("The sum of the times is: ");
t3.display();

scanner.close();
}
}

Output:

Conclusions:
This code teaches how to use constructors for object initialization and implement the
addition of two objects by managing time values correctly. It also emphasizes formatted
output and basic OOP principles like encapsulation and method functionality.

Name: Hil Kalathiya Roll No: 23BIT092 37 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 4
(a) Write a java program to create an abstract class named
Shape that contains two integers and an empty method
named printArea(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the
classes extends the class Shape. Each one of the classes
contain only the method printArea( ) that prints the area of
the given shape.

Introduction:
In this program, an abstract class Shape is defined with two integer variables and an
empty method printArea(). The classes Rectangle, Triangle, and Circle extend the Shape
class and each implement the printArea() method to calculate and display the area of
the respective shape. This demonstrates the use of inheritance and abstraction in Java,
allowing each shape to have its own area calculation.
Program:
abstract class Shape {
int dimension1;
int dimension2;

abstract void printArea();


}

class Rectangle extends Shape {


Rectangle(int length, int breadth) {
this.dimension1 = length;
this.dimension2 = breadth;
}

@Override
void printArea() {
int area = dimension1 * dimension2;
System.out.println("Rectangle Area: " + area);
}
}

class Triangle extends Shape {


Triangle(int base, int height) {

Name: Hil Kalathiya Roll No: 23BIT092 38 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

this.dimension1 = base;
this.dimension2 = height;
}
@Override
void printArea() {
double area = 0.5 * dimension1 * dimension2;
System.out.println("Triangle Area: " + area);
}
}
class Circle extends Shape {
Circle(int radius) {
this.dimension1 = radius;
this.dimension2 = 0; // Not used for Circle
}
@Override
void printArea() {
double area = Math.PI * dimension1 * dimension1;
System.out.println("Circle Area: " + area);
}
}
public class Print {
public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Shape rectangle = new Rectangle(10, 5);
rectangle.printArea();

Shape triangle = new Triangle(10, 5);


triangle.printArea();

Shape circle = new Circle(7);


circle.printArea();
}
}
Output:

Conclusions:
this program showcases the power of abstraction and inheritance in object-oriented
programming. By defining a common interface in the Shape class, different shapes can
implement their own specific functionality for calculating the area. This approach
promotes code reusability and flexibility, allowing easy extension for additional shapes.

Name: Hil Kalathiya Roll No: 23BIT092 39 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

(b) Write a Java program to create an abstract class Vehicle


with abstract methods startEngine() and stopEngine().
Create subclasses Car and Motorcycle that extend the
Vehicle class and implement the respective methods to
start and stop the engines for each vehicle type. Also add
the function which defines the special characteristics
(Company name, Model number, Number of wheels) of Car
and Motorcycle in their respective class.

Introduction:
This program demonstrates the use of abstraction in Java by defining an abstract class
Vehicle with abstract methods startEngine() and stopEngine(). The subclasses Car and
Motorcycle extend the Vehicle class and provide their own implementations of these
methods. Additionally, each subclass includes a method to define specific
characteristics like company name, model number, and number of wheels, showcasing
inheritance and polymorphism.

Program:
abstract class Vehicle {
abstract void startEngine();
abstract void stopEngine();
abstract void specialCharacteristics();
}
class Car extends Vehicle {
private String companyName;
private String modelNumber;
private int numberOfWheels;
public Car(String companyName, String modelNumber, int
numberOfWheels) {
this.companyName = companyName;
this.modelNumber = modelNumber;
this.numberOfWheels = numberOfWheels;
}
@Override
void startEngine() {
System.out.println("Car engine started.");
}
@Override
void stopEngine() {
System.out.println("Car engine stopped.");
}

Name: Hil Kalathiya Roll No: 23BIT092 40 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

@Override
void specialCharacteristics() {
System.out.println("Car Details:");
System.out.println("Company Name: " + companyName);
System.out.println("Model Number: " + modelNumber);
System.out.println("Number of Wheels: " + numberOfWheels);
}
}
class Motorcycle extends Vehicle {
private String companyName;
private String modelNumber;
private int numberOfWheels;

public Motorcycle(String companyName, String modelNumber, int


numberOfWheels) {
this.companyName = companyName;
this.modelNumber = modelNumber;
this.numberOfWheels = numberOfWheels;
}
@Override
void startEngine() {
System.out.println("Motorcycle engine started.");
}
@Override
void stopEngine() {
System.out.println("Motorcycle engine stopped.");
}
@Override
void specialCharacteristics() {
System.out.println("Motorcycle Details:");
System.out.println("Company Name: " + companyName);
System.out.println("Model Number: " + modelNumber);
System.out.println("Number of Wheels: " + numberOfWheels);
}
}
public class Print2 {
public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Car car = new Car("Toyota", "Camry", 4);
Motorcycle motorcycle = new Motorcycle("Yamaha", "YZF-R3", 2);
car.startEngine();
car.specialCharacteristics();
car.stopEngine();
motorcycle.startEngine();
motorcycle.specialCharacteristics();
motorcycle.stopEngine();
}
}

Name: Hil Kalathiya Roll No: 23BIT092 41 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Output:

Conclusions:
this program highlights the use of abstraction and inheritance in Java to model different
vehicle types. By defining common behaviors in the abstract Vehicle class and allowing
subclasses to implement specific details, it promotes code reusability and flexibility. The
approach allows easy extension for new vehicle types with their own unique
characteristics and functionalities.

Name: Hil Kalathiya Roll No: 23BIT092 42 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 5: Design a Java program with an Employee


base class (name, address, salary, job title) and
two subclasses: Manager and Developer.
Implement salary increments: 10% for Managers
and 8% for Developers.

Introduction:
This code demonstrates inheritance and polymorphism by creating a class hierarchy
with a base employee class and two subclasses, Manager and Developer. Each subclass
overrides the incrementSalary() method to apply different salary increments based on
job roles. The program follows object-oriented principles such as encapsulation (using
private fields) and method overriding.
Program:
class employee {
private String name;
private String address;
private double basicSalary;
private String jobTitle;

public employee(String name, String address, double basicSalary,


String jobTitle) {
this.name = name;
this.address = address;
this.basicSalary = basicSalary;
this.jobTitle = jobTitle;
}

public String getName() {


return name;
}
public String getAddress() {
return address;
}
public double getBasicSalary() {
return basicSalary;
}
public String getJobTitle() {
return jobTitle;
}
public void setBasicSalary(double basicSalary) {

Name: Hil Kalathiya Roll No: 23BIT092 43 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

if (basicSalary < 0) {
throw new IllegalArgumentException("Salary cannot be
negative");
}
this.basicSalary = basicSalary;
}
public void incrementSalary() {
}

@Override
public String toString() {
return "employee{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", basicSalary=" + basicSalary +
", jobTitle='" + jobTitle + '\'' +
'}';
}
}

class Manager extends employee {


private static final double INCREMENT_PERCENTAGE = 0.10;

public Manager(String name, String address, double basicSalary) {


super(name, address, basicSalary, "Manager");
}

@Override
public void incrementSalary() {
double newSalary = getBasicSalary() * (1 + INCREMENT_PERCENTAGE);
setBasicSalary(newSalary);
}
}

class Developer extends employee {


private static final double INCREMENT_PERCENTAGE = 0.08;

public Developer(String name, String address, double basicSalary) {


super(name, address, basicSalary, "Developer");
}

@Override
public void incrementSalary() {
double newSalary = getBasicSalary() * (1 + INCREMENT_PERCENTAGE);
setBasicSalary(newSalary);
}
}

Name: Hil Kalathiya Roll No: 23BIT092 44 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

public class EmployeeTest {


public static void main(String[] args) {
employee manager = new Manager("Alice", "123 Main St", 75000);
employee developer = new Developer("Bob", "456 Elm St", 60000);

System.out.println("Before Increment:");
System.out.println(manager);
System.out.println(developer);

manager.incrementSalary();
developer.incrementSalary();

System.out.println("\nAfter Increment:");
System.out.println(manager);
System.out.println(developer);
}
}

Output:

Conclusions:
This code teaches how to use inheritance to extend a base class and apply
polymorphism by overriding methods for specific behaviors. It also emphasizes
encapsulation through private fields and safe salary modification using validation logic.

Name: Hil Kalathiya Roll No: 23BIT092 45 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 6: An interface Polygon containing the


members as given below:
void calcArea( ); abstract method to calculate area of
a particular polygon given its dimensions
void calcPeri( ); abstract method to calculate
perimeter of a particular polygon given its
dimensions
void display( ); method to display the area and
perimeter of the given polygon.
Create a class Square that implements Polygon and
has the following member:
float side
Square(float s); constructor to initialize side of
square
Create another class Rectangle that implements
Polygon and has the following member:
float length
float breadth
Rectangle(int len, int bre); constructor to initialize
length and breadth of a rectangle
Outside the package, create a class that imports the
above package an instantiates an object of
the Square class and an object of the Rectangle
class. Call the above methods on each of the
classes to calculate the area and perimeter given the
side and the length/breadth of the Square
class and the Rectangle class respectively.

Name: Hil Kalathiya Roll No: 23BIT092 46 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Introduction:
This program defines a Polygon interface with methods to calculate and display the area
and perimeter of polygons. The Square and Rectangle classes implement this interface
to calculate these values based on their dimensions. Finally, a separate test class
instantiates these shapes to demonstrate their functionality.

Program:
Polygon –
package gon;
public interface polygon{
public void area();
public void perimeter();
public void display();
}

Square Class –
package gon;

public class square implements polygon {

float s, area, perimeter;

public square(float s) {
this.s = s;
}

public void area() {


area = s * s;
}

public void perimeter() {


perimeter = 4 * s;
}

public void display() {


System.out.println("Area of square is: " + area);
System.out.println("Perimeter of square is: " + perimeter);
}
}

Name: Hil Kalathiya Roll No: 23BIT092 47 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Rectangle Class –
package gon;

public class rectangle implements polygon{


int a, b, area, perimeter;
public rectangle(int a, int b){
this.a = a;
this.b = b;
}
public void area(){
area = a * b;
}
public void perimeter(){
perimeter = 2 * (a + b);
}
public void display(){
System.out.println("Area of rectangle is: " + area);
System.out.println("Perimeter of rectangle is: " + perimeter);
}
}

Main Class-

import gon.*;

public class Main {


public static void main(String[] arg){
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
rectangle R = new rectangle(4,5);
R.area();
R.perimeter();
R.display();
square S = new square(4.3f);
S.area();
S.perimeter();
S.display();
}
}

Name: Hil Kalathiya Roll No: 23BIT092 48 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Output:

Conclusions:
The code demonstrates the power of interfaces in Java, allowing multiple classes to
implement a common structure while defining their specific behaviors. By using
polymorphism, Square and Rectangle calculate and display their area and perimeter
uniquely. This approach enhances code reusability, flexibility, and maintainability.

Name: Hil Kalathiya Roll No: 23BIT092 49 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 7: Write a Java program to create an interface


Playable with a method play() that takes no
arguments and returns void. Create three classes
Football, Volleyball, and Basketball that
implement the Playable interface and override
theplay() method to play the respective sports.

Introduction:
This program defines a Playable interface with a play() method that classes can
implement to represent different sports. The Football, Volleyball, and Basketball classes
each implement Playable and override play() to define the action of playing their specific
sport. This showcases polymorphism, allowing each class to provide its unique behavior
for the same interface method.

Program:
package Play;
interface Playable {
void play();
}

class Football implements Playable {


@Override
public void play() {
System.out.println("Playing Football");
}
}

class Volleyball implements Playable {


@Override
public void play() {
System.out.println("Playing Volleyball");
}
}

class Basketball implements Playable {


@Override
public void play() {
System.out.println("Playing Basketball");
}
}

Name: Hil Kalathiya Roll No: 23BIT092 50 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

public class Play {


public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Playable football = new Football();
Playable volleyball = new Volleyball();
Playable basketball = new Basketball();

football.play();
volleyball.play();
basketball.play();
}
}

Output:

Conclusions:
This code illustrates how interfaces enable polymorphism in Java by allowing different
classes to implement a shared method with unique behaviors. Each sport class
customizes the play() method, demonstrating flexibility in defining actions for various
objects. This approach promotes modularity and makes it easy to expand the program
by adding more sports.

Name: Hil Kalathiya Roll No: 23BIT092 51 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Lab 8: Write a Java Program which asks user to


enter a paragraph and perform the following
operations:
a. Find total no of sentences in the paragraph and the
total number of words in each sentence.
b. Find the total number of characters in the entire
paragraph and find out the occurrence of
each character in the paragraph and display the
information in proper format.
c. Search a word (entered by the user) in the
paragraph and print the position of the word (if
found) or print appropriate message.

Introduction:
This Java program takes a paragraph as input and analyzes its structure. It counts the
sentences and words per sentence, tallies character occurrences, and allows the user
to search for a specific word, displaying its position if found. This demonstrates text
parsing, data organization, and string manipulation in Java.

Program:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Para {


public static void main(String[] args) {
System.out.println("Name: Hil Kalathiya Roll No. : 23BIT092\n");
Scanner scanner = new Scanner(System.in);

System.out.println("Enter a paragraph:");
String paragraph = scanner.nextLine();

String[] sentences = paragraph.split("[.!?]");


System.out.println("Total number of sentences: " +
sentences.length);
for (int i = 0; i < sentences.length; i++) {
String[] words = sentences[i].trim().split("\\s+");

Name: Hil Kalathiya Roll No: 23BIT092 52 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

System.out.println("Sentence " + (i + 1) + " has " +


words.length + " words.");
}

int totalCharacters = paragraph.length();


System.out.println("Total number of characters: " +
totalCharacters);

Map<Character, Integer> charCountMap = new HashMap<>();


for (char c : paragraph.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
}

System.out.println("Character occurrences:");
for (Map.Entry<Character, Integer> entry :
charCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

System.out.println("Enter a word to search:");


String searchWord = scanner.nextLine();
String[] words = paragraph.split("\\s+");
boolean found = false;
for (int i = 0; i < words.length; i++) {
if (words[i].equalsIgnoreCase(searchWord)) {
System.out.println("Word found at position: " + (i + 1));
found = true;
break;
}
}
if (!found) {
System.out.println("Word not found in the paragraph.");
}

scanner.close();
}
}

Name: Hil Kalathiya Roll No: 23BIT092 53 |P a g e


Name : HIL KALATHIYA B.TECH (ICT)
Roll No: 23BIT092

Output:

Conclusions:
This program highlights the use of Java for text processing by counting sentences, words,
and character occurrences in a paragraph. It also demonstrates search functionality,
allowing users to locate specific words. Overall, it showcases efficient string
manipulation, data analysis, and search capabilities in Java.

Name: Hil Kalathiya Roll No: 23BIT092 54 |P a g e

You might also like