0% found this document useful (0 votes)
47 views72 pages

JAVA Practicals Final

This document contains details of 4 Java programs assigned as practical exercises for students. The programs cover printing strings, adding numbers from command line arguments, converting currency values, and calculating area of a circle and student percentages using input from the Scanner class. The document also includes questions for students on object-oriented programming concepts and features of Java language.

Uploaded by

Almash Lakdawala
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)
47 views72 pages

JAVA Practicals Final

This document contains details of 4 Java programs assigned as practical exercises for students. The programs cover printing strings, adding numbers from command line arguments, converting currency values, and calculating area of a circle and student percentages using input from the Scanner class. The document also includes questions for students on object-oriented programming concepts and features of Java language.

Uploaded by

Almash Lakdawala
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/ 72

Object-Oriented Programming with Java (C2310C1)

SoCSET BTech Semester Ⅲ AI&DA/IT

SET 1 – Language Fundamentals

Practical 1
Aim: Write a Java program to print the string literal “Hello World!!!”

Program Code:

public class Practical1

public static void main(String[] args)

System.out.println("Hello world");

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 1
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 2
Aim : Write a Java program to print the poem

“Mary had a little lamb


Its fleece was white as snow
Everywhere that Mary went
The Lamb was sure to go”
Program Code:

public class Practical2

public static void main(String[] args)

System.out.println("Mary had a little lamb\n"+

"Its fleece was white as snow\n"+

"Everywhere that Mary went\n"+

"The Lamb was sure to go\n"+

"");

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 2
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 3
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 3
Aim: Write a Java program to add two numbers using Command Line Argument
Program Code:

public class Practical3

public static void main(String[] args) {

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

int num2 = Integer.parseInt(args[1]);

int total = num1 + num2;

System.out.println("Sum of " + num1 + " and " + num2 + " is " + total);

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 4
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 4
Aim: Write a Java program to convert rupees into dollars using
(i) Command Line Argument
(ii) Scanner Class
Program Code:

Program1: Command Line Argument

public class Practical4

public static void main(String[] args)

Double rupees = Double.parseDouble(args[0]);

Double conversionRate = 0.014; // 1 Rupee = 0.014 Dollar

Double dollars = rupees * conversionRate;

System.out.println( rupees + "Rupees is Equals to " + dollars + "Dollars");

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 5
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Program2: Scanner Class

import java.util.Scanner;
public class Practical4_2
{
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
System.out.println("Enter the rupees:");
int r = obj.nextInt();
float d = (float) r / 60;
System.out.println(r + "Rupees = " + d + "Dollar");
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 6
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Questions to be answered by students :

Q1. Compare Object oriented programming with sequential programming.

Ans-

Sequential Programming Object-Oriented Programming

In object-oriented programming, the


In procedural programming, the program is
program is divided into small parts
divided into small parts called functions.
called objects.

Procedural programming follows a top- Object-oriented programming follows


down approach. a bottom-up approach.

Object-oriented programming has access


There is no access specifier in procedural
specifiers like private, public, protected,
programming.
etc

Procedural programming does not have


Object-oriented programming provides
any proper way of hiding data so it is less
data hiding so it is more secure.
secure.

Examples: C, FORTRAN, Pascal, Basic,


Examples: C++, Java, Python, C#, etc.
etc.

Q2. List the features of Java. Explain them in brief

Ans-

-Multithreaded

With Java’s multithreaded feature it is possible to write programs that can perform many
tasks simultaneously. This design feature allows the developers to construct interactive
applications that can run smoothly.

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 7
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
-Interpreted

Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.

-High Performance

With the use of Just-In-Time compilers, Java enables high performance.

-Distributed

Java is designed for the distributed environment of the internet.

-Dynamic

Java is considered to be more dynamic than C or C++ since it is designed to adapt to an


evolving environment. Java programs can carry an extensive amount of run-time information
that can be used to verify and resolve accesses to objects at run-time.

Q3. Explain the method parseXXX() with examples.

Ans- We can use parseXxx() methods to convert String to primitive. There are two types of
parseXxx() methods:

A. primitive parseXxx(String s): Every Wrapper class except the character class contains the
following parseXxx() method to find primitive for the given String object.

Syntax: public static primitive parseXxx(String s);

B. parseXxx(String s, int radix): Every Integral type Wrapper class (Byte, Short, Integer,
Long) contains the following parseXxx() method to convert specified radix String to
primitive.

Syntax:

public static primitive parseXxx(String s, int radix);

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 8
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Q4. Explain the Command Line Argument in Java.

Ans- The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be
used as an input.

So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 9
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

SET 2 – Datatypes and Operators

Practical 1:
Aim: Write a Java program to compute the area of a circle using Scanner class

The methods for Scanner class are as follows:

Method Description

nextByte() Reads an integer of the byte type

nextShort() Reads an integer of the short type

nextInt Reads an integer of the int type

nextLong() Reads an integer of the long type

nextFloat() Reads an integer of the float type

nextDouble() Reads an integer of the double type

next() Reads a string that ends before a whitespace character

nextLine() Reads a line of text (that is a string ending with the Enter
key pressed)

Program Code:

import java.util.Scanner;

class Practical1

public static void main(String args[])

Scanner sc= new Scanner(System.in);

System.out.println("Enter the radius:");

double r= sc.nextDouble();

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 10
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
double area=(3.14*r*r)/7 ;

System.out.println("Area of Circle is: " + area);

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 11
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 2:
Aim: Write a Java program that calculates the percentage marks of the student if marks of 6
subjects are given.
Program Code:

class Practical2

public static void main(String[] args)

int N = 6, total_marks = 0;

float percentage;

int marks[] = { 89, 75, 82, 60, 95,99 };

for (int i = 0; i < N; i++)

total_marks += marks[i];

percentage = (total_marks / (float)N);

System.out.println( "Total Percentage : " + percentage + "%");

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 12
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 13
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 3:
Aim: Write a program to enter two numbers and perform mathematical operations on them.
Program Code:

import java.util.Scanner;

public class Practical3

public static void main(String args[])

int num1, num2, result;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Two Numbers : ");

num1 = scan.nextInt();

num2 = scan.nextInt();

result = num1 + num2;

System.out.println("Addition = " +result);

result = num1 - num2;

System.out.println("Subtraction = " +result);

result = num1 * num2;

System.out.println("Multiplication = " +result);

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 14
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

result = num1 / num2;

System.out.println("Division = " +result);

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 15
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 4:
Aim: Write a Java program that converts a Fahrenheit degree to Celsius using the formula:
Celsius = (5/9) (Fahrenheit - 32)
Program Code:

import java.util.Scanner;

public class Practical4

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

System.out.println("Enter temperature in Fahrenheit: ");

double fahrenheit = scan.nextDouble();

double celcius = (5.0 / 9.0) * (fahrenheit-32);

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 16
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
System.out.println("Temperature in Celsius: "+ celcius);

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 17
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 5:
Aim: Write a program that computes loan payments. The loan can be a car loan, a student
loan, or a home mortgage loan. Allow the user to enter the interest, rate, number of years and
loan amount, and display the monthly payment as follows:

Program Code:

import java.util.Scanner;

import java.lang.Math;

public class Practical5

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

System.out.print("Enter loan type (car/student/home): ");

String loanType = scanner.nextLine();

System.out.print("Enter loan amount: ");

double loanAmount = scanner.nextDouble();

System.out.print("Enter annual interest rate (%): ");

double annualInterestRate = scanner.nextDouble();

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 18
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

System.out.print("Enter number of years: ");

int numYears = scanner.nextInt();

double monthlyInterestRate = (annualInterestRate / 100) / 12;

int numMonths = numYears * 12;

double monthlyPayment = (loanAmount * monthlyInterestRate) / (1 - Math.pow(1 +


monthlyInterestRate,-numMonths));

System.out.println("\nLoan Amount: $" + loanAmount);

System.out.println("Annual Interest Rate: " + annualInterestRate + "%");

System.out.println("Number of Years: " + numYears);

System.out.println("Monthly Payment: $" + Math.round(monthlyPayment * 100) /


100.0);

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 19
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Questions to be answered by students :

Q. 1) Explain short circuited operator with example.


Ans : short-circuit operators are logical operators that evaluate only as much of an expression
as necessary to determine the final result. The two short-circuit operators are “&&” (logical
AND) and “||” (logical OR).
For example:
Int x = 5;
Int y = 10;
If (x > 0 && y / x > 1) {

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 20
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
System.out.println(“Both conditions are true.”);
} else {
System.out.println(“At least one condition is false.”);
}
In this case, the “&&” operator short-circuits the evaluation. Since the first condition “x > 0”
is false, the second condition “y / x > 1” is not even evaluated, because regardless of its
outcome, the entire expression will be false. Therefore, the output will be “At least one
condition is false.”
Similarly, the “||” operator short-circuits as well. If the first condition in an “||” expression is
true, the second condition is not evaluated, as the overall result will be true regardless.

Q.2) What are the four integer types supported by Java? Explain with some examples
Ans :.Java supports four integer types, which differ in size and range:
Byte : It’s the smallest integer type and occupies 8 bits.
Its range is from -128 to 127.
Ex : byte myByte = 100;
Short : It’s larger than a byte and occupies 16 bits.
Its range is from -32,768 to 32,767
Ex :Short myShort = 2000;
Int :This is the most commonly used integer type and occupies 32 bits.
Its range is from -2^31 to 2^31 – 1.
Ex : Int myInt = 50000;
Long :It’s the largest integer type and occupies 64 bits.
Its range is from -2^63 to 2^63 – 1.
Ex : Long myLong = 10000000000L; // Note the ‘L’ suffix to indicate a long literal

Q.3) What will be the result of the following Java expression?


4 * 2 – 5 > 4 && 3 < 5 – 3
Ans : The result is “False”.
The expression is explained step by step in the following:
4 * 2 – 5: Multiply 4 by 2, which is 8, and then subtract 5, resulting in 3.
5 – 3: Subtract 3 from 5, resulting in 2.
So, the expression becomes:
3 > 4 && 3 < 2
Now, evaluating the logical operators:
3 > 4: This is false.
3 < 2: This is false.
Finally, the expression becomes:
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 21
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
False && false
When using the logical AND operator (“&&”), both sides of the operator need to be true for
the whole expression to evaluate to true. Since both sides are false in this case, the result of
entire expression is “False”.

Q. 4). What are binary literals? Can we use an underscore with numeric literals?

Ans : Binary literals allows us to represent integer values in binary (base-2) notation. They
are introduced with the prefix “Ob” or “OB” followed by a sequence of binary digits (0 and
1). Binary literals are useful for better readability when dealing with binary data or specific
binary patterns.

Example : Int binaryValue = 0b101010; Yes, we can use underscores in numeric literals
(including binary literals) in Java starting from Java 7.

Underscores can be placed between digits to enhance the readability of large numbers. They
do not affect the value of the number, only how it’s presented in the code.

Examples : Long bigNumber = 1_000_000_000L; Int binaryValue = 0b1010_1010

SET 3 – Arrays

Practical 1

Aim: To count the occurrences of integers between 1 and 100.

Program Code:

class Practical1
{
public void Count( )
{
int arr[] = {1, 2, 2, 2, 2, 3, 4, 7 ,8 ,8 };
int n = arr.length;

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 22
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
int x = 2;
int res = 0;

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


{
if (x == arr[i])
res++;
}

System.out.println(x+" occours "+res+ "times");


}
public static void main(String[] args)
{
Practical1 obj = new Practical1();

obj.Count();

}
}

Output:

Practical2
Aim: To read an unspecified number of scores and determine how many scores are above or
equal to the average and how many scores are below the average.

Program Code:

import java.util.Scanner;

public class Practical2


{
public void test()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Scores:(negative number signifies end):");
int scores[] = new int[10];
int numberofScores = 0;
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 23
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
int average = 0;

for (int i = 0; i < 10; i++)


{
scores[i] = input.nextInt();
if (scores[i] < 0)

break;
average = average + scores[i];
numberofScores++;
}
average = average / numberofScores;

int AboveOREqual = 0, below = 0;

for (int i = 0; i < numberofScores; i++)


{
if (scores[i] >= average)
{
AboveOREqual++;
}
else
{
below++;
}

}
System.out.println("Average of scores:" + average);
System.out.println("Number of scores above or equal to average:" + AboveOREqual);
System.out.println("Number of scores below average:" + below);
}

public static void main(String[] args)


{
Practical2 obj = new Practical2();
obj.test();
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 24
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 3

Aim: To eliminate the duplicate values in the array of numbers.

Program code:

public class Practical3


{
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 25
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
public static int removeDuplicateElements(int arr[], int n)
{
if (n==0 || n==1)
{
return n;
}

int[] temp = new int[n];


int j = 0;

for (int i=0; i<n-1; i++)


{
if (arr[i] != arr[i+1])
{
temp[j++] = arr[i];
}
}

temp[j++] = arr[n-1];

for (int i=0; i<j; i++)


{
arr[i] = temp[i];
}

return j;
}

public static void main (String[] args)


{
int arr[] = {10,20,20,30,30,40,50,50};

int length = arr.length;

length = removeDuplicateElements(arr, length);

for (int i=0; i<length; i++)


{
System.out.print(arr[i]+" ");
}
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 26
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 4

Aim: To compute the weekly hours for each employee.

Program Code:

import java.util.Scanner;
public class Practical4
{

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 27
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
public static int[][] readHours()
{
Scanner scan = new Scanner (System.in);
int[][] employees = new int[8][7];
for (int i =0;i<employees.length;i++)
{
for (int j =0;j<employees[i].length;j++)
{
employees[i][j] = scan.nextInt();
}
}
return employees;
}
public static int[][] sortEmployees(int[][] employees)
{
int[][] tempar = new int[8][2];
for (int i =0;i<employees.length;i++)
{
tempar[i][0] =i;
for (int j=0;j<employees[i].length;j++)
{
tempar[i][1] += employees[i][j];
}
}
for (int i =0;i<employees.length;i++)
{
for (int j =0;j<employees.length -1;j++)
{
if ( tempar[j][1] < tempar[j+1][1] )
{
int temp = tempar[j][1];
int temp2 = tempar[j][0];

tempar[j][1] = tempar[j+1][1];
tempar[j][0] = tempar[j+1][0];
tempar[j+1][1] = temp;
tempar[j+1][0] = temp2;
}
}
}
return tempar;
}

public static void printEmployees(int[][] tempar)


{
for (int i =0;i<tempar.length;i++)
{
System.out.println("Employee's " + tempar[i][0] +
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 28
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
" worked the most with " + tempar[i][1] + " hours" );
}
}

public static void main (String[] args)


{
int[][] nums = readHours();
int[][] nums1 = sortEmployees(nums);
printEmployees(nums1);
}
}

Output:

Practical 5

Aim: To locate the largest element in a two-dimensional array

Program Code:

public class Practical5


{
public static int findLargestElement(int[][] array)
{
int max = Integer.MIN_VALUE;

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 29
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if (array[i][j] > max)
{
max = array[i][j];
}
}
}

return max;
}

public static void main(String[] args)


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

int maxElement = findLargestElement(array);

System.out.println("The largest element in the 2D array is: " + maxElement);


}
}

Output:

Questions to be answered by students :

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 30
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
Q1. Can you pass the negative number as an array size?

Ans : As per the convention of array declaration, it is mandatory that each time an array is
evaluated it shall have a size greater than 0. Declaring array size negative breaks this “shall”
condition. That’s why this action gives an error.

Q2. What are jagged arrays in Java?

Ans : In Java, a jagged array is an array of arrays where each sub-array can have a different
length. Unlike a multi-dimensional array, where all sub-arrays have the same length, jagged
arrays allow for more flexibility in creating arrays with varying dimensions. Each sub-array
in a jagged array is an independent array object, and they can be of different lengths. This can
be useful when dealing with irregular data structures or when memory allocation needs vary
across different parts of your program.

Q3.What are the different ways of copying an array into another array?

Ans:

- You can copy one array from another in several ways − Copying element by
element − One way is to create an empty array with the length of the original array,
and copy each element (in a loop).
- Using the clone() method − The clone() method of the class java.lang.Object accepts
an object as a parameter, creates and returns a copy of it.
- Using the System.arraycopy() method − The copy() method of the System class
accepts two arrays (along with other details) and copies the contents of one array to
other.

(4) Differentiate between Array and ArrayList.

Ans:

Basis Array ArrayList


Definition An array is a dynamically-created The ArrayList is a class of Java
object. It serves as a container that holds Collections framework. It contains
the constant number of values of the same popular classes like Vector,
type. It has a contiguous memory location. HashTable, and HashMap.

Static/ Array is static in size. ArrayList is dynamic in size.


Dynamic

Resizable An array is a fixed-length data ArrayList is a variable-length

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 31
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
structure. data structure. It can be resized
itself when needed.

Initialization It is mandatory to provide the size of We can create an instance of


an array while initializing it directly or ArrayList without specifying its
indirectly. size. Java creates ArrayList of
default size.

Performance It performs fast in comparison to ArrayList is internally backed


ArrayList because of fixed size. by the array in Java. The resize
operation in ArrayList slows down
the performance.

Primitive/ An array can store both objects and We cannot store primitive type
Generic type primitives type. in ArrayList. It automatically
converts primitive type to object.

Iterating We use for loop or for each loop to We use an iterator to iterate
Values iterate over an array. over ArrayList.

SET 4 – Classes and Objects

Practical 1

Aim - (The Account class) Design a class named Account that contains:
■ A private int data field named id for the account (default 0).

■ A private double data field named balance for the account (default 0).

■ A private double data field named annualInterestRate that stores the current

interest rate (default 0). Assume all accounts have the same interest rate.

■ A private Date data field named dateCreated that stores the date when the account was created.

■ A no-arg constructor that creates a default account.


Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 32
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
■ A constructor that creates an account with the specified id and initial balance.

■ The accessor and mutator methods for id, balance, and annualInterestRate.

■ The accessor method for dateCreated.

■ A method named getMonthlyInterestRate() that returns the monthly

interest rate.

■ A method named withdraw that withdraws a specified amount from the account.

■ A method named deposit that deposits a specified amount to the account.

Draw the UML diagram for the class. Implement the class. Write a test program that creates an Account object
with an account ID of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method
to withdraw $2,500, use the deposit method to deposit $3,000, and print the balance, the monthly interest, and
the date when this account was created.

Program Code:

import java.util.Date;

public class Account {


private int id;
private double balance;
private double annualInterestRate;
private Date dateCreated;

public Account() {
id = 0;
balance = 0;
annualInterestRate = 0;
dateCreated = new Date();
}

public Account(int id, double balance) {


this.id = id;

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 33
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
this.balance = balance;
annualInterestRate = 0;
dateCreated = new Date();
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public double getBalance() {


return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}

public double getAnnualInterestRate() {


return annualInterestRate;
}

public void setAnnualInterestRate(double annualInterestRate) {


this.annualInterestRate = annualInterestRate;
}

public Date getDateCreated() {


return dateCreated;
}

public double getMonthlyInterestRate() {


return annualInterestRate / 12;
}

public void withdraw(double amount) {


if (amount > balance) {
System.out.println("Insufficient funds.");
} else {
balance -= amount;
}
}

public void deposit(double amount) {


if (amount < 0) {
System.out.println("Invalid deposit amount.");
} else {
balance += amount;
}
}

public static void main(String[] args) {


Account account = new Account(1122, 20000);
account.setAnnualInterestRate(4.5);

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 34
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
account.withdraw(2500);
account.deposit(3000);

System.out.println("Balance: $" + account.getBalance());


System.out.println("Monthly Interest: $" + (account.getMonthlyInterestRate() * account.getBalance() /
100));
System.out.println("Date Created: " + account.getDateCreated());
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 35
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 2

1. Aim: (The Fan class) Design a class named Fan to represent a fan. The class contains:
■ Three constants named SLOW, MEDIUM, and FAST with values 1, 2, and 3 to denote the
fan speed.
■ A private int data field named speed that specifies the speed of the fan
(default SLOW).
■ A private boolean data field named on that specifies whether the fan is on (default false).
■ A private double data field named radius that specifies the radius of the fan (default 5).
■ A string data field named color that specifies the color of the fan (default blue).
■ The accessor and mutator methods for all four data fields.
■ A no-arg constructor that creates a default fan.
■ A method named toString() that returns a string description for the fan. If the fan is on, the
method returns the fan speed, color, and radius in one combined string. If the fan is not on,
the method returns fan color and radius along with the string “fan is off” in one combined
string.

Draw the UML diagram for the class. Implement the class. Write a test program that creates
two Fan objects. Assign maximum speed, radius 10, color yellow, and turn it on to the first
object. Assign medium speed, radius 5, color blue, and turn it off to the second object.
Display the objects by invoking their toString method.

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 36
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
Program Code:

public class Fan {


private final int SLOW = 1;
private final int MEDIUM = 2;
private final int FAST = 3;

private int speed;


private boolean on;
private double radius;
private String color;

public Fan() {
speed = SLOW;
on = false;
radius = 5.0;
color = "blue";
}

public String toString() {


if (on) {
return "Speed: " + speed + ", Color: " + color + ", Radius: " + radius;
} else {
return "Color: " + color + ", Radius: " + radius + ", Fan is off";
}
}

public int getSpeed() {


return speed;
}

public void setSpeed(int speed) {


this.speed = speed;
}

public boolean isOn() {


return on;
}

public void setOn(boolean on) {


this.on = on;
}

public double getRadius() {


return radius;
}

public void setRadius(double radius) {


this.radius = radius;
}

public String getColor() {


return color;
}

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 37
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
public void setColor(String color) {
this.color = color;
}

public static void main(String[] args) {


Fan fan1 = new Fan();
fan1.setSpeed(3);
fan1.setRadius(10);
fan1.setColor("yellow");
fan1.setOn(true);

Fan fan2 = new Fan();


fan2.setSpeed(2);
fan2.setRadius(5);
fan2.setColor("blue");
fan2.setOn(false);

System.out.println("Fan 1: " + fan1.toString());


System.out.println("Fan 2: " + fan2.toString());
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 38
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

SET 5 – Strings

Practical 1

Aim: (Counting Each Letter in a String). Write a program that prompts the user
to enter a string and counts the number of occurrences of each letter in the string
regardless of case.

Program Code:

import java.util.Scanner;

public class Practical1


{
static final int MAX_CHAR = 256;
static void getOccuringChar(String str)
{
int count[] = new int[MAX_CHAR];

int len = str.length();

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 39
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
for (int i = 0; i < len; i++)

count[str.charAt(i)]++;
char ch[] = new char[str.length()];
for (int i = 0; i < len; i++)
{
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++)
{
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("The occurrence of "+ str.charAt(i)+ " is: " + count[str.charAt(i)]);
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a string: ");
String str = sc.nextLine();
getOccuringChar(str);
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 40
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 2

Aim: (Anagrams). Write a method that checks whether two words are
anagrams. Two words are anagrams if they contain the same letters in any
order. For example, “silent” and “listen” are anagrams. The header of the
method is as follows:
public static Boolean isAnagram(String s1, String s2)

Write a test program that prompts the user to enter two strings and, if they are
anagrams, displays “anagram”, otherwise displays “not anagram”.

Program Code:

import java.util.Arrays;
import java.util.Scanner;

public class AnagramChecker {


public static boolean isAnagram(String s1, String s2) {
s1 = s1.replaceAll("\\s", "").toLowerCase();
s2 = s2.replaceAll("\\s", "").toLowerCase();

if (s1.length() != s2.length()) {
return false;
}
char[] s1Array = s1.toCharArray();
char[] s2Array = s2.toCharArray();

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 41
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
Arrays.sort(s1Array);
Arrays.sort(s2Array);
return Arrays.equals(s1Array, s2Array);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first string: ");


String input1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String input2 = scanner.nextLine();

if (isAnagram(input1, input2)) {
System.out.println("Anagram");
} else {
System.out.println("Not anagram");
}
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 42
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 3

Aim: (Palindrome). Write a program that prompts the user to enter a string and
reports whether the string is a palindrome.

Program Code:

import java.util.Scanner;

public class Practical3 {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

if (isPalindrome(input)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}

public static boolean isPalindrome(String str) {


str = str.replaceAll("\\s", "").toLowerCase();

int left = 0;
int right = str.length() - 1;

while (left < right) {


if (str.charAt(left) != str.charAt(right)) {

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 43
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
return false;
}
left++;
right--;
}
return true;
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 44
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 4

Aim: (Checking substrings). You can check whether a string is a substring of


another string by using the indexOf method in the String class. Write your own
method for this function. Write a program that prompts the user to enter two
strings, and check whether the first string is a substring of the second.

Program Code:

import java.util.Scanner;

public class Practical4 {


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

System.out.print("Enter the first string: ");


String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

if (isSubstring(str1, str2)) {
System.out.println("The first string is a substring of the second string.");
} else {
System.out.println("The first string is not a substring of the second string.");
}
}

public static boolean isSubstring(String str1, String str2) {


int strLength1 = str1.length();
int strLength2 = str2.length();

for (int i = 0; i <= strLength2 - strLength1; i++) {


int j;

for (j = 0; j < strLength1; j++) {

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 45
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
if (str2.charAt(i + j) != str1.charAt(j)) {
break;
}
}

if (j == strLength1) {
return true;
}
}
return false;
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 46
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 5

Aim: (Sorting characters). Write a method that returns a sorted string using the
following header:
public static String sort(String s);
For example, sort(“acb”) returns abc
Write a test program that prompts the user to enter a string and displays the
sorted string.

Program Code:

import java.util.Scanner;

public class Practical5 {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.println("Sorted string: " + sort(input));


}

public static String sort(String s) {


char[] charArray = s.toCharArray();
int n = charArray.length;

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


for (int j = 0; j < n - i - 1; j++) {
if (charArray[j] > charArray[j + 1]) {

char temp = charArray[j];


charArray[j] = charArray[j + 1];
charArray[j + 1] = temp;
}
}
}

return new String(charArray);


Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 47
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 48
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

SET 6 - Inheritance and Interface

Practical 1

1. Aim: Describe abstract class called Shape which has three subclasses say
Triangle,Rectangle,Circle. Define one method area() in the abstract class
and override this area() in these three subclasses to calculate for specific
object i.e. area() of Triangle subclass should calculate area of triangle etc.
Same for Rectangle and Circle

Program Code:

abstract class Shape {


abstract double area();
}

class Triangle extends Shape {


private double base;
private double height;

Triangle(double base, double height) {


this.base = base;
this.height = height;
}

double area() {
return 0.5 * base * height;
}
}

class Rectangle extends Shape {


private double length;
private double width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}
double area() {
return length * width;

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 49
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
}
}

class Circle extends Shape {


private double radius;

Circle(double radius) {
this.radius = radius;
}

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

public class Practical1{


public static void main(String[] args) {
Triangle triangle = new Triangle(5, 8);
System.out.println("Area of Triangle: " + triangle.area());

Rectangle rectangle = new Rectangle(4, 6);


System.out.println("Area of Rectangle: " + rectangle.area());

Circle circle = new Circle(3);


System.out.println("Area of Circle: " + circle.area());
}
}

Output:

Practical 2

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 50
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
Aim: Write a program that illustrates interface inheritance. Interface P is
extended by P1 and P2. Interface P12 inherits from both P1 and P2.Each
interface declares one constant and one method. class Q implements
P12.Instantiate Q and invoke each of its methods. Each method displays one of
the constants

Program Code:

interface P {
int CONSTANT_P = 10;
void methodP();
}

interface P1 extends P {
int CONSTANT_P1 = 20;
}

interface P2 extends P {
int CONSTANT_P2 = 30;
}

interface P12 extends P1, P2 {


int CONSTANT_P12 = 40;
}

class Q implements P12 {


@Override
public void methodP() {
System.out.println("Method P invoked");
}
}

public class Practical2{


public static void main(String[] args) {
Q q = new Q();

// Invoking methods and displaying constants


q.methodP();
System.out.println("Constant from P: " + q.CONSTANT_P);
System.out.println("Constant from P1: " + q.CONSTANT_P1);
System.out.println("Constant from P2: " + q.CONSTANT_P2);
System.out.println("Constant from P12: " + q.CONSTANT_P12);
}
}

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 51
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
Output:

Practical 3

Aim: The abstract Vegetable class has three subclasses named Potato, Brinjal
and Tomato. Write an application that demonstrates how to establish this class

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 52
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
hierarchy. Declare one instance variable of type String that indicates the color
of a vegetable. Create and display instances of these objects. Override the
toString() method of Object to return a string with the name of the vegetable
and its color. Declare an abstract method howToEat() to display how the
vegetables are to be prepared.

Program Code:

abstract class Vegetable {


private String color;

public Vegetable(String color) {


this.color = color;
}
public String getColor() {
return color;
}
public abstract void howToEat();
public String toString() {
return "Vegetable: " + this.getClass().getSimpleName() + ", Color: " + getColor();
}
}
class Potato extends Vegetable {
public Potato(String color) {
super(color);
} public void howToEat() {
System.out.println("Potato: Boil, bake, or fry");
}
}
class Brinjal extends Vegetable {
public Brinjal(String color) {
super(color);
}
public void howToEat() {
System.out.println("Brinjal: Roast, fry, or make curry");
}
}
class Tomato extends Vegetable {
public Tomato(String color) {
super(color);
}
public void howToEat() {
System.out.println("Tomato: Eat raw in salads or use in cooking");
}
}
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 53
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
public class Practical3 {
public static void main(String[] args) {
Potato potato = new Potato("Brown");
Brinjal brinjal = new Brinjal("Purple");
Tomato tomato = new Tomato("Red");
System.out.println(potato);
System.out.println(brinjal);
System.out.println(tomato);

potato.howToEat();
brinjal.howToEat();
tomato.howToEat();
}
}

Output:

Practical 4

Aim: The Transport interface declares a deliver() method. The abstract class
Animal is the superclass of the Tiger, Camel, Deer and Donkey classes. The
Transport interface is implemented by the Camel and Donkey classes. Write a
test program that initialize an array of four Animal objects. If the object
implements the Transport interface, the deliver() method is invoked.
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 54
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Program Code:

interface Transport {
void deliver();
}
abstract class Animal {
}

class Tiger extends Animal {


}

class Camel extends Animal implements Transport {


public void deliver() {
System.out.println("Camel delivers goods across deserts.");
}
}

class Deer extends Animal {


}

class Donkey extends Animal implements Transport {


public void deliver() {
System.out.println("Donkey carries loads in rural areas.");
}
}

public class Main {


public static void main(String[] args) {
Animal[] animals = new Animal[4];
animals[0] = new Tiger();
animals[1] = new Camel();
animals[2] = new Deer();
animals[3] = new Donkey();
for (Animal animal : animals) {
if (animal instanceof Transport) {
((Transport) animal).deliver();
}
}
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 55
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

SET 7 - Exception Handling

Practical 1

Aim: Write a program to handle NoSuchMethodException,


ArrayIndexOutOfBoundsException using try-catch-finally and throw.

Program Code:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 56
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

public class ExceptionHandlingExample {

public static void main(String[] args) {


try {
callNonExistingMethod(); // This method doesn't exist
} catch (NoSuchMethodException e) {
System.out.println("Caught NoSuchMethodException: " + e.getMessage());
}
int[] arr = {1, 2, 3};
try {
int value = arr[5]; // Trying to access index 5 which doesn't exist
System.out.println("Value at index 5: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
try {
int result = divideByZero(10, 0);
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
}
public static void callNonExistingMethod() throws NoSuchMethodException {
throw new NoSuchMethodException("Method doesn't exist");
}
public static int divideByZero(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 57
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 2

Aim: Write an application that generates custom exception if any value from its
command line arguments is negative.

Program Code:
class NegativeNumberException extends Exception
{
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 58
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
public NegativeNumberException(String s)
{
super(s);
}
}
class expdemo3
{
static int check(int m)throws NegativeNumberException
{
if(m<0)throw new NegativeNumberException("Number<0");
return m;
}
public static void main(String args[])
{
try
{
int number=check(Integer.parseInt(args[0]));
System.out.println("You have Entered"+number);
}
catch(NegativeNumberException m)
{
System.out.println(m);
}
System.out.println("end");
}
}
Output:

Practical 3

Aim: Write a method for computing x y by doing repetitive multiplication. x and


y are of type integer and are to be given as command line arguments. Raise and
handle exception(s) for invalid values of x and y. Also define method main. Use
finally in above program and explain its usage.

Program Code:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 59
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
class InvalidNumberException extends Exception
{
InvalidNumberException()
{
System.out.println("Power Is Negative ");
}
}
class power
{
public static void main(String a[])
{
int x=Integer.parseInt(a[0]);
int y=Integer.parseInt(a[1]);
int temp;
try
{
if(y>=0)
{
if(y==0)
{
System.out.println(+x+" Power "+y+" is: "+1);
}
else
{
temp=x;
int i;
for(i=1;i<y;i++)
{
temp=temp*x;
}
System.out.println(+x+" Power "+y+" is: "+temp);
}
}
else if(y<0)
{
throw new InvalidNumberException();
}
}
catch(InvalidNumberException i)
{
double temp1;
int y1=(-y);
temp1=1/(double)x;
for(int j=1;j<y1;j++)
{
temp1=temp1*(1/(double)x);
}
System.out.println(+(double)x+" Power "+y+" is: "+temp1);
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 60
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
}
}
}

Output:

Practical 4

Aim: Write a Java program to accept N integer numbers from the command
line. Raise and handle exceptions for the following cases:

a. when a number is negative


b. when a number is evenly divisible by 10
c. when a number is greater than 1000 and less than 2000
d. when a number is greater than 7000
Skip the number if an exception is raised for it, otherwise add it to find
total sum.

Program Code:
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 61
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
import java.util.Scanner;

class InvalidNumberException extends Exception {


InvalidNumberException(String message) {
super(message);
}
}
public class NumberExceptions {
public static void main(String[] args) {
int sum = 0;
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of integers: ");


int N = scanner.nextInt();

System.out.println("Enter " + N + " integers:");

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


try {
int num = scanner.nextInt();
validateNumber(num);
sum += num;
} catch (InvalidNumberException e) {
System.out.println("Exception: " + e.getMessage() + ". Skipping this number.");
}
}

System.out.println("The sum of valid numbers is: " + sum);


}

public static void validateNumber(int num) throws InvalidNumberException {


if (num < 0) {
throw new InvalidNumberException("Number is negative");
} else if (num % 10 == 0) {
throw new InvalidNumberException("Number is divisible by 10");
} else if (num > 1000 && num < 2000) {
throw new InvalidNumberException("Number is between 1000 and 2000");
} else if (num > 7000) {
throw new InvalidNumberException("Number is greater than 7000");
}
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 62
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

SET 8 - I/O

Practical 1

Aim: Create a class Student. Write a student manager program to manipulate


the student information from files by using FileInputStream and
FileOutputStream.

Program Code:

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Student {

public static void main(String[] args) {


System.out.println("-------Writing Data in File-------");
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 63
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
try {
FileOutputStream fout = new FileOutputStream("stdinfo.txt");
String str = "Nmae : Almash, Stream : AI, Sem : 3rd Sem";
byte b[] = str.getBytes();
fout.write(b);
fout.close();
System.out.println("successful write.");
} catch (Exception e) {
System.out.println(e);
}
System.out.println("-------Retrive Data From File-------");
try {
FileInputStream fin = new FileInputStream("stdinfo.txt");
int i = 0;
while ((i = fin.read()) != -1) {
System.out.print((char) i);
}
fin.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 64
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 2

Aim: Write a Java program to check whether the name from command line is a
file or not? If it is a file then print the size and if it is a directory then it should
display the name of all the files in it.

Program Code:

import java.io.File;

public class FileChecker {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a file/directory name as a command line
argument.");
return;
}

String fileName = args[0];


Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 65
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
File file = new File(fileName);

if (file.exists()) {
if (file.isFile()) {
System.out.println(fileName + " is a file.");
System.out.println("Size of " + fileName + " is " + file.length() + " bytes.");
} else if (file.isDirectory()) {
System.out.println(fileName + " is a directory.");
System.out.println("Files in " + fileName + ":");

File[] files = file.listFiles();


if (files != null) {
for (File f : files) {
if (f.isFile()) {
System.out.println(f.getName());
}
}
}
}
} else {
System.out.println("The specified file/directory does not exist.");
}
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 66
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 3

Aim: Write a Java program using BufferedInputStream, FileInputStream,


BufferedOutputStream, FileOutputStream to copy content of one file Test1.txt
into another file Test2.txt.

Program Code:
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourceFile = "Test1.txt";
String destinationFile = "Test2.txt";
try (FileInputStream fileInputStream = new FileInputStream(sourceFile);
BufferedInputStream bufferedInputStream = new
BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
BufferedOutputStream bufferedOutputStream = new
BufferedOutputStream(fileOutputStream)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, bytesRead);

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 67
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
}
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:

SET 9 - MultiThreading

Practical 1

Aim: Write an application that creates and starts three threads. Each thread is
instantiated from the same class. It executes a loop with 10 iterations. Each
iteration displays string "HELLO", sleeps for 300 milliseconds. The application
waits for all the threads to complete & displays the message "Good Bye...".

Program Code:
class HelloThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("HELLO");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 68
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
public class Practical1 {
public static void main(String[] args) {
Thread thread1 = new HelloThread();
Thread thread2 = new HelloThread();
Thread thread3 = new HelloThread();

thread1.start();
thread2.start();
thread3.start();

try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Good Bye...");
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 69
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

Practical 2

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 70
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
Aim: Write a Java program to create two threads, one thread will check whether
given number is prime or not and second thread will print prime numbers
between 0 to 100.

Program Code:
class PrimeChecker extends Thread {
private int number;

public PrimeChecker(int number) {


this.number = number;
}

@Override
public void run() {
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}

private boolean isPrime(int num) {


if (num <= 1) {
return false;
}

for (int i = 2; i <= Math.sqrt(num); i++) {


if (num % i == 0) {
return false;
}
}
return true;
}
}

class PrimePrinter extends Thread {


@Override
public void run() {
System.out.println("Prime numbers between 0 and 100:");
for (int i = 0; i <= 100; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 71
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT

private boolean isPrime(int num) {


if (num <= 1) {
return false;
}

for (int i = 2; i <= Math.sqrt(num); i++) {


if (num % i == 0) {
return false;
}
}
return true;
}
}

public class Practical2{


public static void main(String[] args) {
// Creating threads
PrimeChecker checkerThread = new PrimeChecker(20);
PrimePrinter printerThread = new PrimePrinter();

// Starting threads
checkerThread.start();
printerThread.start();
}
}

Output:

Your Enrollment No: 23C22504


Name: Almash Yunus Lakdawala. Page 72

You might also like