2 - 23BIT092 - Hil Kalathiya
2 - 23BIT092 - Hil Kalathiya
TECH (ICT)
Roll No: 23BIT092
PRACTICALS
B.Tech. (Information and
Communication Technology)
Semester 2
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
Exp
. Title of Lab Work(Module-2) Page Signature
No.
(LAB-3)
9
10
11
12
13
14
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().
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.
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.
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.
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:
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.
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.
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.
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.
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();
}
}
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.
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();
}
}
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.
Program:
import java.util.Scanner;
class vowel {
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();
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.
Program:
import java.util.Scanner;
Output:
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.
Program:
import java.util.Scanner;
printDiamond(n);
}
public static void printDiamond(int n) {
int space = n - 1;
}
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.
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);
}
}
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.
Program:
import java.util.Scanner;
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;
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:
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.
Program:
import java.util.ArrayList;
import java.util.Collections;
Collections.sort(list);
Conclusions:
This code demonstrates how to store integers in an ArrayList and sort them in ascending
order
int[][] matrix2 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
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.
2. Second module
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;
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.
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;
}
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.
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;
@Override
void printArea() {
int area = dimension1 * dimension2;
System.out.println("Rectangle Area: " + area);
}
}
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();
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.
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.");
}
@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;
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.
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;
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 + '\'' +
'}';
}
}
@Override
public void incrementSalary() {
double newSalary = getBasicSalary() * (1 + INCREMENT_PERCENTAGE);
setBasicSalary(newSalary);
}
}
@Override
public void incrementSalary() {
double newSalary = getBasicSalary() * (1 + INCREMENT_PERCENTAGE);
setBasicSalary(newSalary);
}
}
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.
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 square(float s) {
this.s = s;
}
Rectangle Class –
package gon;
Main Class-
import gon.*;
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.
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();
}
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.
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;
System.out.println("Enter a paragraph:");
String paragraph = scanner.nextLine();
System.out.println("Character occurrences:");
for (Map.Entry<Character, Integer> entry :
charCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
scanner.close();
}
}
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.