Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Indira Gandhi Delhi Technical University for Women

(Established by Govt. of Delhi vide Act 09 of 2012)

Kashmere Gate, Delhi - 110006

LABMANUAL
For

OOPSUSINGJAVA
(BAI-102)

SUBMITTED TO:
Department MR Rahul Intelligence
of Artificial Sachdeva & Data
SUBMITTED BY: Divyanshi CSE-AI
Sciences
(Enrollment no. = 05401172023)
INDEX
S. No. Experiment
1 1. Write a program to multiply two floating point
Introduction numbers
to 2. Write a program to swap two numbers
Data Types 3. Write a program to add two binary strings
4. Write a program to add two complex numbers
5. Write a program to calculate simple interest
6. Write a program to calculate compound interest
7. Write a program to find perimeter of rectangle
8. Write a program to find area of circle for radius
entered by user
2 1. * print without loops
Practice in
* *
Loops
* * *
* * * *
2. Print (a+(b*c))/(b-c) taking a, b, c as input
3. Print table of a number taken from user
4. Convert rupees, taken as input, to paise

3 1. Convert degree Celsius, taken as input, to degree


Conditional Fahrenheit
Statements 2. Convert degree Celsius, taken as input, to degree
Fahrenheit
3. Input marks and print grade 85-100: A 70-85: B
60-70: C 50-60: D <50:FAIL
4 1. Convert binary to decimal
Loops and 2. Find roots of quadratic equation
Conditionals 3. Find sum of series (1/x) + (1/x^2) +…. Till n terms.
5 1. Create a calendar, enter date to get its previous date,
Appilcation next date and days
Program 2. Use 2D array to print matrix, perform addition and
multiplication on it with another matrix.
6 1. Create calculator
Calculator 2. Create calculator using Switch
7 1. Create base class distance, give private parameter d1.
Introduction to Create constructors for add, subtract and print. Two
classes derived classes Dinch( convert d1 to inches) Dmiles(
convert d1 to miles), give them same constructors.
Use override to print and add
2. Create an employee class with private members name
address age gender taken as input, use constructor to
initialize values to the variable, display all. Derive
employee class into full time employee, with
members salary and designation (display all) and part
time employee with members work hour and rate per
hour from which pay can be calculated (work hour *
rate per hour), display pay
3. Create class vehicles with members color type weight
and read() print(). Derive it into two classes, Car with
members model engine number of seats and read()
print(), Bike with members engine tyre and read()
print()
4. Create class vehicles with members color type weight
and read() print(). Derive it into two classes, Car with
members model engine number of seats and read()
print(), Bike with members engine tyre and read()
print()
5. Create class addTime that can add two times in hr,
min, sec
8 1. Create class addTime that can add two times in hr,
Inheritance min, sec
2. Create a base class account having acc number, acc
type, name of holder, read(), print().Derive this class
into savings and current acc class where savings acc
has interest rate 10%, update balance; and current acc
has maximum number of transactions. If number of
transactions >30, deduct 1500. Create 10 objects, 5 of
savings type and 5 of current type
3. Create a class to read and print details of students.
Also create function to get average, minimum and
maximum marks.
9 1. Design an interface with a method reverse that
Interfaces reverses the digits of a number
2. Design an interface having method to get velocity
with parameter r that calculates and returns velocity
of a satellite given by the formula velocity=root mu/r
where r is the altitude of satellite taken from the earth
and mu is Kepler’s constant with value 3.986004418*
(10**5). Create a nested interface with a method to
get acceleration with parameter r that calculates and
returns the acceleration of the satellite given by the
formula mu/(r**2)
3. Write a program having a mean interface. Create a
method mean that calculates the mean of user entered
numbers arranged in an array. Extend the interface
having method deviation that calculates the (absolute)
deviation from the mean value for each of the
numbers in the array.
4. Write a program in which 3 interfaces I1 I2 I3 are
defined, I2 extends I1, I3 extends I1 and I2. I1
declares a method withdraw, I2 declares a method
deposit, I3 declares display that shows balance of
account number. Create a class with var acc number,
name, address, balance that implements the interfaces
10 1. Write a program that calculates area of a room and the
File cost of white washing, include provision for window
Handling-1 on any of the walls. The parameters for the room
length height width are taken from the user. If there is
a window then its length and width are taken from the
user. In any case of parameter, if input is less than 1
then throw an invalid dimension exception; otherwise
calculate and display area and cost of white washing
2. Write a program that reads data for name class roll
number marks of a student and print them to a file.
Also read details from the file and dhow on the
monitor
3. Write a program to copy contents of one file into
another
11 1. Write a program to check whether the contents in two
File files is same or not
Handling-2
2. Write a program to count the number of digits stored
in the file
3. Write a program to write a string character by
character to a file and read the string character by
character from the file, print it on the screen
4. Read the data from the keyboard using buffered
reader class
12 Create class with members name, roll number,
Application stream, marks, write it in a file for 10 student such
Program that when you enter roll number, only the details of
that student are printed.
Programs on the Basic Concepts of OOPS IN JAVA
Experiment 1: Introduction to Data Types

Program 1: Write a program to multiply two floating point numbers.


Soln:
CODE:
public static void main(String[] args){
float x=1.5f;
float y=2.0f;
/* f ensures that numbers are float, otherwise assigned double*/ float
product=x*y;
System.out.println("product is "+product);

Program 2: Write a program to swap two numbers.


Soln:
CODE:

public static void main(String[] args){


int x=10;
int y=5;
int
temp=x;
x=y;
y=temp;
System.out.println("x:"+ x +"\n" +"y:"+y);
Program 3: Write a program to add two binary strings.
Soln:
CODE:
import java.util.Scanner;
public class addbinarystrings {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter binary strings ");
Long x=sc.nextLong(); Long y=sc.nextLong();
int i=0,carry=0;
int[]sum=new int[10]; //hold output binary num
while(x!=0 || y!=0){
sum[i++]=(int)(((x%10)+(y%10)+carry)%2);
carry=(int)((x% 10 + y % 10 + carry) / 2); x=x/10;
y=y/10;
}if (carry!=0){
sum[i++]=carry;
}i=i-1;
System.out.print("sum: ");
while (i >= 0) {
System.out.print(sum[i--]);
}System.out.print("\n"); }}

Program 4: Write a program to add two complex numbers


Soln:
CODE:
class addcomplexnos {
int real, imaginary; public
addcomplexnos(int r, int i){
this.real=r; this.imaginary=i;
}public void show(){
System.out.print(this.real+"+i"+this.imaginary); }public static
addcomplexnos add(addcomplexnos x,addcomplexnos y){ addcomplexnos n=new
addcomplexnos(0,0);
n.real=x.real+y.real;
n.imaginary=x.imaginary+y.imaginary;
return n;
}public static void main(String[] args){
addcomplexnos c1= new addcomplexnos(2,3);
addcomplexnos c2= new addcomplexnos(5,6);
System.out.println("First number: "); c1.show();
System.out.println("First number: "); c2.show();
addcomplexnos n=add(c1,c2);
System.out.println("Sum :");
n.show(); }
}

Program 5: Write a program to calculate simple interest


Soln:
CODE:
public class simpleinterest {
public static void main(String[] args){
double principal=1000,rate=0.05,time=3;
double si=(principal*rate*time)/100;
System.out.println(si);
}
}

Program 6: Write a program to calculate compund interest


Soln:
CODE:
public class compoundinterest {
public static void main(String[] args){
double principal=1000, rate=5,time=3;
double ci=principal*(Math.pow((1+(rate/100)),time));
System.out.println(ci);
}
}

Program 7: Write a program to find perimeter of rectangle


Soln:
CODE:
public class rectangleperimeter {
public static void main(String[] args) {
float l = 10, b = 20,perimeter = l * b;
System.out.println("Perimeter: "+perimeter);
}
}

Program 8: Write a program to find area of circle for radius entered by user
Soln:
CODE:
import java.util.*;
public class circlearea {
public static void main(String[]args){
Scanner sc=new Scanner(System.in); //system.in is standard input stream

System.out.print("enter radius of circle:


"); int r=sc.nextInt(); double
area=3.14*r*r;
System.out.println("area of circle: "+area);
}
}

Experiment 2: Practice In Loops

Program 1: Print without loops.


*

* *

* * *

* * * *

Soln:
CODE:
public class patternwithoutloop {
public static void main(String[]args){
System.out.println("*");
System.out.println("* *");
System.out.println("* * *");
System.out.println("* * * *");
}
}
Program 2: Print (a+(b*c))/(b-c) taking a, b, c as input
Soln:
CODE:

import java.util.*;
public class abc {
public static void main(String[]args){
Scanner sc=new
Scanner(System.in);
System.out.println("enter a ");
int a=sc.nextInt();
System.out.println("enter b ");
int b=sc.nextInt();
System.out.println("enter c ");
int c=sc.nextInt(); double
x=(a+(b*c))/(b-c);
System.out.println(x);
}
}

Program 3: Print table of a number taken from user


Soln:
CODE:
import java.util.*;
public class table {
public static void
main(String[]args){ Scanner sc=new
Scanner(System.in);
System.out.println("enter number ");
int num=sc.nextInt(); for(int
i=1;i<=10;i++){
System.out.println(num+"*"+i+"="+num*i);
}
}
}

Program 4: Convert rupees, taken as input, to paise


Soln:
CODE:
import java.util.*;
public class RsToPaise {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("enter amount in rupees: "); int
rs=sc.nextInt();
int paise=rs*100;
System.out.println("amount in paise: "+ paise);

}
}
Experiment 3: Conditional Statements
Program 1: Convert degree Celsius, taken as input, to degree Fahrenheit
Soln:
CODE:
import java.util.*;
public class CtoF {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("enter temp in Celcius
:"); float c=sc.nextFloat(); float
f=(c*(9/5))+32;
System.out.println("temp in Farheinheit :"+
f); }

Program 2: Take student’s information like name, roll number, marks, phone
number from user and print it.
Soln:
CODE:
import java.util.*;
public class studentinfo {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("enter name :");
String name=sc.next();
System.out.println("enter roll no.
:"); int roll=sc.nextInt();
System.out.println("marks :"); float
marks=sc.nextFloat();
System.out.println("enter phone no. :");
double phone=sc.nextDouble();
System.out.print("Details :"+"\n"+
"\n name :"+name+
"\n roll number :"+roll+
"\n marks :"+marks);
System.out.printf("\n phone number : %.0f\n", phone); }
}

Program 3: Input marks and print grade. 85-100:


A 70-85: B 60-70: C 50-60: D <50:FAIL
Soln:
CODE:
import java.util.*;
public class grade {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter english marks :"); float
eng=sc.nextFloat();
System.out.println("Enter physics marks :"); float
phy=sc.nextFloat();
System.out.println("Enter chem marks :"); float
chem=sc.nextFloat();
System.out.println("Enter math marks :"); float
math=sc.nextFloat();
float avg=(eng+phy+chem+math)/4;
if (85<=avg && avg<100){
System.out.println("A");
}else if (70<=avg && avg<85){
System.out.println("B");
}else if(60<=avg && avg<70){
System.out.println("C");
}else if(50<=avg && avg<60){
System.out.println("D");
}else{
System.out.println("FAIL");
}
}
}
Experiment 4: Loops and Conditional Statements
Program 1: Convert binary to decimal
Soln:
CODE:
import java.util.*;
public class binaryTOdecimal {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter binary number
"); int x=sc.nextInt(); double
decimalNumber=0, i=0; int remainder;
while(x!=0){ remainder=x%10; x=x/10;
decimalNumber=decimalNumber+(remainder*Math.pow(2,i)); i=i+1;
}System.out.println("decimal number :"+decimalNumber); }
}

Program 2: Find roots of quadratic equation


Soln:
CODE:
import java.lang.Math;
public class rootsOfQuadratic {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("enter coefficients a,b,c :"); int
a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
int dis=(b*b)-
(4*a*c); if(dis>0){
double r1=(-b+Math.sqrt(dis))/(2*a);
double r2=(-b-Math.sqrt(dis))/(2*a);
System.out.println("Roots are real and distinct :"+r1+" "+r2); }else
if(dis==0){
int r1=-b/(2*a), r2=-b/(2*a);
System.out.println("Roots are real and same :"+r1+" "+r2); }else{
int rpart=-b/(2*a);
double ipart=Math.sqrt(-dis)/(2*a);
System.out.println("Roots are complex and different :"+"real
part:"+rpart+" imaginary part:"+ipart);
}
}
}

Program 3: Find sum of series (1/x) + (1/x^2) +…. Till n terms


Soln:
CODE:
import java.util.*;
public class sumofseries {
public static void main(String[]args){
Scanner sc= new
Scanner(System.in);
System.out.println("enter n ");
int n=sc.nextInt();
System.out.println("enter x
"); int x=sc.nextInt(); double
sum=0; for (int i=1;i<=n;i++){
sum=sum+1/(Math.pow(x,i));
}System.out.println("Sum of series : "+ sum);
}
}
Experiment 5: Application Program
Program 1: Create a calendar, enter date to get its previous date, next date and
days.
Soln:
CODE:
import java.util.Scanner; class calendar{
int date; int month; int year; String
day; String[] arr
={"monday","tuesday","wednesday","thursday","friday","saturday","sunday"}
; public calendar(int d, int m, int y){
this.date=d; this.month=m; this.year=y;
}public boolean check(){
if(date>31 || month>12){
return true;
}else if(date>28 && month==2 &&
year%4!=0){ return true; }else{ return
false;
}
}public void nextdate(int d,int m,int
y){ this.date=d; this.month=m;
this.year=y; if(date==31 && month==12){
year++; date=1;month=1;
}else if(date==31 &&
(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
){ date=1; month++;
}else if(date==30 && (month==4||month==6||month==9||month==11)){ date=1;
month++;
}else if(date==28 &&
month==2){
if(year%4!=0){date++;} else{
date=1; month++;}
}else if(date==29 && month==2 && year%4==0){
date=1; month++;
}else{ date++;
}System.out.println("Next date is "+date+"/"+month+"/"+year); }public
void prevdate(int d, int m, int y){
this.date=d; this.month=m;
this.year=y; if(date==1 && month==1){
date=31; month=12; year--;
}else if(date==1 &&
(month==2||month==4||month==6||month==8||month==9||month==11)){
date=31; month --;
}else if(date==1 && (month==5||month==7||month==10||month==12)){
date=30; month--;
}else if(date==1 && month==3){
month--;
if (year%4==0){date=29;}
else{ date=28;}
}else{date--;}
System.out.println("Previous date is "+date+"/"+month+"/"+year);
} public void daynp(String day){ this.day=day;
for(int i=0;i<7;i++){
if(arr[i].equals(day)){
if(i==0){
System.out.println("Next day is "+arr[i+1]);
System.out.println("Previous day was "+arr[6]); }else if(i==6){
System.out.println("Next day is "+arr[0]);
System.out.println("Previous day was "+arr[i-1]); }else{
System.out.println("Next day is "+arr[i+1]);
System.out.println("Previous day was "+arr[i-1]); }break;
}
}
}
} public class
CALENDER {
public static void
main(String[]args){ Scanner sc= new
Scanner(System.in);
System.out.println("enter date ");
int d=sc.nextInt();
System.out.println("enter month ");
int m=sc.nextInt();
System.out.println("enter year ");
int y=sc.nextInt();
System.out.println("enter day ");
String day=sc.next();

calendar c=new calendar(d,m,y);


if(c.check()){
System.out.println("invalid date");
}else{
c.nextdate(d,m,y);
c.prevdate(d,m,y);
c.daynp(day);
}
}
}
Program 2: Use 2D array to print matrix, perform addition and multiplication
on it with another matrix
Soln:
CODE:
public class matrix2darray { public
static void main(String[]args){ int
mat[][]={{1,2},{4,5}}; int
mat2[][]={{2,3},{4,5}}; for (int
i=0;i<mat.length;i++){ for(int
j=0;j<mat[0].length;j++){
System.out.print(mat[i][j]+" ");
}System.out.println();
}
for (int i=0;i<mat2.length;i++) { for
(int j = 0; j < mat2[0].length; j++) {
System.out.print(mat2[i][j] + " ");
}System.out.println();
}
System.out.println("sum of matrices:");
for (int i=0;i<mat.length;i++) { for
(int j = 0; j < mat[0].length; j++){
System.out.print((mat2[i][j]+mat[i][j]) + " ");
}System.out.println();
}System.out.println("product of matrices:"); int
prod[][]=new int[mat.length][mat[0].length]; for (int
i=0;i<mat.length; i++){
for (int j=0;j< mat[0].length;j++){ for (int
k=0; k<mat.length; k++){
prod[i][j]=prod[i][j]+mat[i][k]*mat2[k][j]; }
}
}for (int i=0; i<mat.length; i++){
for (int j=0; j<mat[0].length; j++){
System.out.print(prod[i][j]+" ");
}System.out.println();
}
}
}

Experiment 6: Calculator

Program 1: Create calculator.


Soln:
CODE:
import java.util.*;
public class calc {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("enter first number ");
float a=sc.nextFloat();
System.out.println("enter second number ");
float b=sc.nextFloat();
System.out.println("enter operator
"); String c=sc.next();
if(c.equals("+")){
System.out.println(a+b);
}else if(c.equals("-")){
System.out.println(a-b);
}else if(c.equals("*")){
System.out.println(a*b);
}else if(c.equals("/")){
System.out.println(a/b);
}else{
System.out.println("enter a valid operator"); }
}
}

Program 2: Create calculator using switch


Soln:
CODE:
import java.util.*;
public class calcUsingSwitch {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("enter first number ");
float a=sc.nextFloat();
System.out.println("enter second number ");
float b=sc.nextFloat();
System.out.println("enter operator
"); char
operator=sc.next().charAt(0); double
result; switch(operator){ case '+':
result=a+b; break; case '-':
result=a-b; break; case '*':
result=a*b; break; case '/':
result=a/b; break; default:
System.out.println("invalid operator"); return;
}System.out.println(a+" "+operator+" "+b+"="+result); }
}
Experiment 7: Introduction to Classes
Program 1: Create base class distance, give private parameter d1. Create
constructors for add, subtract and print. Two derived classes Dinch( convert d1
to inches) Dmiles( convert d1 to miles), give them same constructors. Use
override to print and add.
Soln:
CODE:
import java.util.Scanner;
class distance{
private double d1, d2;
distance(){
d1=0; d2=0;
}
void read(double d1, double d2){
this.d1=d1;
this.d2=d2;
}
void print(){
System.out.println("Distance 1 in meters: "+d1);
System.out.println("Distance 2 in meters: "+d2); }
void add(){
System.out.println("Sum of two distances in meters= "+(d1+d2)); }
} class Dinch extends
distance{
double d3,
d4; Dinch(){
d3=0; d4=0;
}
void read(double d1, double d2){
super.read(d1,d2);
d3=d1*39.3701; d4=d2*39.3701;
}
void print(double d1, double d2){
System.out.println("Distance 1 in inches: "+d3);
System.out.println("Distance 2 in inches: "+d4); }
void add(double d1, double d2){
System.out.println("Sum of two distances in inches= "+(d3+d4)); }
} class Dmiles extends
distance{
double d5,
d6; Dmiles(){
d5=0; d6=0;
}
void read(double d1, double d2){
super.read(d1,d2);
d5=d1*0.000621; d6=d2*0.000621;
}
void print(double d1, double d2){
System.out.println("Distance 1 in miles: "+d5);
System.out.println("Distance 2 in miles: "+d6);
}
void add(double d1, double d2){
System.out.println("Sum of two distances in miles= "+(d5+d6)); }
} public class
convertdistance {
public static void main(String[]
args){ Scanner sc= new
Scanner(System.in); distance dist=new
distance(); Dinch dist1= new Dinch();
Dmiles dist2=new Dmiles();
System.out.print("Enter distance 1 in meters: "); double
a=sc.nextDouble();
System.out.print("Enter distance 2 in meters: "); double
b=sc.nextDouble();

dist.read(a,b);
dist.print();
dist.add();

dist1.read(a,b);
dist1.print(a,b);
dist1.add(a,b);
dist2.read(a,b);
dist2.print(a,b);
dist2.add(a,b);
}
}

Program 2:Create an employee class with private members name address age
gender taken as input, use constructor to initialize values to the variable, display
all. Derive employee class into full time employee, with members salary and
designation (display all) and part time employee with members work hour and
rate per hour from which pay can be calculated (work hour * rate per hour),
display pay.
Soln:
CODE:
import java.util.*;
class emp {
private String name;
private int age;
private String gender;
private String
address;
emp(){
Scanner sc=new Scanner(System.in);
System.out.println("Enter name: "); name=sc.next();
System.out.println("Enter age: "); age=sc.nextInt();
System.out.println("Enter gender: "); gender=sc.next();
System.out.println("Enter address: "); address=sc.next(); }void
print(){
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("Gender: "+gender);
System.out.println("Address: "+address);
}
}class fullTime extends
emp{ private String desig;
private int salary;
fullTime(){
Scanner ab=new Scanner(System.in);
System.out.println("Desig: "); desig=ab.next();
System.out.println("Salary: "); salary=ab.nextInt();
this.desig=desig; this.salary=salary;
}void print(){
super.print();
System.out.println("designation: "+desig);
System.out.println("salary: "+salary);
}
}class partTime extends emp{
private int workingHours;
private int rateOfWorking;
partTime(){
Scanner bc=new Scanner(System.in);
System.out.println("Working Hours: "); workingHours=bc.nextInt();
System.out.println("Rate per Hour: "); rateOfWorking=bc.nextInt(); }void
print(){
super.print();
int salary=workingHours*rateOfWorking;
System.out.println("salary: "+salary);
}
}public class Employee{ public static
void main(String[]args){
Scanner a=new Scanner(System.in);
System.out.println("Enter number of employees: "); int
n=a.nextInt();
System.out.println("Enter 1 for full time and 0 for part time: "); int
t=a.nextInt();
emp[] e=new emp[n]; for (int
i=0;i<n;i++){ if(t==1) {
e[i]=new fullTime(); } else {
e[i]=new partTime(); } }for(int
i=0;i<n;i++){ e[i].print(); }}

Program 3:Create abstract class Shapes. Derive circle triangle rectangle from
shapes. Use abstract method area with different definition in derived class.
Create object of type circle triangle rectangle and print their area.
Soln:
CODE:
import java.util.*;
abstract class Shape{
int length, breadth, radius;
Scanner sc= new
Scanner(System.in); abstract void
Area();
} class Circle extends
Shape{
void Area(){
System.out.println("\n Calculating area of circle");
System.out.print("Enter radius of circle");
radius=sc.nextInt();
System.out.println("The area of circle is:
"+(3.14f*radius*radius));
}
} class Triangle extends
Shape{
void Area(){
System.out.println("\n Calculating area of triangle");
System.out.print("Enter base of triangle");
breadth=sc.nextInt();
System.out.print("Enter height of triangle");
length=sc.nextInt();
System.out.println("The area of triangle is:
"+(0.5*breadth*length));
}
} class Rectangle extends
Shape{
void Area(){
System.out.println("\n Calculating area of rectangle");
System.out.print("Enter width of rectangle");
breadth=sc.nextInt();
System.out.print("Enter length of rectangle");
length=sc.nextInt();
System.out.println("The area of rectangle is:
"+(breadth*length)); }
} public class
abstractShapes {
public static void main(String[]
args){ Circle c=new Circle();
c.Area();
Triangle t= new Triangle();
t.Area();
Rectangle r= new Rectangle();
r.Area();
}
}
Program 4:Create class vehicles with members color type weight and read()
print(). Derive it into two classes, Car with members model engine number of
seats and read() print(), Bike with members engine tyre and read() print().
Soln:
CODE:
import
java.util.Scanner; class
Vehicle{ String color,
type; double weight;
void read(String color, String type, double weight){
this.color=color;
this.type=type;
this.weight=weight;
}
void print(){
System.out.println("Color of the vehicle: "+color);
System.out.println("Type of the vehicle: "+type);
System.out.println("Weight of the vehicle: "+weight); }
} class Car extends Vehicle{ String cType, cEngine,cColor; int
seats; void readc(String cColor,String cType, String cEngine, int
seats){
this.cColor=cColor;
this.cType=cType;
this.cEngine=cEngine;
this.seats=seats;
}
void printc(){
System.out.println("Color of the car: "+cColor);
System.out.println("Type of the car: "+cType);
System.out.println("Engine of the car: "+cEngine);
System.out.println("Number of seats in the car: "+seats); }
}
class Bike extends
Vehicle{ String bEngine,
bColor; int tyres;
void readb(String bColor, String bEngine, int tyres){
this.bColor=bColor;
this.bEngine=bEngine;
this.tyres=tyres;
} void
printb(){
System.out.println("Color of the bike: "+bColor);
System.out.println("Engine of the bike: "+bEngine);
System.out.println("Number of tyres: "+tyres); }
} public class
vehicleCB{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
Vehicle v=new Vehicle();
System.out.println("Enter the details of the vehicle: ");
System.out.print("Color: ");
String color=sc.next();
System.out.print("Type: ");
String type=sc.next();
System.out.print("Weight: ");
double weight=sc.nextDouble();
v.read(color,type,weight);
System.out.println("Details of the vehicle are: ");
v.print();
if(weight>100){
Car c=new Car();
System.out.println("Enter the details of car: ");
System.out.print("Car type: ");
String cType=sc.next();
System.out.print("Car engine: ");
String cEngine=sc.next();
System.out.print("Number of seats: "); int
seats=sc.nextInt();
c.readc(color,cType,cEngine,seats);
System.out.println("Details of the car are: "); c.printc();
}else{
Bike b=new Bike();
System.out.println("Enter the details of bike: ");
System.out.print("Bike engine: ");
String bEngine=sc.next();
System.out.print("Number of tyres: ");
int tyres=sc.nextInt();
b.readb(color,bEngine,tyres);
System.out.println("Details of the bike are: "); b.printb();
}
}
}
Experiment 8: Inheritance
Program 1:Create class addTime that can add two times in hours, minutes,
seconds.
Soln:
CODE:
import java.util.*;
public class addTime {
public static void
main(String[]args){ Scanner sc=new
Scanner(System.in);
System.out.print("enter hours "); int
HR=sc.nextInt();
System.out.print("enter minutes ");
int MIN=sc.nextInt();
System.out.print("enter seconds ");
int SEC=sc.nextInt();
System.out.print("enter hours ");
int HR2=sc.nextInt();
System.out.print("enter minutes ");
int MIN2=sc.nextInt();
System.out.print("enter seconds
"); int SEC2=sc.nextInt(); int
a=HR+HR2; int b=MIN+MIN2; int
c=SEC+SEC2; int Hour=a+(b/60); int
Min=b+(c/60); int Sec= c%60; int
Mins=Min%60;
System.out.println(Hour+":"+Mins+":"+Sec);
}
}

Program 2:Create a base class account having acc number, acc type, name of
holder, read(), print().Derive this class into savings and current acc class where
savings acc has interest rate 10%, update balance; and current acc has
maximum number of transactions. If number of transactions >30, deduct 1500
Soln:
CODE:
import java.util.Scanner;
class bank{
int Acc_No;
String
Acc_type;
String Name;
void Welcome(){
System.out.println("Welcome to XYZ Bank");}
void print(String Name){
System.out.println("Have a nice day "+Name);
}
void read(String Name, String Acc_Type){
this.Name=Name;
this.Acc_type=Acc_type;
}
} class Current extends
bank{
double Acc_balance; int no_of_transactions; void
read(int no_of_transactions){
this.no_of_transactions=no_of_transactions; } void
read1(double d){
this.Acc_balance=d; }
void accBal(){
if(no_of_transactions>30){
Acc_balance=Acc_balance-1500.0;}
System.out.println("Your balance in Current Account is:
"+Acc_balance);
}
} class Savings extends
bank{
double
Acc_balance; int
rate; void
read(int d){
this.rate=d; }
void read1(double d){
this.Acc_balance=d; }
void accBal(){
Acc_balance=Acc_balance*1.10;
System.out.println("Your balance in Savings Account is
"+Acc_balance);
}
} public class
accounts {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
bank a= new bank();
Savings s= new Savings();
Current c= new Current();
s.Welcome();
System.out.print("Enter your name: ");
String Name=sc.next();
System.out.print("Enter account number: "); int
Acc_no=sc.nextInt();
System.out.print("Enter account type: (Savings/Current) "); String
Acc_type=sc.next();
System.out.println("Account Number: "+Acc_no);
if(Acc_type=="Current"){
c.read(31);
c.read1(1500.50);
c.accBal();
}else{
s.read(15);
s.read1(1000.67);
s.accBal();
}
a.print(Name);
}
}
Program 3:Create a class to read and print details of students. Also create
function to get average, minimum and maximum marks.
Soln:
CODE:
import java.util.*;
class students {
Scanner sc = new Scanner(System.in);
int eng; int phy; int chem; int math;
int marks[] = new int[4];
String name; String fname;
students(String name){
this.name = name; }
public void
readDetails(){
System.out.println("enter fathers name ");
this.fname = sc.next();
System.out.println("enter marks in
eng"); this.eng = sc.nextInt(); marks[0]
= this.eng;
System.out.println("enter marks in
phy"); this.phy = sc.nextInt(); marks[1]
= this.phy;
System.out.println("enter marks in
chem"); this.chem = sc.nextInt();
marks[2] = this.chem;
System.out.println("enter marks in
math"); this.math = sc.nextInt();
marks[3] = this.math; } public void
printDetails(){
System.out.println("Name: " + name);
System.out.println("Fathers name: " + fname);
System.out.println("marks: ");
System.out.println("eng: " + eng);
System.out.println("hindi: " + phy);
System.out.println("maths: " + chem);
System.out.println("sst: " + math);
} public int avg(){ int av = (eng +
phy + chem + math)/4;
return av;
}
public int maximum() {
int m = marks[0];
for(int i = 0; i<4;
i++){ if(marks[i]>m){ m
= marks[i];
}
}return m;
}
public int minimum() {
int m = marks[0];
for(int i = 0; i<4; i++){
if(marks[i]<m){
m = marks[i]; } }
return m; } }
public class marksavgminmax {
public static void main(String[] args) {
students s1 = new students("XYZ");
s1.readDetails(); s1.printDetails();
int max1 = s1.maximum(); int min1 = s1.minimum(); int avg1 = s1.avg();
System.out.println("max: " + max1);
System.out.println("min: " + min1);
System.out.println("avg: " + avg1);
} }

Experiment 9: Interfaces
Program 1:Design an interface with a method reverse that reverses the digits of
a number.
Soln:
CODE:
import java.util.*;
interface number{
int reverse(int x);
}class reverseNum implements
number{ public int reverse(int x){
int y=0; while (x!=0){ int r=x%10;
y=(y*10)+r; x=x/10;
}return y;
}public static void main(String[]args){
Scanner sc= new Scanner(System.in);
System.out.println("enter number");
int x=sc.nextInt();
System.out.println("reversed number");
reverseNum obj= new reverseNum();
System.out.println(obj.reverse(x));
}
Program 2:Design an interface having method to get velocity with parameter r
that calculates and returns velocity of a satellite given by the formula
velocity=root mu/r where r is the altitude of satellite taken from the earth and
mu is Kepler’s constant with value 3.986004418* (10**5). Create a nested
interface with a method to get acceleration with parameter r that calculates and
returns the acceleration of the satellite given by the formula mu/(r**2)
Soln:
CODE:
import java.util.*;
interface v{ float
velocity(float r);
interface a{
float acceleration(float r);
}} class va implements
v,v.a {
public float velocity(float r) { double mu =
3.986004418 * Math.pow(10, 5); float velocity =
(float) Math.pow((mu / r), 0.5);
return velocity;
}

public float acceleration(float r) { double mu =


3.986004418 * Math.pow(10, 5); float acceleration =
(float) (mu / Math.pow(r, 2)); return
acceleration;
}
} public class
satellite {
public static void main(String[]args){
Scanner sc= new Scanner(System.in);
System.out.println("enter altitude ");
float r=sc.nextFloat();
va obj= new va();
System.out.println("velocity="+obj.velocity(r));
System.out.println("acceleration="+obj.acceleration(r)); }
}

Program 3:Write a program having a mean interface. Create a method mean


that calculates the mean of user entered numbers arranged in an array. Extend
the interface having method deviation that calculates the (absolute) deviation
from the mean value for each of the numbers in the array.
Soln:
CODE:
import java.util.*;
interface meanInterface{
int mean(int []arr,int n);
} interface deviation extends
meanInterface{
void deviation(int []arr,int n);
} class Math1 implements
deviation{
public int mean(int []arr,int n) {
int sum=0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
int mean = sum / n;
return mean;
}
public void deviation(int []arr,int
n){ int m = mean(arr,n); for(int
i=0;i<n;i++){ int stdv = arr[i]-m;
System.out.println("Deviation of "+(i+1)+"element from mean: "+ stdv+" ");
}
}
} public class
MeanDev {
public static void main(String[] args)
{ Scanner sc = new Scanner(System.in);
int []arr = new int[1000];
System.out.print("Enter number of elements :");
int n = sc.nextInt();
for(int i=0;i<n;i++){
System.out.print("Enter " +(i+1)+" element: ");
arr[i]=sc.nextInt();
}
Math1 s1 = new Math1();
System.out.println("Mean= "+s1.mean(arr,n));
s1.deviation(arr,n);
}
}

Program 4:Write a program in which three interfaces I1 I2 I3 are defined, I2


extends I1, I3 extends I1 and I2. I1 declares a method withdraw, I2 declares a
method deposit, I3 declares display that shows balance of account number.
Create a class with var account number, name, address, balance that implements
the interfaces
Soln:
CODE:
import java.util.*;
interface I1{
void withdraw( float withdrawn_amt );
}interface I2 extends I1{ void
deposit( float money_deposit );
}interface I3 extends I1,I2{
void display( float acc_bal );
} class account implements
I3{
double acc_no; float acc_bal; String name,address;
account(){
Scanner sc=new Scanner(System.in);
System.out.println("enter name: ");
name=sc.next();
System.out.println("enter address: ");
address=sc.next();
System.out.println("enter 12 digit account number: ");
acc_no=sc.nextDouble();
acc_bal=30000; // amount initiliaised by bank
}
public void withdraw(float withdrawn_amt){
if (withdrawn_amt< acc_bal) {
System.out.println("amount withdrawn= "+withdrawn_amt); acc_bal=acc_bal-
withdrawn_amt; System.out.println("updated balance= "+acc_bal); }else{
System.out.println("insufficient balance "); }
}public void deposit(float money_deposit){
System.out.println("amount deposited= "+money_deposit);
acc_bal=acc_bal+money_deposit;
System.out.println("updated balance= "+acc_bal); }public
void display(float acc_bal){
System.out.println("account balance= "+acc_bal); }public
void function(){
Scanner sc=new Scanner(System.in);
System.out.println("Enter W- to withdraw DE- to deposit DI- to display
balance");
String choice=sc.nextLine();
switch(choice){
case "W": { System.out.println("Enter amount to withdraw: "); float
withdrawn_amt=sc.nextFloat();
withdraw(withdrawn_amt);
break;}
case "DE": { System.out.println("Enter amount to deposit: "); float
deposit_amt=sc.nextFloat();
deposit(deposit_amt);
break;}
case "DI": { System.out.println("Amount: "+ acc_bal); break;}
default: { System.out.println("Invalid input");
System.out.println("Try again");
function();
}
}
}
} class bankBalance extends account{
public static void main(String[]
args){ Scanner sc= new
Scanner(System.in); account a1=new
account();
a1.function();
System.out.println("Do you want to do the transaction again? ");
System.out.println("Enter 1 for Yes, 0 for No"); int
choose=sc.nextInt(); if(choose==1){ a1.function();
} else if(choose==0){
System.out.println("Have a nice day!");
} else{
System.out.println("Wrong input");
}
}
}

Experiment 10: File Handling-1

Program 1:Write a program that calculates area of a room and the cost of white
washing, include provision for window on any of the walls. The parameters for
the room length height width are taken from the user. If there is a window then
its length and width are taken from the user. In any case of parameter, if input is
less than 1 then throw an invalid dimension exception; otherwise calculate and
display area and cost of white washing
Soln:
CODE:

import java.util.*; import


java.lang.Exception; class
MyException extends Exception{
public MyException(String message){
super(message);
}
} class
Dimensions {
double length, width, height, area;
double w_length=0.0, w_width=0.0;
Scanner sc=new Scanner(System.in);
Dimensions(){
System.out.println("Enter dimensions of the room: ");
System.out.println("Length: ");
length=sc.nextFloat();
System.out.println("Width: ");
width=sc.nextFloat();
System.out.println("Height: ");
height=sc.nextFloat();
}
public void WindowDimension() {
System.out.println("Enter length of window: ");
w_length = sc.nextFloat();
try {
if (w_length < 1 || w_length > height){
throw new MyException("invalid length"); }
} catch (MyException exl) {
System.out.println(exl.getMessage());
WindowDimension();
}
System.out.println("Enter width of window: ");
w_width = sc.nextFloat();
try {
if (w_width < 1 || w_width > width){
throw new MyException("invalid width");
}
} catch (MyException exw) {
System.out.println(exw.getMessage());
WindowDimension();
}
}
public double area(){
area=(length*width)+(2*(length*height))+(2*(width*height))(w_length*w_w
idth);
System.out.println("Enter rate of whitewashing: "); double
rate=sc.nextFloat();
double cost=area*rate;
System.out.println("Cost of whitewashing: ");
return cost;
}
} public class
whitewashing {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
Dimensions dim= new Dimensions();
System.out.println("Does your room have windows? (1 for Yes/0 for No)
"); int choice=sc.nextInt(); if (choice==1){ dim.WindowDimension();
}System.out.println("Rs. "+dim.area());
}
}

Program 2:Write a program that reads data for name class roll number marks
of a student and print them to a file. Also read details from the file and show on
the monitor
Soln:
CODE:

import java.io.*;
public class studentFile {
public static void main(String args[]) throws IOException {
String name = "XYZ";
String cLaSs="XA";
double roll =
1234567; int
marks=80; try {
FileWriter output = new FileWriter("src/student.txt");
output.write(name+" "+cLaSs+" "+roll+" "+marks);
System.out.println("Data is written to the file."); output.close();
}
catch (Exception e) {
e.getStackTrace();
}
File fileName = new File("src/student.txt");
FileInputStream inFile = new FileInputStream("src/student.txt");
int fileLength = (int) fileName.length(); byte Bytes[] = new
byte[fileLength];
System.out.println("File size is: " + inFile.read(Bytes)); String
file1 = new String(Bytes);
System.out.println("File content is:\n" + file1);
inFile.close();
}
}
Program 3:Write a program to copy contents of one file into another.
Soln:
CODE:
import java.io.*;
import java.util.*;
public class copyFilecontent {
public static void copyContent(File a, File b)
throws Exception {
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);
try {
int n;
while ((n = in.read()) != -1) {
out.write(n);
} } finally { if
(in != null) {
in.close();
} if (out !=
null) {
out.close();
}
}
System.out.println("File Copied");
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the source filename:"); String a
= sc.nextLine();
File x = new File(a);
System.out.println("Enter the destination filename:"); String b
= sc.nextLine(); File
y = new File(b);
copyContent(x, y);
}
}
Experiment 11: File Handling-2
Program 1:Write a program to check whether the contents in two files is same
or not.
Soln:
CODE:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class compareFiles {
public static void main(String[] args) throws IOException {
BufferedReader reader1 = new BufferedReader(new
FileReader("src/source.txt"));
BufferedReader reader2 = new BufferedReader(new
FileReader("src/destination.txt"));
String l1 = reader1.readLine();
String l2 = reader2.readLine();
boolean Equal = true; int lineNum
= 1; while (l1 != null || l2 !=
null) { if(l1 == null || l2 ==
null) { Equal = false; break;
}
else if(! l1.equalsIgnoreCase(l2)) {
Equal = false;
break;
}
l1 = reader1.readLine();
l2 = reader2.readLine();
lineNum++;
}
if(Equal) {
System.out.println("Two files have same content."); }
else {
System.out.println("Two files have different content. They differ at
line "+lineNum);
System.out.println("File1 has "+l1+" and File2 has "+l2+" at line
"+lineNum);
}
reader1.close();
reader2.close();
}
Program 2:Write a program to count the number of digits stored in the file
Soln:
CODE:
import java.io.*; import
java.util.Scanner;
public class integersINfile{
public static void main (String[] args)throws FileNotFoundException {
Scanner reader = new Scanner(new File("src/integers.txt")); int count=0;
while (reader.hasNextInt()) {
count++;
reader.nextInt();
}
System.out.println("The file had " + count + " number(s)"); }
}
}

Program 3:Write a program to write a string character by character to a file and


read the string character by character from the file, print it on the screen.
Soln:
CODE:
import java.io.*; import
java.io.FileReader;
import
java.io.FileWriter; class
fileCharByChar{
public static void main(String[] args) throws IOException {
String s="OOPS using Java";
FileWriter fw=new
FileWriter("src/file1.txt"); for(int i=0;
i<s.length(); i++) fw.write(s.charAt(i));
fw.close();
FileReader fin=new FileReader("src/file1.txt");
for(int i=0; i<s.length(); i++)
System.out.println((char)fin.read());
fin.close();
}
}

Program 4: Read the data from the keyboard using buffered reader class.
Soln:
CODE:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class readwBuffered {
public static void main(String[] args) throws Exception{ char
ch;
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("enter some characters:
"); for(int i=0; i<5; i++){
ch=(char)din.read();
System.out.println(ch);
}din.close();
}
}
Experiment 12: Application Program

Program 41: Create class with members name, roll number, stream, marks,
write it in a file for 10 student such that when you enter roll number, only the
details of that student are printed.

Soln:
CODE:

import java.io.*; import java.util.*;

class Student1 implements Serializable{

private int roll_no; private String name;

private int marks;

Student1(){

Scanner sc = new Scanner(System.in);

roll_no = sc.nextInt(); name =

sc.next();

marks = sc.nextInt(); }

int getRoll_no(){

return roll_no; } String

getName(){ return

name; } int

getMarks(){ return

marks; } } public class

lastQ { public static

void main(String[]
args) throws

Exception{ Scanner sc

= new

Scanner(System.in);

File f = new File("myFile.ser");

FileOutputStream fos = new FileOutputStream(f);


ObjectOutputStream oos = new ObjectOutputStream(fos);
for(int i=0; i<2; i++) { Student1 s1 = new Student1();
oos.writeObject(s1); } oos.close(); fos.close();

FileInputStream fis = new FileInputStream("myFile.ser");


ObjectInputStream ois = new ObjectInputStream(fis); int x
= sc.nextInt(); for(int
i=0; i<2; i++){

Student1 s = (Student1) ois.readObject(); if(s.getRoll_no()==x)

System.out.println("roll number: " + s.getRoll_no());


System.out.println("name: " + s.getName());
System.out.println("marks: " + s.getMarks()); break;
}
ois.close();
fis.close();
}

You might also like