Computer PDF
Computer PDF
Page Teach
Sl. No. Date Topics / Program Statements
No. er’s
Signa
ture
1. Introduction to Object Oriented Programming 5
1.1 - Object in OOP 5
1.4 - Inheritance 5
1.6 - Encapsulation 5
1.7 - Modularity 5
1.8 - Polymorphism 5
4.1 - Assignment 1 9
4.2 - Assignment 2 12
4.3 - Assignment 3 15
4.4 - Assignment 4 18
4.5 - Assignment 5 21
5.1 - Assignment 1 24
5.2 - Assignment 2 27
5.3 - Assignment 3 30
Page 1 of 127
5.4 - Assignment 4 33
5.5 - Assignment 5 36
6.1 - Assignment 1 40
6.2 - Assignment 2 43
6.3 - Assignment 3 46
6.4 - Assignment 4 49
6.5 - Assignment 5 52
7.1 - Assignment 1 55
7.2 - Assignment 2 58
7.3 - Assignment 3 51
7.4 - Assignment 4 54
7.5 - Assignment 5 57
8.1 - Assignment 1 60
8.2 - Assignment 2 63
8.3 - Assignment 3 66
8.4 - Assignment 4 69
8.5 - Assignment 5 72
Java Programs Based on Arrays, Searching 75
9.
and Sorting in an Array
9.1 - Assignment 1 75
9.2 - Assignment 2 78
9.3 - Assignment 3 81
9.4 - Assignment 4 84
9.5 - Assignment 5 87
10. Conclusion 90
11. Bibliography 91
Page 2 of 127
2. INTRODUCTION TO OBJECT ORIENTED
PROGRAMMING
Write at least one paragraph on the following topics –
- 2.1 - Object in OOP
In object-oriented programming (OOP), objects are the things you think about first in designing a program
and they are also the units of code that are eventually derived from the process.
- 2.2 - Data Abstraction
Data abstraction is the reduction of a particular body of data to a simplified representation of the whole.
Abstraction, in general, is the process of removing characteristics from something to reduce it to a set of
essential elements. To this end, data abstraction creates a simplified representation of the underlying data,
while hiding its complexities and associated operations. In computing, data abstraction is commonly used in
object-oriented programming (OOP) and when working with a database management system (DBMS).
- 2.3 - Abstract Class
An abstract class is a class that contains at least one abstract method. An abstract method is a method that is
declared, but not implemented in the code.
- 2.4 – Inheritance
When a class derives from another class. The child class will inherit all the public and protected properties and
methods from the parent class. In addition, it can have its own properties and methods. An inherited class is
defined by using the extends keyword.
- 2.5 - Final Class
A final class is a class that can't be extended. Also methods could be declared as final to indicate that cannot be
overridden by subclasses. Preventing the class from being subclassed could be particularly useful if you write
APIs or libraries and want to avoid being extended to alter base behaviour.
- 2.6 – Encapsulation
Object-oriented computer programming (OOP) languages, the notion of encapsulation (or OOP Encapsulation)
refers to the bundling of data, along with the methods that operate on that data, into a single unit. Many
programming languages use encapsulation frequently in the form of classes.
- 2.7 – Modularity
Modularity is the process of decomposing a problem (program) into a set of modules so as to reduce the
overall complexity of the problem. Booch has defined modularity as − “Modularity is the property of a system
that has been decomposed into a set of cohesive and loosely coupled modules.”
- 2.8 – Polymorphism
Polymorphism is one of the core concepts of object-oriented programming (OOP) and describes situations in
which something occurs in several different forms. In computer science, it describes the concept that you can
access objects of different types through the same interface. Each type can provide its own independent
implementation of this interface.
Page 3 of 127
3. INTRODUCTION TO PROGRAMMING IN
JAVA
- 3.1 - Concept of Compilers and Interpreters and the Program Execution Process in Java
i. Compiler:
It is a translator which takes input i.e., High-Level Language, and produces an output of low-level la
nguage i.e. machine or assembly language.
A compiler is more intelligent than an assembler it checks all kinds of limits, ranges, errors, etc.
But its program run time is more and occupies a larger part of memory. It has a slow speed because a compiler
goes through the entire program and then translates the entire program into machine codes.
ii. Interpreter:
An interpreter is a program that translates a programming language into a comprehensible
language. –
Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source
code(JAVA Program). This intermediate code makes Java a platform-independent language.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which
java bytecode can be executed.
Page 4 of 127
4. INTRODUCTION TO CONSTRUCTORS IN
JAVA
- 4.1 – Use of the “static”
Keyword
In Java, the static keyword is primarily used for memory management. We can use the static keyword
with variables, methods, blocks, and classes. Using the static class is a way of grouping classes
together. It is also used to access the primitive member of the enclosing class through the object
reference.
The this keyword refers to the current object in a method or constructor. The most common use of the
this keyword is to eliminate the confusion between class attributes and parameters with the same
name (because a class attribute is shadowed by a method or constructor parameter).
-
Page 5 of 127
OUTPUT-
Page 6 of 127
5. JAVA PROGRAMS BASED ON CONSTRUCTORS
5.1 - Assignment 1:
Excel Transport Limited charges for the parcels of its customer as per the following
specificationsgiven below:
Member variables:
String cname – to store the name of the customer
int wt – to store the weight of the parcels in kilogram (kg)
double charges – to store the charges for the parcel
Member functions:
void accept ( )– to accept the name of the customer, weight of the parcel from the user
(usingScanner class)
void calculate ( ) – to calculate the charges as per the weight of the parcelas per the
following criteria.
void display ( ) – to print the name of the customer, weight of the parcel, total bill
amountinclusive of surcharge in a tabular form in the following format :
Name Weight Bill amount
Define a class with the above mentioned specifications, create the main method,
create anobjectand invoke the member functions.
INPUT
Enter the name of the customer : Devjit
Mondal Enter the weight of the parcels in
kilogram (kg) : 13
Page 7 of 127
OUTPUT
Name Weight Bill amount
Devjit Mondal 13 ₹ 682.5
INPUT
Enter the name of the customer : Rahul
Banerjee Enter the weight of the parcels in
kilogram (kg) : 25
OUTPUT
Name Weight Bill amount
Rahul Banerjee 25 ₹ 1207.5
INPUT
Enter the name of the customer : Aman
Mukherjee
OUTPUT
Name Weight Bill amount
Aman Mukherjee 64 ₹ 2289.0
import java.util.Scanner;
public class ETLimited
{
private String cname;
private int wt;
private double charges;
private double char1;
void accept()
{
Scanner sc =new Scanner(System.in);
System.out.print("Enter the name of customer: ");
cname = sc.nextLine();
System.out.print("Enter the weight of the parcel: ");
wt = sc.nextInt();
Page 8 of 127
}
void calculate()
{
{
if(wt<=20)
charges = wt * 50;
else if(wt<=50)
charges = 1000 +((wt-20)*30);
else
charges = 1000 + 900 + ((wt-50)*20);
}
char1= (5/100) * charges ;
charges = charges + char1;
}
void display()
{
System.out.println(" Name Weight
BillAmount");
System.out.println(""+cname+ " " +wt+ "
" +charges);
}
public static void main(String args[])
{
asg5_1 ob = new asg5_1();
ob.accept();
ob.calculate();
ob.display();
}
Page 9 of 127
VDT-
Page 10 of 127
OUTPUT-
Page 11 of 127
5.2 - Assignment 2:
Write a menu driven program to perform the conversion of temperature from one system
ofmeasurement to another. Use constructor to initialize member variables.
The user is given the following options:
(i) Convert from Celsius to Fahrenheit
(ii) Convert from Fahrenheit to Celsius
(iii) Convert from Celsius to Kelvin
For option (i), accept the temperature in Celsius (C). Convert and print the
temperatureinFahrenheit (F)
For option (ii), accept the
temperature inFahrenheit (F).
Convert and print the
temperature inCelsius (C)
For option (iii), accept the temperature in Celsius (C). Convert and print the
temperature inKelvin using the formula: K = C + 273.15
For an incorrect option, an appropriate error message should be displayed
INPUT
User Menu
1. Convert from Celsius to Fahrenheit
2. Convert from Fahrenheit to Celsius
3. Convert from Celsius to KelvinEnter your Choice : 1
Enter the Temperature in Celsius : 40
OUTPUT
Resultant Temperature in Fahrenheit : 104.0
INPUT
User Menu
1. Convert from Celsius to Fahrenheit
2. Convert from Fahrenheit to Celsius
3. Convert from Celsius to KelvinEnter your Choice : 2
Enter the Temperature in Fahrenheit : 86
OUTPUT
Resultant Temperature in Celsius : 30.0
import java.util.Scanner;
class asg4_2
{
public static void main(String args[])
Page 12 of 127
{
Page 13 of 127
VTD-
Page 14 of 127
OUTPUT-
Page 15 of 127
5.3 - Assignment 3:
Define a class Telephone having the following description :
Member Methods :
void input ( ) – to input the name of the customer and number of calls made
user(usingScanner class)
void cal ( ) – to calculate the amount and total amount to be paid
void display ( ) – to display the name of the customer, calls made, amount and total amount to
bepaidin the following format :
However every customer has to pay ₹ 180per month as monthly rent for availing the service.
INPUT
Enter the name of the customer : Arjab
Mitra
OUTPUT
Name Calls Made Total Amount
Page 16 of 127
Arjab Mitra 55 ₹ 180.0
INPUT
Enter the name of the customer : Arfin
Rana
OUTPUT
Name Calls Made Total Amount
Arfin Rana 175 ₹ 247.5
import java.util.Scanner;
class Telephone {
String name;
int calls;
double amt;
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the name of the Customer: ");
name = sc.nextLine();
System.out.print("Enter the number of calls made: ");
calls = sc.nextInt();
}
void cal() {
double monthlyRent = 180.0;
if (calls <= 100) {
amt = monthlyRent;
} else if (calls <= 200) {
amt = monthlyRent + (calls - 100) * 0.90;
} else if (calls <= 400) {
amt = monthlyRent + 100 * 0.90 + (calls - 200) * 0.80;
} else {
amt = monthlyRent + 100 * 0.90 + 200 * 0.80 + (calls - 400) * 0.70;
}
}
void display() {
System.out.println("Name\tCalls Made\tTotal Amount");
System.out.println(name + "\t" + calls + "\t " + amt);
}
public static void main(String[] args)
Page 17 of 127
{
Telephone ob = new Telephone();
ob.input();
ob.cal();
ob.display();
}
}
Page 18 of 127
VTD-
Page 19 of 127
OUTPUT-
Page 20 of 127
5.4 - Assignment 4:
Write a menu driven program to perform the calculation of the volume of geometrical
structures.Theuser is given the following options: Implement the concept of overloaded
constructors.
(i) Volume of Cube
(ii) Volume of Cone
(iii) Volume of Sphere
(iv) Volume of Cuboid
(v) Volume of Cylinder
For option (i), accept the side (s) of a cube. Calculate and print the volume of cube
For option (ii), accept the radius (r) and height (h) of a cone. Calculate and print the
volume ofconeFor option (iii), accept the radius (r) of a sphere. Calculate and print the
volume of sphere
For option (iv), accept the length (l), breadth (b) and height (h) of a cuboid. Calculate and print
thevolumeof cuboid
For option (v), accept the radius (r) and height (h) of a cylinder. Calculate and print the
volume ofcylinderFor an incorrect option, an appropriate error message should be displayed.
INPUT
User Menu
1. Volume of Cube
2. Volume of Cone
3. Volume of Sphere
4. Volume of Cuboid
5. Volume of Cylinder
OUTPUT
Volume of Cube : 29.791
INPUT
Page 21 of 127
User Menu
6. Volume of Cube
7. Volume of Cone
8. Volume of Sphere
9. Volume of Cuboid
10. Volum
e of CylinderEnter
your Choice : 3
Enter the Radius of Sphere : 1.1
OUTPUT
Volume of Sphere : 5.57752381
INPUT
User Menu
1. Volume of Cube
2. Volume of Cone
3. Volume of Sphere
4. Volume of Cuboid
5. Volume
of Volume of Choice :
4
Enter the Length of Cuboid :
1.1 Enter theBreadth of Cuboid
: 2.2Enter the Height of Cuboid
: 3.3
OUTPUT
Volume of Cuboid : 7.986
mport java.util.Scanner;
lass Asg4_4
Page 22 of 127
System.out.println("===================");
System.out.println("1. Volume of Cube");
System.out.println("2. Volume of Cone");
System.out.println("3. Volume of Sphere");
System.out.println("4. Volume of Cuboid");
System.out.println("5. Volume of Cylinder");
ch=sc.nextByte();
switch(ch)
{
case 1:
System.out.println("Enter sides of the cube");
s=sc.nextDouble();
v=Math.pow(s,3);
System.out.println("Volume of the cube= "+v);
break;
case 2:
System.out.println("Enter radius of the cone");
r=sc.nextDouble();
System.out.println("Enter height of the cone");
h=sc.nextDouble();
v=Math.PI*Math.pow(r,2)*h/3;
System.out.println("Volume of the cone= "+v);
break;
case 3:
System.out.println("Enter radius of the sphere");
r=sc.nextDouble();
v=(4/3)*Math.PI*Math.pow(r,3);
System.out.println("Volume of the cone= "+v);
break;
case 4:
System.out.println("Enter length of the cuboid");
l=sc.nextDouble();
System.out.println("Enter breadth of the cuboid");
b=sc.nextDouble();
System.out.println("Enter height of the cuboid");
h=sc.nextDouble();
v=l*b*h;
System.out.println("Volume of the cone= "+v);
break;
case 5:
System.out.println("Enter radius of the cylinder: ");
Page 23 of 127
r=sc.nextDouble();
System.out.println("Enter height of the cylinder: ");
h=sc.nextDouble();
v=Math.PI*Math.pow(r,2)*h;
System.out.println("Volume of the cone= "+v);
break;
default:
System.out.println("Invalid Input");
}
}
}
Page 24 of 127
VTD-
Page 25 of 127
OUTPUT-
Page 26 of 127
5.5 - Assignment 5:
A company announces an increment of their employees on the seniority basis (length of
service) asper the given tariff:
Length of service Increment Dearness Allowance
Up to 10 years 20% of 10% of basic
basic
Above 10 and up to 20 25% of 15% of basic
years basic
Above 20 years 30% of 20% of basic
basic
Member methods :
void getdata(String n, int p, : to accept
name, length of service,basicdouble bs, double d)
and DA
void calculate( ) : to find increment and update basic salary.
: to display length of service and update basic salaryinthe format given
below:
Output:
Name Length of service Basic Salary DA
****** *********** ********* *********
****** *********** ********* *********
****** *********** ********* *********
INPUT
Name: Ashish
Kumar Shaw Enter
the basic pay:
15000.0Enter the
length of service: 12
Page 27 of 127
OUTPUT
Name Length of Service Basic Salary DA
Ashish Kumar 12 15000.0 2250.0
Shaw
package CLASS_10;
import java.util.Scanner;
class Increment {
private String name;
private double basic;
private int lengthOfService;
private double dearnessAllowance;
scanner.close();
}
}
Page 29 of 127
VTD-
Page 30 of 127
OUTPUT-
Page 31 of 127
5. NUMBER BASED PROGRAMS IN JAVA
5.1 - Assignment 1:
Write a program to accept a number and check if it is a happy number or not
The happy number can be defined as a number which will yield 1 when it is replaced by the
sum of the square of its digits repeatedly. If this process results in an endless cycle of
numbers containing 4, then the number is called an unhappy number.
32 + 22 = 13
12 + 32 = 10
12 + 02 = 1
Some of the other examples of happy numbers are 7, 28, 100, 320
and so on. The unhappy number will result in a cycle of 4, 16, 37,
To find whether a given number is happy or not, calculate the square of each digit present
in number and add it to a variable sum. If resulting sum is equal to 1 then, given number is
a happy number. If the sum is equal to 4 then, the number is an unhappy number. Else,
replace the number with the sum of the square of digits.
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class happy_num
{
private int n,d=0,s=0;
void acpt()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
n = sc.nextInt();
}
void isHappy()
{
while(n!=1 && n!=4)
{
while(n!=0)
{
Page 32 of 127
d = n%10;
s = s + d*d;
n/=10;
}
n=s;
break;
}
}
void chk()
{
if(s==n)
{
System.out.println("Happy");
}
else
{
System.out.println("not Happy");
}
}
public static void main(String args[])
{
happy_num ob = new happy_num();
ob.acpt();
ob.isHappy();
ob.chk();
}
}
Page 33 of 127
VTD-
Page 34 of 127
OUTPUT-
Page 35 of 127
5.2 - Assignment 2:
Write a program to accept a number and check if it is a Circular Prime number or not
A circular prime is a prime number with the property that the number generated at each
intermediate step when cyclically permuting its digits will be prime. For example, 1193 is a
circular prime, since 1931,9311 and 3119 all are also prime.
import java.util.Scanner;
public class cir_pri_num
{
public static void main(String args[])
{
int n,num,r,c=0;
boolean flg=true;
num=n;
while(num>0)
{
r = num%10;
c++;
num = num/10;
}
num=n;
for(int i =1; i<=c; i++)
{
r = num%10;
num = num/10;
num = (r * (int) Math.pow(10, c-1)) + num;
if(!prime(num))
{
flg = false;
break;
}
}
if(flg)
System.out.println("Circular prime");
Page 36 of 127
else
}
static boolean prime(int n)
{
int i =2;
boolean flg = true;
while(n>i)
{
if(n%2==0)
{
flg = false;
break;
}
i++;
}
return flg;
}
}
Page 37 of 127
VTD-
Page 38 of 127
OUTPUT-
Page 39 of 127
5.3 - Assignment 4:
Write a program to accept a number and check if it is a Evil number or not
The Evil number is another special positive whole number in Java that has an even number
of 1's in its binary equivalent. Unlike Prime and Armstrong numbers, Evil number is not so
popular and asked by the interviewers.
The numbers which are not evil are called odious numbers. Some examples of evil and
odious numbers.
1. 15 is an evil number because in its binary equivalent, i.e., 1111, it has an even number of ones.
2. 16 is an odious number because in its binary equivalent, i.e., 10000 has not even number of ones
3. 23 is also an evil number because it has an even number of ones in its binary equivalent,
i.e., 10111.
import java.util.Scanner;
public class evil_or_odi
{
private int n,m,c=0,r=0;
void acpt()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check if it is evil or odious number");
n = sc.nextInt();
}
void isEvil()
{
m=n;
while(m>0)
{
r = m%2;
if(r%2==1)
c++;
m = m/2;
}
if(c%2==0)
System.out.println("It is evil number");
else
System.out.println("It is a odious number");
}
public static void main(String args[])
{
evil_or_odi ob = new evil_or_odi();
ob.acpt();
ob.isEvil();
Page 40 of 127
}
}
VTD-
Variable name Type Purpose
n Int
to store the number of which
the user as enter
m int To make a duplicate of variable
n
c int For counter
r int For remainder
Page 41 of 127
OUTPUT-
Page 42 of 127
5.4 - Assignment 5:
Write a program to accept a number and check if it is a Automorphic number or not
A number is called an automorphic number if and only if the square of the given number
ends with thesame number itself.
For example, 25, 76 are automorphic numbers because their square is 625 and 5776,
respectively and the last two digits of the square represent the number itself. Some other
automorphic numbers are 5, 6, 36, 890, 625, etc.
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class automor_num
{
private int n,sq,flg=0;
void acpt()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check if it is Automorphic number or not");
n = sc.nextInt();
}
void isAuto()
{
sq=n*n;
while(n>0)
{
if(n%10!=sq%10)
flg=1;
n/=10;
sq/=10;
}
}
void chk()
{
if(flg==1)
{
System.out.println("Automorphic number");
}
else
{
System.out.println("not Automorphic number");
}
}
Page 43 of 127
public static void main(String args[])
{
automor_num ob = new automor_num();
ob.acpt();
ob.isAuto();
ob.chk();
}
}
Page 44 of 127
VTD-
Page 45 of 127
OUTPUT-
Page 46 of 127
7. SERIES BASED PROGRAMS IN JAVA
7.1 - ASSIGNMENT 1:
Write a program to calculate the sum of the numbers in the series mentioned below:
𝟏! 𝟑! 𝟓! (𝟐𝒏 − 𝟏)!
𝑺= + + + ⋯……+
𝒙𝟏
where
x = a variable
n = no. of terms
You have to accept the value of x and n from the user and then calculate the sum of the series.
package All_School_assgigment;
import java.util.Scanner;
import java.io.*;
import java.lang.*;
class asgin
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the value of x");
double x = sc.nextDouble();
System.out.println("Enter the value of n");
int n = sc.nextInt();
double sum = 0;
for(int i = 1; i<=n; i++)
{
int f = 1;
for(int j=1;j<=2*i-1;j++)
{
f*=j;
}
sum+=(f * Math.pow(x,i))/Math.pow(x,i-1);
}
System.out.println("Sum of series "+ sum);
sc.close();
}
}
Page 47 of 127
VTD-
Page 48 of 127
Page 49 of 127
OUTPUT-
Page 50 of 127
7.2 - ASSIGNMENT 2:
Write a program to calculate the sum of the numbers in the series mentioned below:
S = 1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) + ............ + (1 + 2 + 3 + 4 + ......... + n)
Page 51 of 127
VTD-
Page 52 of 127
OUTPUT-
Page 53 of 127
7.3 - ASSIGNMENT 3:
Write a program to calculate the sum of the numbers in the series mentioned
where n = 101
import java.util.Scanner;
public class asg_7_3
{
public static void main(String args[])
{
int n=101;
int s=0;
for(int i = 3; i<=n; i+=4)
s+=(i-(i-2));
System.out.println("Sum " + s);
}
}
Page 54 of 127
VTD-
Variable name Type Purpose
n Int For no. of terms
s Int For addition
i Int For increment in forloop
Page 55 of 127
OUTPUT-
Page 56 of 127
7.4 - ASSIGNMENT 4:
Write a program to calculate the sum of the numbers in the series mentioned below:
import java.util.Scanner;
public class asg_7_4
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter num of terms”);
int n = sc.nextInt();
sc.close();
int t=0;
int s=0;
for(int i = 1; i<=n; i++)
{
t = t * 10+i;
s+=t;
}
System.out.println("Sum " + s);
}
}
Page 57 of 127
VTD-
Page 58 of 127
OUTPUT-
Page 59 of 127
7.5 - ASSIGNMENT 5:
Write a program to calculate the sum of the numbers in the series mentioned below:
S = 1 + 11 + 111 + 1111 + ............. + n
where n = no. of terms
You have to accept the value of n from the user and then calculate the sum of the series.
import java.util.Scanner ;
public class se10
{
public static void main(String args[])
{
System.out.println(“Enter no.of terms”):
int n = sc.nextInt();
int i,s=0,s1=0;
for(i=1; i<=n; i++)
{
s=s*10+1;
s1 = s1 +s;
//System.out.print(s + " ");
}
System.out.print(s1);
}
}
Page 60 of 127
VTD-
Page 61 of 127
OUTPUT-
Page 62 of 127
8. METHOD OVERLOADING BASED PROGRAMS IN JAVA
8.1 – ASSIGNMENT 1:
Design a class overloading a function Compute ( ) as follows:
a) void Compute(String str, int p) with one String argument and one integer argument. It
displays the word in upper case if p is 1 otherwise, displays the word in lower case.
b) void Compute(char chr, int p) with one character argument and one integer argument. It
checks and displays whether a character is in upper case or not if p is 1 otherwise,
displays thecharacter in lower case or not.
c) void Compute( String str, char chr) with one String argument and one character
argument. Itdisplays the first three characters of a String if chr is ‘f’ otherwise, displays
the last three characters of the String.
// Method to display the word in upper or lower case based on the value of 'p'
public void Compute(String str, int p) {
if (p == 1) {
System.out.println(str.toUpperCase());
} else {
System.out.println(str.toLowerCase());
}
}
Page 64 of 127
VTD-
Page 65 of 127
OUTPUT-
Page 66 of 127
8.2 - ASSIGNMENT 2:
Define a class called Employee with the following description:
Instance variables/ Data members:
int emp_ no: to accept the employee number
String name: to input the name of an
employee
int bas: to accept basic salary
Member methods:
void accept ( ) : to accept emp_no, name and basic salary
void compute ( ): to compute the gross salary and net salary of the employee accordingly:
da = 40% of basic salary
hra = 15% of basic salary
pf = 12% of basic salary
epf = 1.67% of basic salary
gross = bas + da + hra
net_sal = gross – (pf + epf)
void display ( ): to display the details of the employee with gross and net salary
Write a main method to create an object of the class and call the above member
methods. You canchange the return types of the methods if required
INPUT
Enter the employee number : 16
Enter the name of an employee:
Aniket SarkarEnter the basic
salary : 18000
OUTPUT
Name:Aniket Sarkar
Employee Number: 16
Gross salary: Rs. 27900.0
Net Salary: Rs. 25439.4
import java.util.Scanner;
class Employee
{
// Instance variables
private int emp_no;
private String name;
private int bas;
Page 67 of 127
// Member method to accept employee details
void accept()
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the employee number: ");
emp_no = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
System.out.print("Enter the name of an employee: ");
name = scanner.nextLine();
System.out.print("Enter the basic salary: ");
bas = scanner.nextInt();
}
Page 68 of 127
VTD-
Page 69 of 127
OUTPUT-
Page 70 of 127
8.3 - ASSIGNMENT 3:
Design a class to overload a function area ( ) as follows:
double area ( double a, double b, double c) – with three double arguments returns the
area of scalenetriangle using the formula:
where s= (a + b + cArea = √(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐)
double area(int a, int b, int height) – with three integer arguments, returns the area of a
trapezium using the formula:
double area (double diagonal1, double diagonal2) – with the double arguments, returns
the area of a rhombus using the formula:
Area = ( 1 / 2 )
*(diagonal1*diagonal2)
You have to accept data as per requirement of the user
choice
INPUT
Enter the sides of a triangle:
10
12
7
OUTPUT
The area is: 499.028869
import java.util.Scanner;
Page 71 of 127
// Method to calculate the area of a rhombus
public double area(double diagonal1, double diagonal2) {
return 0.5 * diagonal1 * diagonal2;
}
switch (choice) {
case 1:
System.out.println("Enter the sides of the triangle:");
double sideA = sc.nextDouble();
double sideB = sc.nextDouble();
double sideC = sc.nextDouble();
double triangleArea = ob.area(sideA, sideB, sideC);
System.out.println("The area is: " + triangleArea);
break;
case 2:
System.out.println("Enter the values of the trapezium:");
int baseA = sc.nextInt();
int baseB = sc.nextInt();
int heightTrapezium = sc.nextInt();
double trapeziumArea = ob.area(baseA, baseB, heightTrapezium);
System.out.println("The area is: " + trapeziumArea);
break;
case 3:
System.out.println("Enter the diagonals of the rhombus:");
double diagonal1 = sc.nextDouble();
double diagonal2 = sc.nextDouble();
double rhombusArea = ob.area(diagonal1, diagonal2);
System.out.println("The area is: " + rhombusArea);
break;
default:
Page 72 of 127
System.out.println("Invalid choice.");
break;
}
sc.close();
}
}
Page 73 of 127
VTD-
Page 74 of 127
OUTPUT-
OUTPUT-
Page 75 of 127
8.4 - ASSIGNMENT 4:
Define a Class called Library with the following description:
Member methods:
(i) void input ( ) : to input and store accession number, title and author.
(ii) void compute ( ) : to accept the number of days late, calculate the display the fine
charged the rate Rs.2 per day.
(iii) void display ( ) : to display the details in the following format:
Accession Number Title Author Fine
………………………….. ……………………………….. ………………………………. …….
………………………… ………………………………. …………………………….. …….
…………………………… ……………………………….. ………………………………. …….
INPUT
Enter the accession number: 1530
Enter the title of the book: The
Namesake Enter the name of the
author: Jhumpa LahiriEnter the
number of days late: 14
OUTPUT
Accession Number Title Author Fine
153 The Jhumpa Lahiri 28.0
0 Namesake
import java.util.Scanner;
public class Library
{
// Instance variables
private int acc_num;
private String title;
private String author;
Page 77 of 127
VTD-
Page 78 of 127
OUTPUT-
Page 79 of 127
8.5 - ASSIGNMENT 5:
Write a class program with the following specifications:
Class name: stringpro
Member Methods:
String pro (String) : Parameterized constructor to initialize str.
void count(char c) : To find and print the frequency of a character in the string.
void compare(String) : To compare the string str with the
string passed as argument and print whether the given string as
argument is larger,
smaller or equal.
INPUT
Enter the string: COMPUTER APPLICATIONS
OUTPUT
Frequency of characters:
Character Frequency
A 2
C 2
E 1
I 2
L 1
M 1
N 1
O 2
P 3
R 1
S 1
T 2
U 1
Page 80 of 127
package All_School_assgigment;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
if (result > 0) {
System.out.println("The given string is larger.");
} else if (result < 0) {
System.out.println("The given string is smaller.");
} else {
System.out.println("The given string is equal.");
}
}
Page 81 of 127
String inputString = sc.nextLine();
sc.close();
}
}
Page 82 of 127
VTD-
Page 83 of 127
OUTPUT-
Page 84 of 127
9. STRING BASED PROGRAMS IN JAVA
9.1 - ASSIGNMENT 1:
Write a program to input a sentence. Convert in Upper case and shift each letter of the
English alphabet two steps towards the right. Characters other than alphabets remain the
same. Print original and new string in two different lines.
// Input a sentence
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();
// Convert to uppercase
String upperCaseSentence = sentence.toUpperCase();
if (Character.isLetter(currentChar)) {
char shiftedChar = (char) (currentChar + 2);
shiftedSentence.append(shiftedChar);
} else {
// Non-alphabet characters remain the same
shiftedSentence.append(currentChar);
Page 85 of 127
}
}
System.out.println("Shifted Sentence:");
System.out.println(shiftedSentence.toString());
sc.close();
}
}
Page 86 of 127
VTD-
Page 87 of 127
OUTPUT-
Page 88 of 127
9.2 - ASSIGNMENT 2:
Write a program in Java to enter a String/Sentence and display the longest word and the
length of the longest word present in the String.
Sample Input: “TATA FOOTBALL ACADEMY WILL PLAY AGAINST MOHAN BAGAN”
Sample Output:
The longest
word: FOOTBALL
The length of
the word: 8
import java.util.Scanner;
import java.io.*;
import java.lang.*;
// Input a sentence
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();
Page 89 of 127
// Print the longest word and its length
System.out.println("The longest word: " + longestWord);
System.out.println("The length of the word: " + maxLength);
sc.close();
}
}
Page 90 of 127
VTD-
Page 91 of 127
OUTPUT-
Page 92 of 127
9.3 - ASSIGNMENT 3:
Write a program in JAVA to accept a word .Convert and Display the word in Pig Latin. A Pig
Latin is an encrypted word in English, which is generated by doing following altercations:
The first vowel occurring in the input word is placed at the start of the new word along
with the remaining alphabets of it. The alphabets present before the first vowel are
shifted at the end of the new word followed by “ay” or “AY”
For example:
TROUBLE ->
OUBLETRAY
OWL->
OWLAY
package All_School_assgigment;
import java.util.Scanner;
// Input a word
System.out.print("Enter a word: ");
String inputWord = scanner.nextLine();
scanner.close();
}
Page 93 of 127
// Find the index of the first vowel
for (int i = 0; i < word.length(); i++) {
char currentChar = word.charAt(i);
if (currentChar == 'A' || currentChar == 'E' || currentChar == 'I' || currentChar == 'O'
|| currentChar == 'U') {
firstVowelIndex = i;
break;
}
}
return pigLatin;
}
}
Page 94 of 127
VTD-
Page 95 of 127
OUTPUT-
Page 96 of 127
9.4 - ASSIGNMENT 4:
Write a program to accept a sentence in mixed case. Find the frequency of vowels in each
word andprint the words along with their frequencies in separate lines.
Sample Input:
We are learning scanner class
Sample Output:
We are learning scanner class
Word
frequency of vowels
we 1
are 2
learning 3
scanner 2
class 1
package All_School_assgigment;
import java.util.Scanner;
// Input a sentence
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
scanner.close();
}
Page 97 of 127
// Display the header
System.out.printf("%-15s%s%n", "Word", "Frequency of Vowels");
return vowelCount;
}
}
Page 98 of 127
VTD-
Page 99 of 127
OUTPUT-
package All_School_assgigment;
import java.util.Scanner;
// Input a word
System.out.print("Enter a word: ");
String inputWord = scanner.nextLine();
scanner.close();
}
10.1 - ASSIGNMENT 1:
Write a program in Java to accept the names and total marks of N number of students in two
singledimensional arrays – name [ ] and totalmarks [ ]
Calculate and print the following:
The average of the total marks obtained by the N number of
students[Average = (sum of total marks of all the students) /
N]
Name and deviation of each student’s total marks with
the average[Deviation = total marks of a student –
average]
package All_School_assgigment;
import java.util.Scanner;
scanner.close();
}
// Method to search for a city in the array and return its index
private static int searchCityIndex(String[] cities, String searchCity) {
for (int i = 0; i < cities.length; i++) {
if (cities[i].equalsIgnoreCase(searchCity)) {
return i; // Return the index of the city if found
}
}
return -1; // Return -1 if the city is not found
}
}
import java.util.Scanner;
scanner.close();
}
return mergedArray;
}
Output:
Original Matrix:
9 5 2 4
1 6 3 9
2 8 7 7
2 6 0 5
Product of only prime numbers present in the left diagonal = 35
Sum of all the elements except the boundary elements = 24
package All_School_assgigment;
import java.util.Scanner;
// Calculate and print the product of prime numbers in the left diagonal
int productOfPrimes = productOfPrimeNumbersLeftDiagonal(matrix);
System.out.println("Product of only prime numbers present in the left diagonal = " +
productOfPrimes);
// Calculate and print the sum of all elements except the boundary elements
int sumExceptBoundary = sumOfElementsExceptBoundary(matrix);
System.out.println("Sum of all the elements except the boundary elements = " +
sumExceptBoundary);
}
// Method to calculate the sum of all elements except the boundary elements
private static int sumOfElementsExceptBoundary(int[][] matrix) {
int sum = 0;
for (int i = 1; i < matrix.length - 1; i++) {
for (int j = 1; j < matrix[i].length - 1; j++) {
sum += matrix[i][j];
}
}
return sum;
}
}
Output:
Original Matrix:
1 2 3
6 5 4
7 8 9
Matrix after 90 Degree Anti–Clockwise Rotation:
3 4 9
2 5 8
1 6 7
Sum of corner elements = 20
package All_School_assgigment;
import java.util.Scanner;
return rotatedMatrix;
}
while OOP has its learning curve, the benefits it brings in terms of code organization,
reusability, and scalability make it a valuable paradigm in modern software development. As
developers become more proficient in OOP, they can leverage its principles to create robust,
maintainable, and scalable software solutions.
Give the names of the books and the websites visited for researching on the above topics
andprogramming in the format given below