100% found this document useful (3 votes)
2K views

Java Lab Record

This document contains a lab record submitted by a student named Shubham Choudhary for their Java assignments. It includes an index listing 22 assignments completed from February to May on various Java topics like data types, operators, loops, arrays, inheritance, exceptions and file I/O. Each assignment contains sample code demonstrating the concepts covered.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
2K views

Java Lab Record

This document contains a lab record submitted by a student named Shubham Choudhary for their Java assignments. It includes an index listing 22 assignments completed from February to May on various Java topics like data types, operators, loops, arrays, inheritance, exceptions and file I/O. Each assignment contains sample code demonstrating the concepts covered.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 193

JAVA LAB Record

Submitted by: Submitted to:


Name: Shubham Choudhary Mr. Utpal De
Roll:2070045 &
Section-A Mr. Lalat keshari Kundu
INDEX
SL.NO DATE ASSIGNMENTS PAGE REMARKS

2 11/02/2021 Data type 3-11


3 18/02/2021 Operator 12-17
4 22/02/2021 Bitwise Operator 18-25
5 25/02/2021 IfElse-switchcase 26-46
6 27/02/2021 Loop 47-61
7 1/03/2021 Series 62-70
8 8/03/2021 Constructor 71-76
9 15/03/2021 Array 77-82
10 18/03/2021 Sorting 83-87
11 5/04/2021 MD-Array 88-94
12 8/04/2021 Jagged Array 95-98
13 15/04/2021 Static Method 99-108
14 15/04/2021 String 109-118
15 19/04/2021 Inheritance 119-127
16 26/04/2021 Inheritance 128-141
17 26/04/2021 Abstract 142-148
18 26/04/2021 Interface 149-158
19 29/04/2021 Package 159_169
20 6/05/2021 Built-in-Exception 170-172
21 6/05/2021 User-defind-Exception 173-191
22 17/05/2021 File read & write 192-193
ASSIGNMENT-2(DATATYPE)
Q1. The basic salary of an employee is 12000. WAP in JAVA to
compute gross and net salary of that employee where
HRA=15%, and DA=110%, PF=12%.
Source Code:
class a
{
public static void main(String k[])
{

int bs=12000;
double da,hra,pf,gp,np;
da=1.10*bs; hra=0.15*bs;
pf=0.12*bs; gp=bs+da+hra;
np=gp-pf;
System.out.println("Gross salary=Rs." +gp);
System.out.println("Net salary=Rs." +np);
}
}
Q2. Define a class CalcInt. Declare variables required to
calculate simple interest. Also define methods:
a) to set principal, time and rate of interest.
b) to calculate simple interest.
c) to display the loan details.
Try to modify the above program by making the method
private that is used to calculate simple interest.
Source Code:
import java.util.Scanner; class
CalcInt
{

static int p,r,t;


static float si;
private static void input()
{
Scanner s=new Scanner(System.in); System.out.println("Enter
the value of principal="); p=s.nextInt();
System.out.println("Enter the rate of interest="); r=s.nextInt();
System.out.println("Enter the amount of time=");
t=s.nextInt();
}
private static void calc(int p,int r,int t)
{
si=p*r*t;
si=si/100;
}
private static void output(float si,int p)
{
System.out.println("Simple Interest=" +si);
System.out.println("Loan Amout=" +(si+p));
}
public static void main(String k[])
{
input();
calc(p,r,t);
output(si,p);
}
}
Q3. WAP in Java to define variables to store your name,
current age, previous age and next age. Define following
methods :
a) To set your name and current age.
b) That can calculate and set your new age after the years
that is equal to last digit of your current age.
c) That can calculate and set your new age before the years
that is equal to first digit of your current age.
d) To show your name along with current, previous and
next age.
Source Code:
import java.util.Scanner; class
a
{

public static int age,n,q,m,h; public


static String l;
public static void input()
{

Scanner s=new Scanner(System.in);


System.out.println("Enter the name:"); l=s.next();
System.out.println("Enter current age:");
q=age=n=s.nextInt();
}
public static void after()
{

int j; j=age%10;
m=age+j;
}

public static void before()


{

int f=0,t=n; while(n>10)


{

n=n/10; f=n;
}

h=t-f;
}

public static void show()


{

System.out.println("Current age is are:" +q);


System.out.println("Age after is:" +m);
System.out.println("Age before is:" +h);
}

public static void main(String k[])


{
input();
after();
before();
show();
}
}
Q4.WAP to design a class AreaOfShapes. Define
variables for all the shapes given below. Define
separate methods for different figures.
Each method should do the following tasks-
a) set required data, b) calculate area of a shape and
c) display the details of that shape.
The geometric shapes are- a) circle, b) triangle, c)
rectangle.
Source Code:
import java.util.Scanner; class
Areaofshapes
{

void circle(int r)
{
System.out.println("Area of circle=" +(3.14*r*r));
}
void triangle(int b,int h)
{
System.out.println("Area of triangle=" +(0.5*b*h));
}
void rectangle(int l,int w)
{
System.out.println("Area of rectangle=" +(l*w));
}
public static void main(String k[])
{
int r,b,h,l,w;
Scanner s=new Scanner(System.in); System.out.println("Enter
the radius of circle="); r=s.nextInt();
System.out.println("Enter the Base and Height of triangle=");
b=s.nextInt(); h=s.nextInt();
System.out.println("Enter the length and width of
rectangle=");
l=s.nextInt(); w=s.nextInt();
Areaofshapes obj=new Areaofshapes();
obj.circle(r);
obj.triangle(b,h);
obj.rectangle(l,w);
}
}
ASSIGNMNET-3(OPERATOR)

Q1. Convert the temperature readings given in degree


Fahrenheit to degreeCelsius, using the following formula : C = (5/9) * (F - 32) Test these
values in degree Fahrenheit using CMD: 68, 150, 212, 0, -22, -200.

Source Code:

import java.util.Scanner; class a

public static void main(String k[])

double f,c;

Scanner s=new Scanner(System.in); System.out.println("Enter the Fahrenheit

temperature="); f=s.nextDouble();

c=((5/9.0)*(f-32.0));

System.out.println("Converted temperature in Celsius=" +c);

}
Q2.Calculate the volume and surface area of a sphere using the
following formula: V= 4/3 πr3 A = 4 πr2 π=3.14159 Test the program using
CMD for the given radius: 1, 6, 12.2,0.2.
Source Code:

import java.util.Scanner; class a

public static void main(String k[])

double v,a,r; double

pi=3.14159;

Scanner s=new Scanner(System.in); System.out.println("Enter the

radius of sphere="); r=s.nextDouble();

v=(4/3)*pi*r*r*r;

a=4*pi*r*r;

System.out.println("Volume of sphere=" +v);

System.out.println("Surface area of sphere=" +a);

}
Q3. WAP in JAVA to find the smaller and greater number among
two numbers read from CMD using ternary operator.

Source Code:

import java.util.Scanner; class

public static void main(String k[])

Scanner s=new Scanner(System.in); int a,b,c;

System.out.println("Enter 1st number="); a=s.nextInt();

System.out.println("Enter 2nd number="); b=s.nextInt();

c=a>b?a:b;

System.out.println("Greatest number=" +c); if(c==a)

System.out.println("Smallest number=" +b); else

System.out.println("Smallest number=" +a);

}
Q4.Write a program to show the use of ++, -- and different

assignment operators.
Source Code:

import java.util.Scanner; class a

public static void main(String m[])

int a,var,b,c,k,l;

Scanner s=new Scanner(System.in);

System.out.println("Enter a number:"); a=s.nextInt();

var=a;

System.out.println("var using =: " +var); var+=a;

System.out.println("var using +=: " + var); var-=a;

System.out.println("var using -=: " + var); var*=a;

System.out.println("var using *=: " + var); var/=a;

System.out.println("var using /=: " + var); var%=a;

System.out.println("var using %=: " + var);

System.out.println("Enter next number:");


b=s.nextInt();

System.out.println("Enter next number:"); c=s.nextInt();

k=++b;

l=--c;

System.out.println("var using ++: " +k);

System.out.println("var using --: " +l);

}
Q5.WAP to observe the difference between – and ~
operators.
Source Code:

import java.util.Scanner; class a

public static void main(String k[])

int a,b,c;

Scanner s=new Scanner(System.in);

System.out.println("Enter 1st number:"); a=s.nextInt();

System.out.println("Enter 2nd number:"); b=s.nextInt();

c=a-b;

System.out.println("a-b= " +c);

System.out.println("a~b= " +~c);

}
ASSIGNMENT_4(BITWISE OPERATOR)

Q1. Define two numbers v and n, where v is the


original number and n is the shifting value. Then shift the value of v to left (<<) and
right (>>) up to n bits and print the new values. Also use the >>> operator for right
shift and observe the difference between >> and

>>>.

Source Code:

import java.util.Scanner; class a

public int v,n; void

input()

Scanner s=new Scanner(System.in); System.out.println("Enter the original

number="); v=s.nextInt();

System.out.println("Enter the shifting value="); n=s.nextInt();

void leftshift()

System.out.println("Shifting left(<<)=" +(v<<n));

void rightshift()
{

System.out.println("Shifting right(>>)=" +(v>>n));

System.out.println("Shifting right(>>>)=" +(v>>>n));

public static void main(String k[])

a obj=new a();

obj.input();

obj.leftshift();

obj.rightshift();

}
Q2. Write a program to explain the use of (&, |, ^, ~)
bitwise operators in Java. Define two numbers num1 and num2. Then store the
result in num3 after using the operators given above. Print the value of num1,
num2 and num3 to check the result.

Source Code:

import java.util.Scanner; class a

public int num1,num2,num3; public void

input()

Scanner s=new Scanner(System.in);

System.out.println("Enter the num1="); num1=s.nextInt();

System.out.println("Enter the num2="); num2=s.nextInt();

public void output()

num3=num1&num2;

System.out.println(num1 + " & " +num2 +" = " +(num3)); num3=num1|num2;

System.out.println(num1 + " | " +num2 +" = " +(num3)); num3=num1^num2;


System.out.println(num1 + " ^ " +num2 +" = " +(num3));

num3=(~num1);

System.out.println(" ~ " +num1 +" = " +(num3)); num3=(~num2);

System.out.println(" ~ " +num2 +" = " +(num3));

public static void main(String k[])

a obj=new a();

obj.input();

obj.output();

}
Q3. Define two numbers and swap them without using

third variable.

a. Use the bitwise ^ operator and show the numbers after swapping.

Source Code:

import java.util.Scanner; class a

public int num1,num2; void

input()

Scanner s=new Scanner(System.in); System.out.println("Enter the

1st number="); num1=s.nextInt();

System.out.println("Enter the 2nd number="); num2=s.nextInt();

void output()

num1=num1^num2; num2=num1^num2;

num1=num1^num2; System.out.println("After

Swapping:");

System.out.println("1st number=" +num1);


System.out.println("2nd number" +num2);

public static void main(String k[])

a obj=new a();

obj.input();

obj.output();

}
b. Restore the numbers by using (+, -) operator and
show the numbers.

Source Code:

import java.util.Scanner; class a

public int num1,num2; void

input()

Scanner s=new Scanner(System.in); System.out.println("Enter the

1st number="); num1=s.nextInt();

System.out.println("Enter the 2nd number="); num2=s.nextInt();

void output()

num1=num1+num2;

num2=num1-num2;

num1=num1-num2;

System.out.println("After Swapping:"); System.out.println("1st

number=" +num1); System.out.println("2nd number=" +num2);

}
public static void main(String k[])

a obj=new a();

obj.input();

obj.output();

}
ASSIGNMENT-5(IfElse-SwitchCase)

Q1. WAP in JAVA to input basic salary and to compute


Gross salary of an employee if salary is less than 12000 the HRA=20%, and DA=115% of
Basic salary otherwise HRA=15% and DA=90% of Basic salary.

Source Code:
import java.util.Scanner; class a
{
public static void main(String k[])
{
Scanner s=new Scanner(System.in); double b,hra,da,g;
System.out.println("Enter basic salary of an employee=");
b=s.nextDouble(); if(b<12000)
{
hra=0.2*b;
da=1.15*b;
g=b+hra+da;
System.out.println("Gross Salary of an employee=Rs."
+g);
}
else
{

hra=0.15*b;
da=0.9*b;
g=b+hra+da;
System.out.println("Gross Salary of an employee=Rs."
+g);
}
}
}
Q2.WAP in JAVA to input an amount in Rs through
command line argument and find the number of 2000, 500, 200, 100, 50, 20, 10, 5, 2 and 1
Rs denominations will be needed to have that amount.
Source Code:
import java.util.Scanner; class a
{
public static void main(String k[])
{
Scanner s=new Scanner(System.in); int n,a,b,c,d,e,f,g,h,i,j;
a=b=c=d=e=f=g=h=i=j=0;
System.out.print("Enter amount in Rs."); n=s.nextInt();
if(n>=2000)
{
a=n/2000; System.out.println("Rs.2000=" +a); n-=a*2000;
} if(n>=500)
{
b=n/500; System.out.println("Rs.500=" +b);
n-=b*500;

} if(n>=200)
{
c=n/200; System.out.println("Rs.200=" +c); n-=c*200;
} if(n>=100)
{
d=n/100; System.out.println("Rs.100=" +d); n-=d*100;
}
if(n>=50)
{
e=n/50; System.out.println("Rs.50=" +e); n-=e*50;
}
if(n>=20)
{
f=n/20; System.out.println("Rs.20=" +f);
n-=f*20;

}
if(n>=10)
{
g=n/10; System.out.println("Rs.10=" +g); n-=g*10;
}
if(n>=5)
{
h=n/5; System.out.println("Rs.5=" +h); n-=h*5;
}
if(n>=2)
{
i=n/2; System.out.println("Rs.2=" +i); n-=i*2;
}
if(n>=1)
{
j=n/1; System.out.println("Rs.1=" +j);
n-=j*1;

}
}
}
Q3. Test the nature of the root of a quadraticequation
ax2+bx+c=0. The nature can be tested from the discriminant d=b2-4ac. The result can
be displayed from the Table-2 after finding d from the values given in Table-1.
Table-1

a B c Result(d)

2 6 1

2 -4 3

3 3 0

1 3 1

0 12 -3
Table-2

d<0 d=0 d>0


Root is imaginary. Roots are equal so ony one Rational and Rational but
root. Squared. Not squard.

Source Code:
import java.lang.*; class a
{
public static void main(String k[])
{
double a,b,c,d; a=2;b=6;c=1;d=0;
d=Math.pow(b,2);
d=(d-(4*a*c)); if(d>0)
{

System.out.println("Roots are squared!" +d);


}
else if(d==0)
{
System.out.println("Roots are equal so only one root!"
+d);
}
else
{
System.out.println("Rational and squared or Rational but not squared" +d);
}
a=2;b=-4;c=3;d=0;
d=Math.pow(b,2);
d=(d-(4*a*c)); if(d>0)
{
System.out.println("Roots are squared!" +d);
}
else if(d==0)
{
System.out.println("Roots are equal so only one root!"
+d);
}

else
{
System.out.println("Rational and squared or Rational but not squared" +d);
} a=3;b=3;c=0;d=0;
d=Math.pow(b,2);
d=(d-(4*a*c)); if(d>0)
{
System.out.println("Roots are squared!" +d);
}
else if(d==0)
{
System.out.println("Roots are equal so only one root!"
+d);
}
else
{
System.out.println("Rational and squared or Rational but not squared" +d);
} a=1;b=3;c=1;d=0;
d=Math.pow(b,2);

d=(d-(4*a*c)); if(d>0)
{
System.out.println("Roots are squared!" +d);
}
else if(d==0)
{
System.out.println("Roots are equal so only one root!"
+d);
}
else
{
System.out.println("Rational and squared or Rational but not squared" +d);
}
a=0;b=12;c=-3;d=0;
d=Math.pow(b,2);
d=(d-(4*a*c)); if(d>0)
{
System.out.println("Roots are squared!" +d);
}
else if(d==0)
{

System.out.println("Roots are equal so only one root!"


+d);
}
else
{
System.out.println("Rational and squared or Rational but not squared" +d);
}
}
}
Q4. Input 3 sides of a triangle and find out which type
of triangle is this.
Source Code:
import java.util.Scanner; class a
{
public static void main(String k[])
{
Scanner s=new Scanner(System.in); float a,b,c;
System.out.println("Enter 1st side of a triangle:"); a=s.nextFloat();
System.out.println("Enter 2nd side of a triangle:"); b=s.nextFloat();
System.out.println("Enter 3rd side of a triangle:"); c=s.nextFloat();
if(a==b && b==c)
{
System.out.println("Equilateral traingle!");
}
else if(a==b||b==c||a==c)
{
System.out.println("Isosceles traingle!");
}
else

{
System.out.println("Scalene traingle!");
}
}
}
Q5. Input Roll No, Name, and marks in five subjects.
Calculate total and percentage of marks using if-else-if. Calculate grade as follows :
>= 90% Grade O

>=80% Grade E

>=70% Grade A

>=60% Grade B

>=50% Grade C

>=40% Grade D
<40% Fail
Generate a Mark Sheet.
Source Code:
import java.util.Scanner; class a
{
public static void main(String l[])
{
Scanner s=new Scanner(System.in); int r,m,ss,p,h,e,t=0;
double per;
String k;
System.out.println("Enter roll no="); r=s.nextInt();
System.out.println("Enter your name:"); k=s.next();

System.out.println("Enter Math's Marks=");


m=s.nextInt();

System.out.println("Enter Science Marks="); ss=s.nextInt();


System.out.println("Enter Social Science Marks="); p=s.nextInt();
System.out.println("Enter English Marks="); e=s.nextInt();
System.out.println("Enter Hindi Marks="); h=s.nextInt();
t=m+ss+p+e+t; per=t/5.0;
System.out.println("Math's Marks=\t" +m); System.out.println("Science Marks=\t" +ss);
System.out.println("Social Science Marks=" +p); System.out.println("English Marks=\t" +e);
System.out.println("Hindi Marks=\t" +h); System.out.println("Total marks=\t" +t);
System.out.println("Percnetage=\t"+per+"%"); if(per>=90)
{
System.out.println("Grade O");
}
else if(per>=80)
{
System.out.println("Grade E");

}
else if(per>=70)
{
System.out.println("Grade A");
}
else if(per>=60)
{
System.out.println("Grade B");
}
else if(per>=50)
{
System.out.println("Grade C");
}
else if(per>=40)
{
System.out.println("Grade D");
}
else
{
System.out.println("FAIL");
}
}
}
Q6. Input two numbers and an operator(+, -, *, /) then
calculate the result according to the operator selected.
Source Code:
import java.util.Scanner; class a
{
public static void main(String k[])
{
Scanner s=new Scanner(System.in); double a,b,d=0;
char c;
System.out.println("Enter 1st number="); a=s.nextDouble();
System.out.println("Enter 2nd number="); b=s.nextDouble();
System.out.println("Enter an operator from(+,-,*,/):"); c=s.next().charAt(0);
switch(c)
{
case '+':
d=a+b;
break; case '-
': d=a-b;
break;

case '*':
d=a*b; break;
case '/':
d=a/b;
default:
System.out.println("Invalid Operator!");
}
System.out.println(a+" " +c +" " +b+ "=" +d);
}
}
Q7.Input a number and display it in words. Ex-

5012(Five Zero One Two).


Source Code:
import java.util.Scanner; class a
{
public static void main(String k[])
{
Scanner s=new Scanner(System.in); int n,num=0;
System.out.println("Enter a number="); n=s.nextInt();
while(n>0)
{
num=(num*10)+(n%10); n/=10;
}
while(num!=0)
{
switch(num%10)
{
case 0: System.out.print("ZERO "); break;
case 1:

System.out.print(" ONE"); break;


case 2:
System.out.print(" TWO"); break;
case 3:
System.out.print(" THREE"); break;
case 4:
System.out.print(" FOUR"); break;
case 5: System.out.print(" FIVE"); break;
case 6: System.out.print(" SIX"); break;
case 7:
System.out.print(" SEVEN"); break;
case 8:
System.out.print(" EIGHT"); break;
case 9:

System.out.print(" NINE"); break;


}
num=num/10;
}
}
}
ASSIGNMENT-6(LOOP)

Q1. Input 10 numbers and find out the


largest and smallest.

Source Code:

import java.util.Scanner;

class a

public static void main(String k[])

Scanner s=new Scanner(System.in);

int q=0,l=0,n,i;

System.out.println("Enter 10 number=");

for(i=1;i<=10;i++)

n=s.nextInt();

if(n>l)

l=n;

}
if(n<l)

q=n;

System.out.println("The Largest no. is:" +l);

System.out.println("The Smallest no. is : " +q);

}
Q2. Print the factorials of a given
number.

Source Code:

import

java.util.Scanner; class

public static void main(String k[])

Scanner s=new

Scanner(System.in); int i,f=1,n;

System.out.println("Enter a

number="); n=s.nextInt();

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

f=f*i;

System.out.println("Factorial of " +n +"= " +f);

}
}
Q3. Generate a Fibonacci series up to
nth term.

Source Code:

import java.util.Scanner;

class a

public static void main(String k[])

Scanner s=new Scanner(System.in);

int c=0,n,a=0,b=1;

System.out.print("Enter the nth value=");

n=s.nextInt();

while(c<=n)

a=b;

b=c;

System.out.println(c);

c=a+b;
}

}
Q4. Input the starting range (m) and
the end range (n). Then find all prime numbers present in
this input range.

Source Code:

import java.util.Scanner;

class a

public static void main(String k[])

Scanner s=new Scanner(System.in);

int f,l,i,j;

System.out.println("Enter the intervals to find prime


numbers between them:");

f=s.nextInt();

l=s.nextInt();

for(i=f;i<=l;i++)

for(j=2;j<i;j++)
{

if(i%j==0)

break;

if(i==j)

System.out.println(i);

}
Q5. Find the sum of all digits of a given
number. Then count and print those digits from the result
number which are also present in the original number.

Source Code:

import java.util.Scanner;

class a

public static void main(String k[])

Scanner s=new Scanner(System.in);

int a,b=0,n,g=0,r,t=0,rem=0,c;

System.out.println("Enter a number=");

n=a=s.nextInt();

do{

b+=a%10;

a=a/10;

}
while(a>0);

System.out.println("Sum of digit=" +b);

while(b!=0)

r=b%10;

t=n;

g=0;

while(t!=0)

rem=t%10;

c=rem;

if(r==rem)

g++;

t/=10;

if(g!=0)

System.out.println(r + "is present " +g+" no. of times in


original number");

b=b/10;
}

}
Q6. Input a number and check whether
it is palindrome or not.

Source Code:

import java.util.Scanner;

class a

public static void main(String k[])

Scanner s=new Scanner(System.in);

int n,rev=0,r,q;

System.out.println("Enter a number=");

q=n=s.nextInt();

while(n>0)

r=n%10;

rev=(rev*10 )+r;

n=n/10;

}
if(rev==q)

System.out.println("Palindrome!");

else

System.out.println("Not Palindrome!");

}
Q7. Check whether an input number is
an Armstrong number or not.

Source Code:

import java.util.Scanner;

import java.lang.Math;

class a

public static void main(String k[])

Scanner s=new Scanner(System.in);

int n,d=0,d1,q=0,i;

System.out.println("Enter a number=");

n=s.nextInt();

for(i=n;i>0;i=i/10)

d++;

for(i=n;i>0;i=i/10)
{

d1=i%10;

q+=Math.pow(d1,d);

if(q==n)

System.out.println("Armstrong!");

else

System.out.println("Not Armstrong!");

}
ASSIGNMENT-7(SERIES)

Q1. WAP in Java to print and find the sum of following

series. Use separate methods for different series.


a) 1+ 1/2 + 1/3 + 1/4 + 1/5 + .. 1/n. Find the sum of this series.
b) 1 + 1/x + 1/x2 + 1/x3+.......+1/xn. Find the sum of this series.
c) 1 + 1/2! + 1/3!+....... +1/n!. Also find the sum.
d) 1 + 23 + 32 + 43 + …….+n
import java.util.Scanner;
import java.lang.Math; class a
{
int n,i,m;
Scanner s=new Scanner(System.in); void
first()
{
float sum=0,i,n;
System.out.print("Enter the value of n="); n=s.nextFloat();
for(i=1;i<=n;i++)
{
if(i==1) System.out.print("1 +");
else if(i==n) System.out.println("
1/"+i); else
System.out.print(" 1/"+i+" +");
sum=sum+(float)(1/i);
}
System.out.println("Sum=" +sum);
}
void second()
{
int x,n,i;
float f=0;
System.out.print("Enter total number of terms:");
n=s.nextInt();
System.out.print("Enter the value of x:"); x=s.nextInt();
for(i=1;i<=n;i++)
{
if(i==1) System.out.print("1
+"); else if(i==n)
System.out.println(" 1/"+x+"^"+i); else
System.out.print(" 1/"+x+"^"+i+"+");
f+=1+(1/Math.pow(x,i));
}
System.out.println("Sum=" +f);
}
void third()
{
int f=1,i,n; double
sum=0;
System.out.print("Enter number of terms=");
n=s.nextInt();
for(i=1;i<=n;i++)
{
f=f*i;
sum+=1.0/(f);
if(i==1) System.out.print("1
+"); else if(i==n)
System.out.println("1/"+i+"!"); else
System.out.print(" 1/"+i+"! "+"+");
}
System.out.println("Sum=" +sum);
}
void fourth()
{
int i,n,a=0,b=0,sum=0,j,m;
Scanner s=new Scanner(System.in);
System.out.print("Enter the value of n=");
m=n=s.nextInt();
for(i=1;i<=n;i++)
{
if(i<n & i%2==0)
{
System.out.print(i+"^3 + ");
}
else if(i==n)
{ if(i%2==0)
{
System.out.print(i+"^3");
} if(i%2!=0)
{
System.out.print(i+"^2");
}
}
else if(i<n & i%2!=0)
{
System.out.print(i+"^2 + ");
}
}
for(j=1;j<=m;j++)
{ if(j%2==0)
a+=Math.pow(j,3); else
b+=Math.pow(j,2);
}
sum=a+b;
System.out.println("");
System.out.println(sum);
}
public static void main(String k[])
{
a obj=new a();
obj.first();
obj.second();
obj.third();
obj.fourth();
}
}
Q2. Find all 4 digit numbers which satisfies the condition
that, square of (First two digit + last two digit) = original number. Eg. if number is
3025 then (30+25)2 =3025.
Source Code:
import java.lang.Math; class
a
{
public static void main(String k[])
{
for(int i=1000;i<=9999;i++)
{
int n=i;
int r1=0,r2=0,f=0;
double res=0;
r1=n%100;
r2=n/100;
f=r1+r2;
res=Math.pow(f,2);
if(res==n)
{
System.out.println(res);
}
}
}
}
Q3. Input any number and reduce it to single digit by
adding all its digits repeatedly.
Source Code:
import java.util.Scanner; class
a
{
public static void main(String k[])
{
Scanner sc=new Scanner(System.in); int
n,s=0;
System.out.println("Enter a number=");
n=sc.nextInt();
while(n>0 || s>9)
{
if(n==0)
{
n=s;
s=0;
} s+=n%10;
n=n/10;
}
System.out.println("Sum=" +s);
}
}
Q4. Multiply all digits of a number repeatedly till the result
is a single digit. Zeros should be ignored from the original number and intermediate
results. Ex- if the number is 505, then result should be 1.
Source Code:
import java.util.Scanner;
class a
{
public static void main(String k[])
{
int p=1,n,a;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number=");
n=s.nextInt();
while(n>10)
{
a=n;
while(a!=0)
{
p=p*(a%10);
a=a/10;
if(a == 0)
{
n=p;
p=1;
}
}
}
if(n==0)
System.out.println("1");
else System.out.println(n);
}}
Q5. Generate the following patterns:

a.) 1 0 0 0 1
01010
00100
01010
10001
Source Code:
class a
{
public static void main(String k[])
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if((j==i)||(i+j==5+1))
{
System.out.print("1"+" ");
}
else
{
System.out.print("0"+" ");
}
}
System.out.println();
}
}
}
b.) 5 4 3 2 1

5 4 3 2

5 4 3

5 4

Source Code:
class a
{
public static void main(String k[])
{
int i,j;
for(i=0;i<=5;i++)
{
for(j=5;j>i;j--)
{
System.out.print(j+" ");
}
System.out.println("");
}
}
}
ASSIGNMENT-8(CONSTRUCTOR)

Q1. WAP in Java to design a class Fraction having data


members num and denum. Define default constructor, one argument constructor, two argument
constructor and a copy constructor to set the values to numerator and denominator by different
objects.

Define methods such as show(), add(), subtract(), multiply(), div(), compare(), mixed()
and reduce().

Create different objects using different constructors given above. Perform the above operations using
appropriate methods. Show the result in reduced form of the result fraction after each operation.
After reducing if the fraction is an improper fraction (Ex- 5/2) then represent it in the form of mixed
fraction(2 Full and ½).
Source Code:
import java.util.Scanner; class
Fraction

{
int num;
final int num_backup; int
denum;
final int denum_backup;
Fraction()

{
this(1);
}
Fraction(int num)
{
this(num, 1);
}
Fraction(Fraction object)
{
this(object.num_backup, object.denum_backup);
}
Fraction(int num, int denum)
{
this.num= num_backup = num; this.denum =
denum_backup = denum;

}
int greatestCommonDevisor(int first, int second)
{
if (first > second)
{
first = first + second; second =
first - second; first = first -
second;

} // ' first ' always gets the minimum value


for (int commonDivisor = 0, i = 1; i <= first; i++)
{
if (first % i == 0 && second % i == 0)
commonDivisor = i;

if(i == first)
return commonDivisor;
}
return -1;
}
int reduce()
{
int quotient=num/denum;
num=num % denum;
int hcf=greatestCommonDevisor(num, denum); num=num/hcf;
denum=denum/ hcf; return
quotient;

}
public void show()
{
int quotient = reduce();
if(quotient == 0)
System.out.println(num + "/" + denum); else if
(num%denum== 0) System.out.println(quotient);

else
System.out.println(quotient + " full " + num + "/" + denum);
}
public static void main(String[] args)
{
System.out.println("Enter the numerator and denominator"); Scanner s=new
Scanner(System.in);
int firstNumber=s.nextInt(); int
secondNumber=s.nextInt();
Fraction test = new Fraction(firstNumber, secondNumber); Fraction
object=new Fraction();
Fraction obj=new Fraction(object);
test.show();

}
}
Q2. Create a class Complex having member variables
real and imag. Also create constructors and methods as follows:

a. Complex()
b. Complex(int,int)
c. Complex(Complex)
d. void showComplex()
e. Complex addComplex(Complex)
f. Complex substractComplex(Complex)
g. Complex multiplyComplex(Complex)
Write a java program to create objects of above class and perform operations as the methods
specified above.
Source Code:
import java.util.Scanner; import
java.lang.Math; class Complex

{
double real, img; Complex(double r,
double i)

{
this.real = r;
this.img = i;

}
public static Complex sum(Complex c1,Complex c2)
{
Complex temp = new Complex(0, 0); temp.real =
c1.real + c2.real; temp.img = c1.img + c2.img;
return temp;
}
public static Complex sub(Complex c1,Complex c2)
{
Complex temp1 = new Complex(0, 0); temp1.real
= c1.real - c2.real; temp1.img = c1.img - c2.img;

return temp1;
}
public static Complex mul(Complex c1,Complex c2)
{
Double i,m,n,j;
Complex temp2 = new Complex(0, 0); m=((c1.real *
c2.real) - (c1.img * c2.img)); n=((c1.real * c2.img) +
(c1.img * c2.real)); temp2.real = m;
temp2.img = n;
return temp2;

}
public static void main(String k[])
{
Scanner s=new Scanner(System.in); Double
r1,r2,i1,i2;
System.out.println("Enter real and imag part of 1st Complex Number="); r1=s.nextDouble();

i1=s.nextDouble();
System.out.println("Enter real and imag part of 2nd Complex Number="); r2=s.nextDouble();

i2=s.nextDouble();

Complex c1 = new Complex(r1,i1);


Complex c2 = new Complex(r2,i2); Complex
temp = sum(c1, c2);
System.out.println("Sum is: "+ temp.real+" + "+ temp.img +"i"); Complex temp1 =
sub(c1, c2);
System.out.println("Sub is: "+ temp1.real+" + "+ temp1.img +"i"); Complex temp2 =
mul(c1, c2);

System.out.println("Mul is: "+ temp2.real+" + "+ temp2.img +"i");


}
}
ASSIGNMENT-9(ARRAY)

Q1. WAP to create a class ArrayOperation having


member variables as an integer array and it’s size. Allocate memory for the Array as per the size
specified and initialize it to zero using constructor.
Design methods to perform the following operations on the array:
=> Input required elements into the array.

=> To display the array elements.

=> Calculate sum and average of elements.


=> Swap the max and min elements.
=> Find the occurrence of all unique elements.
=> Generate numbers by concatenating the values of two consecutive indexes starting from zero to end.
Also find the maximum number out of these new generated numbers. For example if the values are : 2,
35, 70, 9, 6

then the generated numbers should be 235, 709, 6.

Source Code:
import java.util.Scanner; class
ArrayOperation

{
int array[]=new int[100]; int i,n;

ArrayOperation()
{

this.input();
this.output();
this.sumavg();
this.swap();
this.ocrnce();
this.concat();

}
void input()
{

Scanner s=new Scanner(System.in);


System.out.println("Enter size of array="); n=s.nextInt();
System.out.println("Enter elements of array="); for(i=0;i<n;i++)

array[i]=s.nextInt();
}
}

void output()
{

System.out.println("Array elements are=");


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

System.out.println(array[i]);
}
}

void sumavg()
{

int sum=0,avg;
for(i=0;i<n;i++)

sum+=array[i];
}

avg=sum/n;
System.out.println("Sum of array elements=" +sum);
System.out.println("Average of array elements=" +avg);
}

void swap()
{

int max,min,mxpos=0,mnpos=0,l;
max=array[0];
min=array[0];
for(i=0;i<n;i++)

if(array[i]>max)
{

max=array[i];
mxpos=i;

if(array[i]<min)
{

min=array[i];
mnpos=i;

}
}

l=array[mxpos];
array[mxpos]=array[mnpos];
array[mnpos]=l;
System.out.println("After swapping max and min value="); for(i=0;i<n;i++)

System.out.println(array[i]);
}
}

void ocrnce()
{
int c=0,j;
int b[]=new int[n];
for(i=0;i<n;i++)

c=1;
if(array[i]!=-1)
{

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

if(array[i]==array[j])
{
c=c+1;
array[j]=-1;

}
}

b[i]=c;
}
}

System.out.println("Occurenece of array element:"); for(i=0;i<n;i++)

if(array[i]!=-1)
{
System.out.println(array[i] + ":" +b[i]);
}
}
}

void concat()
{

int m,c=0,g=0,t,b;
int q[]=new int[100]; System.out.println("Concatenation after Occurence
="); for(int i=0,j=0;i<=array.length-1;i+=2,j++)

m=0;
m=array[i+1];
c=0;

while(m>0)
{

m=m/10;
c++;

if(i==(array.length-1))
{

q[j]=array[i+1]*(int)(Math.pow(10,c));
System.out.println(q[j]);
}
else
{
q[j]=array[i]*(int)(Math.pow(10,c)) + array[i+1];

if(q[j]>0)
{

System.out.println(q[j]); g++;

}
}

for(i=0;i<g;i++)
{

for(b=i+1;b<g;b++)
{
if(q[i]>q[b])
{

t=q[i];
q[i]=q[b];
q[b]=t;

}
}
}

System.out.println("Maximum element=" +q[g-1]);


}

public static void main(String k[])


{
ArrayOperation obj=new ArrayOperation();
}
}
ASSIGNMENT-10(SORTING)

Q1. WAP in Java to design a class SortArray with


suitable data members and member functions to do the following operations:
a) To allocate n size of memory for the array which is to be sorted.
b) To input n numbers into the array.
c) To show the values stored in the array.
To arrange them in ascending / descending order using:

d) Bubble sort

e) Selection sort
f) Insertion sort
Source Code:
import java.util.Scanner; class
SortArray
{
Scanner s=new Scanner(System.in); public
int n,i,j;
int[] array = new int[10]; void
allocate()
{

System.out.println("Enter the size of array="); n=s.nextInt();


}

void input()
{

System.out.println("Enter the elements of array:");


for(i=0;i<n;i++)
{
array[i]=s.nextInt();
}
}

void show()
{

System.out.println("Values stored in the array=");


for(i=0;i<n;i++)
{
System.out.println(array[i]);
}
}

void bubblesort()
{
int temp = 0;
for(i=0; i < n; i++)
{
for(j=1; j < (n-i); j++)
{
if(array[j-1] > array[j])
{

temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;

}
}
}

System.out.println("Array After Bubble Sort(ascending order):-"); for(i=0;i<n ;


i++)
{

System.out.println(array[i]);
}
System.out.println("Array After Bubble Sort(descending order):-"); for(i=n-1;i>=0 ;
i--)
{

System.out.println(array[i]);
}
}

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

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

if(array[j]<array[min_indx])
{
min_indx=j;
}
}

int temp=array[min_indx];
array[min_indx]=array[i];
array[i]=temp;
}

System.out.println("Array After Selection Sort(descending order):-"); for(i=n-1;i>=0 ;


i--)
{

System.out.println(array[i]);
}

System.out.println("Array After Selection Sort(ascending order):-"); for(i=0;i<n; i++)


{
System.out.println(array[i]);
}
}

void insertionsort()
{

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

int key=array[i]; j=i-


1;
while (j>=0 && array[j]>key)
{

array[j+1]=array[j]; j=j-
1;
}

array[j+1]=key;
}

System.out.println("Array After Insertion Sort(descending order):-"); for(i=n-1;i>=0 ;


i--)
{

System.out.println(array[i]);
}

System.out.println("Array After Insertion Sort(ascending order):-"); for(i=0;i<n;++i)


System.out.println(array[i]);

public static void main(String k[])


{
SortArray obj=new SortArray();
obj.allocate();
obj.input();
obj.show();
obj.bubblesort();
obj.selectionsort();
obj.insertionsort();
}
}
ASSIGNMENT-11(MD-ARRAY)

Q1. WAP in Java to create two classes such as


TwoDArray and OneDArray. Members of TwoDArray
class are:

a) One 2D array.
b) Constructor to allocate memory of size (2 X n) for the array.
c) Input data into the Array.

d) Display the array elements in row wise.


e) Split this array into two different arrays and store them in the array available in two
different objects of class OneDArray.
f) Add the arrays(m X n matrices) of two objects of TwoDArray class.
g) Multiply the arrays(m X n matrices) of two objects of TwoDArray class.

Members of OneDArray class are:

a) One 1D array.
b) Constructor to allocate memory of size (n) as the column size of TwoDArray
class.
c) Show the array.
Source Code:
import java.util.Scanner; class
TwoDArray
{

Scanner sc=new Scanner(System.in);


private int twodarr[][];
public TwoDArray(int n)
{

twodarr=new int[2][n];
}

public void getinput(int n)


{
for(int i=0;i<2;i++) for(int
j=0;j<n;j++)
{

System.out.println("enter the element of location arr2d


["+i+"] ["+j+"]");
twodarr[i][j]=sc.nextInt();
}
}

public void display(int n)


{

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

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

System.out.print(twodarr[i][j]+"\t");
}

System.out.print("\n");
}
}

public void split(OneDArray od,int j)


{

for(int i=0;i<twodarr[j].length;i++)
od.array[i]=twodarr[j][i];
}

public void add(TwoDArray td1,TwoDArray td2,int n)


{

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


j=0;j<n;j++)
twodarr[i][j]=td1.twodarr[i][j]+td2.twodarr[i][j];
}
public void multiply(TwoDArray td1,TwoDArray td2,int n)
{

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


j=0;j<n;j++)
{

twodarr[i][j]=0; for(int
k=0;k<n;k++)
twodarr[i][j]+=td1.twodarr[i][k]*td2.twodarr[k][j];
}
}
}

class OneDArray
{

public int array[]; public


OneDArray(int n)
{

array=new int[n];
}

public void print(int n)


{

for(int i=0;i<n;i++)
System.out.print(array[i]+"\t");
System.out.print("\n");
}

public static void main(String args[])


{
Scanner sc=new Scanner(System.in); int n;
System.out.println("enter the column no for 2D array"); n=sc.nextInt();
TwoDArray td=new TwoDArray(n);
TwoDArray td1=new TwoDArray(n);
OneDArray od1=new OneDArray(n);
OneDArray od2=new OneDArray(n);
td1.getinput(n);
System.out.println("Array element row wise");
td1.display(n);
td1.split(od1,0);
td1.split(od2,1);
System.out.println("OneDArray splitting ");
System.out.println("Splitted array row wise");
od1.print(n);
System.out.println("Splitted array row wise");
od2.print(n);
TwoDArray td2=new TwoDArray(n);
td2.getinput(n);
System.out.println("Array element row wise");
td2.display(n);
td.add(td1,td2,n);
System.out.println("Addition of two object of TwoDArray: "); td.display(n);
td.multiply(td1,td2,n);
System.out.println("Multipication of two object of TwoDArray: "); td.display(n);
}
}
Q2. Modify the above program to create same (m) no
of array of objects of OneDArray as the no of rows available in the array (m X n) of
TwoDArray. Then add another method in TwoDArray class that can distribute all rows of
the 2D array of TwoDArray class into each object of OneDArray class.
Source Code:
import java.util.Scanner; class
TwoDArray
{

Scanner sc=new Scanner(System.in);


private int twodarr[][];
public TwoDArray(int m,int n)
{

twodarr=new int[m][n];
}

public void getinput(int m,int n)


{

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


j=0;j<n;j++)
{

System.out.println("enter the element of location arr2d


["+i+"] ["+j+"]");
twodarr[i][j]=sc.nextInt();
}
}

public void display(int m,int n)


{

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

for(int j=0;j<n;j++)
{
System.out.print(twodarr[i][j]+"\t");
}

System.out.print("\n");
}
}

public void split(OneDArray od,int j)


{

for(int i=0;i<twodarr[j].length;i++)
od.array[i]=twodarr[j][i];
}
}

class OneDArray
{

public int array[]; public


OneDArray(int n)
{
array=new int[n];
}
public void print(int n)
{

System.out.println("Splitted array row wise"); for(int


i=0;i<n;i++)
System.out.print(array[i]+"\t");
System.out.print("\n");
}
}

class m_d_array
{

public static void main(String args[])


{
Scanner sc=new Scanner(System.in); int
n,m;
System.out.println("enter the row no for 2D array");
m=sc.nextInt();
System.out.println("enter the column no for 2D array"); n=sc.nextInt();
TwoDArray td=new TwoDArray(m,n);
TwoDArray td1=new TwoDArray(m,n);
//created a array of class type OneDArray
od[]=new OneDArray[m];
//in loop create a object of same class of array type for(int
i=0;i<m;i++)
{

od[i]=new OneDArray(n);
}

td1.getinput(m,n);
System.out.println("Array element row wise");
td1.display(m,n);
for(int i=0;i<m;i++)
td1.split(od[i],i);
System.out.println("OneDArray splitting "); for(int
i=0;i<m;i++)
od[i].print(n);

}
}
ASSIGNMENT-12(JAGGED ARRAY)

Q1. There are five brothers and sisters are trying to


store their marks in one reference (array) for better analysis. But the number of
subjects is different for each child as they are reading in different classes.
Child1 has 3 subjects, Child2 has 5 subjects, Child3 has 2 subjects, Child4 has 6
subjects and Child5 has 4 subjects. Help them to achieve this.

Design a class JaggedArray with following members:

a) One Array to hold all marks of five brothers & sisters.


b) Constructor to allocate memory for the Array exactly
as the no of subjects specified for each children.
c) Input marks in different subjects for different children.
d) Show the marks row-wise with child name at the beginning.

e) Show the total marks scored by each child.


f) Count the subjects having marks more than 80 separately for each child.
g) Alert them by showing the subjects which are less than 30 for better preparation.
Source Code:
import java.util.Scanner; class
JaggedArray
{
Scanner s=new Scanner(System.in); int[][]
marks=new int[5][ ]; JaggedArray()
{

marks[0]=new int[3];
marks[1]=new int[5];
marks[2]=new int[2];
marks[3]=new int[6];
marks[4]=new int[4];
}

void input()
{

for(int i=0;i<marks.length;i++)
{

System.out.println("Enter marks of CHILD " +(i+1) +"="); for(int


j=0;j<marks[i].length;j++)
{

System.out.print("Enter marks of Subject " +(j+1) +"="); marks[i][j]=s.nextInt();


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

void show()
{

for(int i=0;i<marks.length;i++)
{

System.out.print("Marks of CHILD " +(i+1) +":" +" ");


for(int j=0;j<marks[i].length;j++)
{

System.out.print("Subject " +(j+1) +"=" +marks[i][j] +" ");


}

System.out.println("");
}
}
void total()
{

int sum=0;
for(int i=0;i<marks.length;i++)
{

for(int j=0;j<marks[i].length;j++)
{

sum+=marks[i][j];
}

System.out.println("Total Marks of CHILD " +(i+1) +"=" +sum); sum=0;


}
}

void more()
{

int count=0;
for(int i=0;i<marks.length;i++)
{

for(int j=0;j<marks[i].length;j++)
{

if(marks[i][j]>80)
{

count++;
}
}

System.out.println("CHILD " +(i+1) +"have " +count +" subjects in which his/her
marks is more than 80!");
count=0;

}
}

void less()
{

for(int i=0;i<marks.length;i++)
{

for(int j=0;j<marks[i].length;j++)
{

if(marks[i][j]<30)
{
System.out.println("CHILD" +(i+1) +"needs better preparation in Subject" +(j+1));
}

}
}

public static void main(String k[])


{
JaggedArray obj=new JaggedArray();
obj.input();
obj.show();
obj.total();
obj.more();
obj.less();
}
}
ASSIGNENT-13(STATIC METHOD)

Q1. Write a java program to create a class CricketPlayer


(name, no_of_innings, times_ of_notout, total_runs, bat_avg). Create an array of
objects for n players.
Calculate the batting average for each player using a static method avg().
Define a static method “sortPlayer( )” which sorts the array in descending
order on the basis of batting average. Display the player details in sorted order.

Source Code:

import java.io.*;

class Cricket

String name;

int inning,tofnotout,totalruns;

float batavg;

Cricket()

name=null;

inning=0;

tofnotout=0;

totalruns=0;

batavg=0;

public void get() throws IOException

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("Enter the name, no of innings, no of times not out,


total runs: ");

name=br.readLine();

inning=Integer.parseInt(br.readLine());
tofnotout=Integer.parseInt(br.readLine());

totalruns=Integer.parseInt(br.readLine());

public void put()

System.out.println("Name="+name);

System.out.println("no of innings="+inning);

System.out.println("no times notout="+tofnotout);

System.out.println("total runs="+totalruns);

System.out.println("bat avg="+batavg);

System.out.println(" ");

static void avg(int n, Cricket c[])

try

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

c[i].batavg=c[i].totalruns/c[i].inning;

catch(ArithmeticException e)

System.out.println("Invalid arg");

}
static void sort(int n, Cricket c[])

String temp1;

int temp2,temp3,temp4;
float temp5;

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

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

if(c[i].batavg<c[j].batavg)

temp1=c[i].name;

c[i].name=c[j].name;

c[j].name=temp1;

temp2=c[i].inning;

c[i].inning=c[j].inning;

c[j].inning=temp2;

temp3=c[i].tofnotout;

c[i].tofnotout=c[j].tofnotout;

c[j].tofnotout=temp3;

temp4=c[i].totalruns;

c[i].totalruns=c[j].totalruns;

c[j].totalruns=temp4;

temp5=c[i].batavg;

c[i].batavg=c[j].batavg;

c[j].batavg=temp5;

}
}

}
class a

public static void main(String args[])throws IOException

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

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

int n=Integer.parseInt(br.readLine());

Cricket c[]=new Cricket[n];

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

c[i]=new Cricket();

c[i].get();

Cricket.avg(n,c);

Cricket.sort(n, c);

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

c[i].put();

}
Q2. Create a class called Account having data members
acct_no, acct_type, customer_name and acct_balance. Write a java program to
input data for five customers and print the details of customer having maximum
balance in the account.

Source Code:

import java.io.*;

class Account

String acct_type,custmr_name;

int acct_no,acct_balnc; Account()

acct_no=0;

acct_type=null;

custmr_name=null;

acct_balnc=0;

public void get() throws IOException

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

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

acct_no=Integer.parseInt(br.readLine());

System.out.print("Enter the account type=");

acct_type=br.readLine(); System.out.print("Enter

the customer name="); custmr_name=br.readLine();

System.out.print("Enter the account balance=");

acct_balnc=Integer.parseInt(br.readLine());

System.out.println("");
}

public void put()

System.out.println("Account number=" +acct_no);

System.out.println("Account type=" +acct_type);

System.out.println("Customer Name=" +custmr_name);

System.out.println("Account Balance=" +acct_balnc);

System.out.println(" ");

public static void main(String m[])throws IOException

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

Account a[]=new Account[5];

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

a[i]=new Account();

a[i].get();

int[] array=new int[5];

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

array[i]=a[i].acct_balnc;

int largest=array[0];

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

if(largest<array[i])

largest=array[i];

}
System.out.println("Maximum account balance among the customer="
+largest);

System.out.println("Details of customer having maximum account balance:


");
for(int i=0;i<5;i++)

if(a[i].acct_balnc==largest)

a[i].put();

}
ASSIGNMENT-14(STRING)

Q1. Write a java program to define a class UserString


and to perform the following operations using different methods. a) Count all the characters b) Count
no of words c) Compare two strings d) Convert to uppercase
e) Convert to lowercase f) Concatenate two strings g) Check a string is palindrome or not h) Find the
position of a given character i) Make a substring from a desired start and end position. j) Search the
presence of a substring. k) Replace a substring with a new string.

l) Swap two substrings from two strings.

Source Code:
import java.util.*;
import java.lang.*; class
UserString

{
void countchar(String s,String s1)
{

System.out.println("Number of char in a Sentence:" +(s.length())); System.out.println("Number of


char in another Sentence:" +(s1.length()));

void countwords(String s,String s1)


{

int c=1,d=1;
for(int i=0;i<s.length();i++)
{

if((s.charAt(i)==' ') && (s.charAt(i+1)!=' '))


{

c++;
}
}
System.out.println("Number of words in a sentence=" +c); for(int
i=0,j=0;i<s.length() && j<s1.length();i++,j++)

if((s.charAt(i)==' ') && (s.charAt(i+1)!=' '))


{

c++;
}

if((s1.charAt(j)==' ') && (s1.charAt(j+1)!=' '))


{

d++;
}
}

System.out.println("Number of words in another sentence=" +d);


}

void compare(String s,String s1)


{

int l1=s.length(); int


l2=s1.length(); if(l1!=l2)

System.out.println("Strings are not equal");

else
{
int i=0,t=0;
while(i!=l1)

if(s.charAt(i)!=s1.charAt(i))
{

t=1;
break;
}
i++;
}

if(t==0)
System.out.println("Strings are equal");

else
System.out.println("Strings are not equal");

}
}

void upper(String s,String s1)


{

char[ ] ch=s.toCharArray(); char[ ]


ch1=s1.toCharArray(); for(int
i=0;i<ch.length;i++)

if(ch[i]>='a' && ch[i]<='z')


{

ch[i]=(char)((int)ch[i] - 32);
}
}

System.out.println("String in uppercase is: "); for(int


a=0;a<ch.length;a++)

System.out.print(ch[a]);
}

System.out.println(""); for(int
i=0;i<ch1.length;i++)

if(ch1[i]>='a' && ch1[i]<='z')


{

ch1[i]=(char)((int)ch1[i] - 32);
}
}

System.out.println("String1 in uppercase is: "); for(int


b=0;b<ch1.length;b++)

System.out.print(ch1[b]);
}

System.out.println("");
}

void lower(String s,String s1)


{

char[ ] ch=s.toCharArray(); char[ ]


ch1=s1.toCharArray();

for(int a=0,b=0;a<ch.length && b<ch1.length;a++,b++)


{

if(ch[a]>='A' && ch[a]<='Z')


{

ch[a]=(char)((int)ch[a] + 32);
}

if(ch1[b]>='A' && ch1[b]<='Z')


{

ch1[b]=(char)((int)ch1[b] + 32);
}
}

System.out.println("String in lowercase is: "); for(int


a=0;a<ch.length;a++)

System.out.print(ch[a]);
}

System.out.println("");
System.out.println("String1 in lowercase is: "); for(int
b=0;b<ch1.length;b++)

System.out.print(ch1[b]);
}

System.out.println("");
}

void concatenate(String s,String s1)


{

System.out.println("Concatenated String: " +(s+" "+ s1) );


}

void palindrome(String s,String s1)


{

s=s + " ";


String str1=""; int
i,j,k,c=0;
System.out.print("Palindrome word in a Sentence are : " );
for(i=0;i<s.length();i++)

char ch=s.charAt(i);
if(ch==' ')

for(j=0,k=str1.length()-1;j<(str1.length()/2);j++,k--)
{

if(str1.charAt(j)==str1.charAt(k)) c++;

if(c==(str1.length()/2))
System.out.print(str1 +" " );
str1="";
c=0;

}
else

str1=str1+ ch;
}

s=s1 + " ";


str1="";
c=0;

System.out.println("");
System.out.print("Palindrome word in another Sentence are : " );
for(i=0;i<s.length();i++)

char ch=s.charAt(i);
if(ch==' ')

for(j=0,k=str1.length()-1;j<(str1.length()/2);j++,k--)
{

if(str1.charAt(j)==str1.charAt(k)) c++;

if(c==(str1.length()/2))
System.out.print(str1 +" " );
str1="";
c=0;
}
else

str1=str1+ ch;
}

System.out.println("");
}
void position(String s,String s1)
{

Scanner sc=new Scanner(System.in); String


str,str1;

int k,m;
System.out.print("Enter a character to check it's position in a sentence:"); str=sc.next();
k=s.indexOf(str);
while(k!=-1)

System.out.println((k+1));
k=s.indexOf(str, k+1);

System.out.print("Enter a character to check it's position in another sentence:");


str1=sc.next();
m=s1.indexOf(str1);
while(m!=-1)

System.out.println((m+1));
m=s1.indexOf(str1, m+1);

}
}

void substring(String s,String s1)


{

Scanner sc=new Scanner(System.in); int a,b,c,d;


System.out.print("Enter the start position of a sentence:"); a=sc.nextInt();
System.out.print("Enter the end position of a sentence:"); b=sc.nextInt();

System.out.println("Substring of a sentence from given position is : "


+(s.substring(a,(b+1))));

System.out.print("Enter the start position of a sentence:"); c=sc.nextInt();


System.out.print("Enter the end position of a sentence:"); d=sc.nextInt();

System.out.println("Substring of a sentence from given position is : "


+(s1.substring(c,(d+1))));
}

void prsnc(String s,String s1)


{

Scanner sc=new Scanner(System.in); String


str,str1;
System.out.print("Enter the substring of a sentence to check it's presence:");
str=sc.next(); System.out.println(s.toUpperCase().contains(str.toUpperCase()));

System.out.print("Enter the substring of another sentence to check it's presence:");


str1=sc.next(); System.out.println(s1.toUpperCase().contains(str1.toUpperCase()));

void replc(String s,String s1)


{

Scanner sa=new Scanner(System.in); String


str,str1,str2,str3;
System.out.print("Enter a substring which u want to replace in a sentence:");
str=sa.next();
System.out.print("Enter a new substring:");
str1=sa.next();

System.out.println("After replacement: " +(s.replace(str,str1)));

System.out.print("Enter a substring which u want to replace in another sentence:");


str2=sa.next();
System.out.print("Enter a new substring:"); str3=sa.next();

System.out.println("After replacement: " +(s1.replace(str2,str3)));

void swap(String s,String s1)


{

Scanner sca=new Scanner(System.in); String


str,str1;
System.out.print("Enter sub string of a Sentence which u want to swap with another
sentence:");
str=sca.nextLine();
System.out.print("Enter sub string of another Sentence which u want to swap with a sentence:");
str1=sca.nextLine();
System.out.println("After swapping string of a Sentence:"
+s.replace(str,str1));
System.out.println("After swapping string of another Sentence:"
+s1.replace(str1,str));
}

public static void main(String k[])


{
Scanner sc=new Scanner(System.in); UserString
obj=new UserString(); String s,s1;
System.out.print("Enter a Sentence:"); s=sc.nextLine();
System.out.print("Enter a another Sentence:");
s1=sc.nextLine();
obj.countchar(s,s1);
obj.countwords(s,s1);
obj.compare(s,s1);
obj.upper(s,s1);
obj.lower(s,s1);
obj.concatenate(s,s1);
obj.palindrome(s,s1);
obj.position(s,s1);
obj.substring(s,s1);
obj.prsnc(s,s1);

obj.replc(s,s1);
obj.swap(s,s1);
}
}
ASSIGNMENT-15(INHERITANCE)

Q1. Create a class Vehicle as follows :


Data members (All are private) –[Brand, Country_of_Origin,
Base_price]
Methods - input (to input details of vehicle) and display (to show vehicle details).
Create a sub class Car as follows:
Data members – [Model, speed, Market_price]
[NB: Market price of a car can be calculated from the Base price and speed. If
speed is above 80km/hr, market price will be 15% more than the base price
otherwise market price will be 5% less than the base price.]
Methods – read (to input car details) and show (to show car details).
In addition to above methods add more appropriate methods to set the
required data members.
Now create objects. Input required data and show the details (Brand,
Country_of_Origin, Base_price, Model, speed, Market_price) of any car.

Source Code:

import java.util.Scanner;

class Vehicle

Scanner s=new Scanner(System.in);

private String brand,Country_of_Origin;

private int Base_price;

public void input()

System.out.print("Enter the brand of vehicle:");

brand=s.next();

System.out.print("Enter the Country_of_Origin of vehicle:");


Country_of_Origin=s.next();

System.out.print("Enter the base price of vehicle in Rs.:");

Base_price=s.nextInt();

public int getBase_price()

return Base_price;

public void display()

System.out.println("Brand of vehicle is " +brand);

System.out.println("Country_of_Origin of vehicle is "

+Country_of_Origin);

System.out.println("The base price of vehicle is Rs. " +Base_price);

class Car extends Vehicle

private String model; private

float speed,a; private float

Market_price; void read()

System.out.print("Enter the model of car:");

model=s.next();

System.out.print("Enter the speed of vehicle in (km/hr)=");

speed=s.nextFloat();
System.out.println("");

void show()
{

a=getBase_price();

if(speed>80)

Market_price=(a +(0.15f*a));

else

Market_price=( a-(0.05f*a));

System.out.println("The model of car:" +model); System.out.println("The

speed of vehicle in (km/hr)=" +speed); System.out.println("The market

price of vehicle is Rs." +Market_price);

public static void main(String k[])

Car obj = new Car();

obj.input();

obj.read();

obj.display();

obj.show();

}
Q2. Create two classes such as Teacher (basic, da, hra,
epf, sub_taught) and Student (fees_per_sem, course, duration) which are inherited
from class Person(name, Id, year_of_join). Design appropriate methods to input the
data as given above whenever required.
Prepare an annual report for a Teacher showing the details such as Name, Id,
Subject Taught, Joining year, Basic salary per month, Total net salary received
per year, Total Epf deposited per year. If [Basic=15500/-, da=110%, hra=15%,
and epf=12%]
Inform the student by showing details such as Name, Id, Course Offered, Joining
year and total fees to be paid if the course duration is 4 years and fees per
semester is 18000/-.

Source Code:

import java.util.Scanner;

class Person

Scanner s=new Scanner(System.in);

public String name,id;

public int yr_of_join;

void input()

System.out.print("Enter the name of person:");

name=s.next();

System.out.print("Enter the id of person=");

id=s.next();

System.out.print("Enter the year of join of person=");

yr_of_join=s.nextInt();

}
class Teacher extends Person

float basic,da,hra,epf,total,tpef;

String sub_taught;

void input()

super.input();

System.out.print("Enter the name of subject taught:");

sub_taught=s.next();

basic=15500;

da=1.10f*basic;

hra=0.15f*basic;

epf=0.12f*basic;

total=12*((basic+da+hra)-epf);

tpef=0.12f*basic*12;

void showteacher()

System.out.println("The name of Teacher:" +name);

System.out.println("The id of Teacher=" +id); System.out.println("The

subject taught is " +sub_taught); System.out.println("The year of join

of Teacher=" +yr_of_join); System.out.println("The basic salary of

"+name +" per month is "

+basic);
System.out.println("Total net salary of "+name +" received per year is
" +total);

System.out.println("Total epf of "+name +" deposited per year is "


+tpef);

}
}
class Student extends Person

int fees_per_sem=18000,duration,total_fees; String

course;

void input()

super.input();

Scanner sc=new Scanner(System.in); System.out.print("Enter

the duration of course in year="); duration=sc.nextInt();

System.out.print("Enter the course offered:");

course=sc.next(); total_fees=18000*(2*duration);

void showstudent()

System.out.println("The name of Student:" +name);

System.out.println("The id of person=" +id); System.out.println("The

course offered is " +course); System.out.println("The duration of

offered course is " +duration); System.out.println("The year of join of

Student=" +yr_of_join); System.out.println("Total fees to be paid Rs. "

+total_fees);

public static void main(String k[])

Teacher t=new Teacher();

t.input(); t.showteacher();

Student stud=new Student();

stud.input();

stud.showstudent();
}

}
ASSIGNMENT-16(INHERITANCE)

Q1. Create a class Number :

Data member: An array of type integer.


Constructor: Constructor with one parameter n, that is the size of the array.
Allocate n memory for the array and input n numbers into the array.
Method-1: To display all the values in the array. Derive a class OddNum
from the class Number: Data member: An array of type integer.
Constructor: To count the odd numbers present in the array of its base class
Number and accordingly allocate memory for its own array.
Method-1: To copy all odd numbers from its base class array to its own array.

Method-2: To display all odd numbers.


Derive a class PrimeNum from the class OddNum: Data member: An array
of type integer.
Constructor: To count the prime numbers present in the array of its base class
OddNum and accordingly allocate memory for its own array.
Method-1: To copy all prime numbers from its base class array to its own
array.

Method-2: To display all prime numbers.

Source Code:

import java.util.Scanner;

class Number

public int arr[],m;

public Number(int b)

m=b;

Scanner s=new Scanner(System.in);


arr=new int[m];

System.out.println("Enter the elements of array:");

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

arr[i]=s.nextInt();

display(m);

void display(int t)

System.out.println("Elements of array are:");

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

System.out.println(arr[i]);

class OddNum extends Number

public int arr1[],count,m;

public OddNum(int p)

super(p);

m=p;

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

if(arr[i]%2!=0)
count++;

arr1=new int[count];

copyodd();
displayodd();

void copyodd()

int j=0;

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

if(arr[i]%2!=0)

arr1[j++]=arr[i];

void displayodd()

System.out.println("Odd numbers in an array are:");

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

System.out.println(arr1[i]);

System.out.println();

class PrimeNum extends OddNum

public int arr2[],count=0;

PrimeNum(int u)

super(u);
m=arr1.length;

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

int j=2;
int q=1;

while(j<arr1[i])

if(arr1[i]%j==0)

q=0;

break;

j++;

if(q==1)

count++;

arr2=new int[count];

copyprime();

displayprime();

void copyprime()

int k=0;

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

int j=2;

int q=1;

while(j<arr1[i])

if(arr1[i]%j==0)
{

q=0;

break;

}
j++;

if(q==1)

arr2[k]=arr1[i]

; k++;

void displayprime()

System.out.println("Prime numbers in an array are ");

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

System.out.println(arr2[i]);

System.out.println();

public static void main(String k[])

Scanner sc=new Scanner(System.in);

int a;

System.out.println("Enter the size of array:");

a=sc.nextInt();

PrimeNum ob=new PrimeNum(a);

}
Q2. Define a class Employee having private members –
id, name, department, salary. Define default and parameterized constructors.
Create a subclass called “Manager” with private member bonus. Define methods
accept() and display() in both the classes.
Create n objects of the Manager class and display the details of the manager
having the maximum total salary (salary+bonus).

Source Code:

import java.util.Scanner;

class Employee

private int id,depart_salary;

private String name,dept;

Employee()

id=0;

depart_salary=0;

name="";

dept="";

Employee(int i,int s,String n,String d)

id=i;

depart_salary=s;

name=n; dept=d;

void accept()

{
Scanner s=new Scanner(System.in);

System.out.print("\nEnter the name of the employee:");

name=s.next();

System.out.print("\nEnter the id of the employee:");

id=s.nextInt();

System.out.print("\nEnter the Salary of the employee:");

depart_salary=s.nextInt();

System.out.print("\nEnter the department of the employee:");

dept=s.next();

void display()

System.out.println("The name of the employee:" +name);

System.out.println("The id of the employee:" +id); System.out.println("The

Salary of the employee:" +depart_salary); System.out.println("The

department of the employee:" +dept);

int getid()

return(id);

int getdepart_salary()

return(depart_salary);

String getname()

{
return(name);

String getdept()

{
return(dept);

class Manager extends Employee

private int bonus;

Manager()

super();

Manager(int i,int s,String n,String d,int b)

super(i,s,n,d);

bonus=b;

void accept()

Scanner sc=new Scanner(System.in);

super.accept();

System.out.print("Enter bonus of the employee:");

bonus=sc.nextInt();

void display()

super.display();

System.out.println("Bonus of the employee:" +bonus);

}
static void max(Manager p[])

int max=0,total=0,id=0,i;

for(i=0;i<p.length;i++)
{

total=(p[i].getdepart_salary()) + p[i].bonus;

if(max<total)

max=total;

id=i;

System.out.print("\nEmployee having maximum salary:");

p[id].display();

public static void main(String k[])

Scanner s=new Scanner(System.in);

int n,i;

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

n=s.nextInt();

Manager[] m=new Manager[n];

System.out.print("\nEnter the details of employee:");

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

m[i]=new Manager();

m[i].accept();

Manager.max(m);

}
ASSIGNMENT-17(ABSTRACT)

Q1. Create a class Shape having data members length,


breadth, height and abstract methods such as volume and surfaceArea. Inherit this class
into cube, cylinder and cuboid classes. Redefine the required methods to calculate and
display the volume and surface area of each shape.
Source Code:
import java.util.Scanner;
abstract class Shape
{

int l,b,h; double


r1,h1;
abstract void volume(); abstract
void surfaceArea();
}

class Cube extends Shape


{

void input()
{

Scanner s=new Scanner(System.in);


System.out.println("Enter the length:"); l=s.nextInt();
}

void volume()
{

System.out.println("Volume of cube=" +(l*l*l));


}

void surfaceArea()
{

System.out.println("Surface area of cube=" +(6*l*l));


}
}

class Cylinder extends Shape


{

void inputcylndr()
{

Scanner s=new Scanner(System.in);


System.out.println("Enter the radius:");
r1=s.nextDouble(); System.out.println("Enter the
height:"); h1=s.nextDouble();
}

void volume()
{

System.out.println("Volume of cylinder=" +(3.14*r1*h1));


}

void surfaceArea()
{

System.out.println("Surface area of cylinder=" +((2*3.14*r1*h1) + (2*3.14*r1*r1)


));
}

}
class Cuboid extends Shape
{

void input()
{

Scanner s=new Scanner(System.in);


System.out.println("Enter the length:"); l=s.nextInt();
System.out.println("Enter the breadth:"); b=s.nextInt();
System.out.println("Enter the height:"); h=s.nextInt();
}

public void volume()


{

System.out.println("Volume of cuboid=" +(l*b*h));


}

public void surfaceArea()


{

System.out.println("Surface area of cuboid=" +( (2*l*b)


+(2*b*h)+(2*h*l) ));
}
public static void main(String k[])
{
Cube obj=new Cube();
obj.input();
obj.volume();
obj.surfaceArea();

Cylinder ob=new Cylinder();


ob.inputcylndr(); ob.volume();
ob.surfaceArea();

Cuboid o=new Cuboid();


o.input();
o.volume();
o.surfaceArea();
}
}
Q2. Design an abstract class fruit with data members
colour, taste and an abstract method display. Inherit this class to other classes such as
Apple, Banana, Orange and Strawberry. Redefine the display method to show the color
and taste of each fruit along with its name.
Source Code:
import java.util.Scanner;
abstract class fruit
{

String colour,taste; abstract


void display();
}

class Apple extends fruit


{

void input()
{

Scanner s=new Scanner(System.in); System.out.println("Enter the


colour of fruit"); colour=s.next();
System.out.println("Enter the taste of fruit"); taste=s.next();
}

void show()
{

System.out.println("Fruit is Apple!");
}

void display()
{

System.out.println("The colour of fruit Apple is " +colour +" and taste is " +taste);
}
}
class Banana extends fruit
{

void input()
{

Scanner s=new Scanner(System.in);


System.out.println("Enter the colour of fruit");
colour=s.next();
System.out.println("Enter the taste of fruit"); taste=s.next();
}

void show()
{

System.out.println("Fruit is Banana!");
}

void display()
{

System.out.println("The colour of fruit Banana is " +colour +" and taste is " +taste);
}

}
class Orange extends fruit
{

void input()
{

Scanner s=new Scanner(System.in); System.out.println("Enter the


colour of fruit"); colour=s.next();
System.out.println("Enter the taste of fruit"); taste=s.next();
}
void show()
{

System.out.println("Fruit is Orange!");
}

void display()
{

System.out.println("The colour of fruit Orange is " +colour +" and taste is " +taste);
}

}
class Strawberry extends fruit
{

void input()
{

Scanner s=new Scanner(System.in); System.out.println("Enter the


colour of fruit"); colour=s.next();
System.out.println("Enter the taste of fruit"); taste=s.next();
}

void show()
{

System.out.println("Fruit is Strawberry!");
}

void display()
{

System.out.println("The colour of fruit Strawberry is " +colour +" and taste is "
+taste);
}
public static void main(String k[])
{
Apple obj=new Apple();
obj.show();
obj.input();
obj.display();

Banana ob=new Banana();


ob.show();
ob.input();
ob.display();

Orange o=new Orange();


o.show();
o.input();
o.display();
}
}
ASSIGNMENT-18(INTERFACE)

Q1. Define an interface “IntOperations” with methods


to check whether a number is positive/ negative, even/odd, prime, palindrome
and operations like factorial and sum of digits. Define a class MyNumber having
one private data member of type int. Write a default constructor to initialize it
to 0 and another constructor to initialize it to a value (Use this).
Implement the above interface. Create an object in main method. Input a number
and write a menu driven program to check different properties of the number using
above methods.

Source Code:

import

java.util.Scanner;

interface IntOperation

void positive(int

n); void even(int

n); void prime(int

n); void fact(int

n); void sum(int

n);

class MyNumber implements IntOperation

private int
num;

MyNumber()

num=0;

MyNumber(int num)
{

this.num=num;

}
public void positive(int num)

if(num>0)

System.out.println(num +" is Positive");

else

System.out.println(num +" is Negative");

public void even(int num)

if(num%2==0)

System.out.println(num +" is Even");

else

System.out.println(num +" is Odd");

public void fact(int num)

int fact=1,i;

for(i=1;i<num+1;i++)

fact=fact*i;

System.out.println("Factorial is "+fact);

public void sum(int num)

{
int sum=0;

while(num!=0

sum=sum+(num%10)

; num=num/10;

System.out.println("Sum of digits "+sum);

public void prime(int num)


{

int i,j=0;

for(i=2;i<num;i++

if(num%i==0

) j=1;

if(j==0 || num==1)

System.out.println(num +" is

Prime");

else
System.out.println(num +" is not Prime");

public static void main(String[] arg)

Scanner s=new

Scanner(System.in); IntOperation

m;

MyNumber n1=new

MyNumber(); m=n1;

System.out.println("Enter a

number:"); int n=s.nextInt();

n1.positive(n)

; n1.even(n);

n1.prime(n);

n1.fact(n);

n1.sum(n);

}
}
Q2. Define an interface “StackOperations” which
declares methods for a static stack. Define a class “MyStack” which contains an
array and top as data members and implements the above interface.
Initialize the stack using a constructor. Write a menu driven program to
perform all operations(Push, POP, Peak) on a MyStack object.

Source Code:

import java.util.Scanner;

interface StackOperations

int max=10;

void push(int data);

void pop();

int isempty();

int isfull();

class Mystack implements StackOperations

private int arr[]=new int[StackOperations.max];

private int top;

Mystack()

top=-1;

public void push(int data)

arr[++top]=data;

public void pop()


{

System.out.println("Poped element is :"+arr[top]);

top--;

public int isempty()

if(top==-1)

return 1;

else
return 0;

public int isfull()

if(top==9)

return 1;

else
return 0;

public static void main(String arg[])

int ch,data;

Scanner sc=new Scanner(System.in);

Mystack s=new Mystack();

do

System.out.println("\n1:Push");

System.out.println("2:Pop");
System.out.println("3:Peak.");

System.out.println("\nEnter your choice:");

ch=sc.nextInt();

switch(ch)
{

case 1:if(s.isfull()==1)

System.out.println("Stack is full");
}

else

System.out.println("Enter the data :"); data=sc.nextInt();

s.push(data);

break;

case 2:if(s.isempty()==1)

System.out.println("Stack is empty");
}

else

s.pop();

break;

case 3:System.exit(0);

break;

default:System.out.println("\nInvalid choice:");

}while(ch!=4);

}
ASSIGNMENT-19(PACKAGE)

1. Create a package named mathop. Define class MathsOperations


with static methods
to find the maximum and minimum of n numbers. Create another
package statop. Define class StatsOperations with methods to find the
average and median of n numbers. Import these packages to use the
above methods to perform above operations on n numbers.
Source Code:
Math op Package-
package mathop;

public class MathOperations{


public double max(double
arr[]){ double
temp=arr[0];
for(int
i=0;i<arr.length;i++)
{ if(temp<arr[i]){
temp=arr[i];
}
}
return temp;
}
public double min(double
arr[]){ double
temp=arr[0];
for(int
i=0;i<arr.length;i++)
{ if(temp>arr[i]){
temp=arr[i];
}
}
return temp;
}

}
Statop Package-

package statop;

public class StatsOperations{


public double avg(double
arr[]){ double sum=0;
double avg;
for(int
i=0;i<arr.length;i++)
{ sum+=arr[i];
}
avg=(double)sum/arr.lengt
h; return avg;
}

public double median(double


arr[]){ int n;
if(arr.length%2!=0){
n=(arr.length+1)/2;
}
else{
n=((arr.length/2)+(arr.length/2+1))
/2;
}
double med=arr[n-
1]; return med;
}

}
Main class-

import
mathop.MathOperations;
import
statop.StatsOperations;

class array{
public static void main(String args[])
{
double arr[]={1,2,3,4,5,6};
MathOperations ob=new
MathOperations(); StatsOperations
ob1=new StatsOperations();
System.out.println("Maximum value in array: "+
ob.max(arr)); System.out.println("Minimum value in array:
"+ ob.min(arr)); System.out.println("Average value in array:
"+ ob1.avg(arr)); System.out.println("Median value of
array: "+ ob1.median(arr));
}

}
2. Create a package called nodepack which contains the class “Node”.
Create
another
package called listpack which contains the class “LinkedList” representing
methods
to create a Single Linked list, Add a node to the list and traverse the list.
Write a menu
driven program in main to create a Single Linked list, Add nodes and
display the List.
The elements are passed as user input.
Source Code:
Node Pack:
package
nodepack; public
class Node{

public int data;


public Node
next; public
Node(int i){
data=i;
next=null
;
}

List Pack:
package listpack;
import
nodepack.Node;
public class LinkedList{
Node head;
public LinkedList insert(LinkedList list, int d)
{

Node n=new Node(d);


n.next=null;
if(list.head==null){
list.head=n;

}
else{
Node last=list.head;
while(last.next!=null
){
last=last.next;

}
last.next=n;
}
return list;

}
public void display(LinkedList
list){ Node
c_node=list.head;
System.out.println("Linked List:
"); while(c_node!=null){
System.out.print(c_node.data+" -> ");
c_node=c_node.next;
}
}

Main Class:

import nodepack.Node;
import
listpack.LinkedList;
import
java.util.Scanner; class
list{
public static void main(String arg[])
{

int ch,data;

Scanner sc=new
Scanner(System.in); LinkedList
ll=new LinkedList();
do
{

System.out.println("\n1:Insert");
System.out.println("2:Display");
System.out.println("3:Exit.");
System.out.println("\nEnter your
choice:");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter the data
:"); data=sc.nextInt();
ll=
ll.insert(ll,data);
break;
case
2:ll.display(
ll); break;
case
3:System.exit(
0); break;
default:System.out.println("\nInvalid choice:");
}
}while(ch!=4);
}

}
ASSIGNMENT-20(BUILT IN EXCEPTION)

1. Input two numbers as numerator and denominator for division. Write


a
program to show an ArithmeticException when the division is not
possible due to denominator is 0.
Source Code:
import
java.util.Scanner; class
a
{
public static void main(String k[])
{
try{
int numerator,denominator;
Scanner s=new
Scanner(System.in);
System.out.println("Enter 1st
number:"); numerator=s.nextInt();
System.out.println("Enter 2nd
number:"); denominator=s.nextInt();
System.out.println("Division:" +(numerator/denominator));
}
catch(Exception e)
{
System.out.println("AIRTHMETIC EXCEPTION!");
}
}
}
2. Define an array of size n and set some values to it. Show an
ArrayIndexOutOfBoundException when trying to access the index
that is more than size of the array.
Source Code:
import
java.util.Scanner; class
a
{
public static void main(String k[])
{
try{
int[]
c; int
n,i;
Scanner s=new Scanner(System.in);
System.out.println("Enter the size of
array:"); n=s.nextInt();
c=new int[n];
System.out.println("Enter the
elements:"); for(i=0;i<n;i++)
{
c[i]=s.nextInt();
}
System.out.println("Enter the index more than the
size:"); int d=s.nextInt();
System.out.println("Elements at index "+d+" = "+c[d-1]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundException!");
}
}
}
3. Write a program to show the use of NullPointerException
and NumberFormatException.
Source Code:
import
java.util.Scanner; class
a
{
public static void main(String k[])
{
try{
Scanner s=new
Scanner(System.in); int
n=Integer.parseInt(k[0]);
System.out.println(n);
String str=null;
System.out.println("Length of String is " +str.length());
}
catch(NumberFormatException e)
{
System.out.println("Number Format Exception!");
}
catch(NullPointerException npe)
{
System.out.println("NullPointerException!"
+npe.getMessage()); System.out.println("String is null!");
}
}
}
ASSIGNMENT-21(USER DEFINED EXCEPTION)

1.Define Exceptions VowelException, BlankException, ExitException


to restrict the input of vowel, space and „X‟. Write another class
TestException which reads a character from command line. If it is a
vowel, throw VowelException, if it is a blank space throw
BlankException and for a
character „X‟ throw an ExitException and terminate the program. For
any other character, display “Valid character”.
Source Code:
import java.lang.String;
class VowelException extends
Exception{ public String
toString(){
return "Vowel Exception";
}
}
class BlankException extends
Exception{ public String
toString(){
return "Blank Exception";
}

}
class ExitException extends
Exception{ public String
toString(){
return "Exit Exception";
}
}

class TestException{
static void display(char c)
throws
VowelException,BlankException,Exi
tException{

if(c=='a'||c=='e'||c=='i'||c=='o'||c=
='u'){ throw new
VowelException();
}
else if(c==' '){
throw new BlankException();
}
else if(c=='X'){
throw new ExitException();
}
else
{
System.out.println("Valid Character");

}
}
}

class Exceptions{
public static void main(String args[])
throws Exception{ try{
char c=args[0].charAt(0);
TestException t=new
TestException(); t.display(c);
}
catch(Exceptio
n e){
System.out.println("Exception: "+ e);
}

}
1. Write a program which accepts two integers and an arithmetic operator
from the command line and performs the operation. Check the following
user defined exceptions:
i.
If the number of arguments are less than 3 then
throw “FewArgumentsException”.
ii. If the operator is not an Arithmetic operator,
throw “InvalidOperatorException”.
iii. If result is –ve, then throw “NegativeResult” exception.
Source Code:

class

FewArgumentsExc

eption{ public

String toString(){

System.out.println("Few Arguments Exception");

class InvalidOperatorException

extends Exception{ public String

toString(){

System.out.println("Invalid Operator Exception");

}
}

class NegativeResult extends Exception{

public String toString(){

System.out.println("Negative Result

Exception");

class Operation{
static void calc(int a,char o,int b)throws
FewArgumentsException,InvalidOperatorException
,NegativeResult{

switch(o){

case '+':

System.out.println("Addition

: "+(a+b)); break;

case '-':

System.out.println("subtractio

n: "+(a-b)); break;

case '*':

System.out.println("subtraction

: "+(a*b)); break;

case '/':
{

System.out.println("Division:

"+(a/b)); break;

case '%':

System.out.println("subtraction

: "+(a%b)); break;
}

class exceptions2{

public static void

main(String args[]){

try{

int

a=Integer.parseInt(args

[0]); char

o=args[1].charAt(0);

int

b=Integer.parseInt(args[

2]); Operation op=new

Operation();

op.calc(a,o,b);

}
catch(Exception e){

System.out.println("Exception: "+e);

}
2.Create a class Student with attributes roll no, name, age and
course. Initialize values through parameterized constructor. If age of
student is not between 15 and 21 then generate user-defined
exception
“InvalidAgeException”. If name contains numbers or special
characters raise exception “InvalidNameException”. Define the two
exception classes. Source Code:

import java.util.*;

class InvalidAgeException extends

Exception{ public String

toString(){

return "Invalid Age Exception";

class InvalidNameException

extends Exception{ public

String toString(){

return "Invalid Name Exception";

class Student{
static int rollno,age;

static String name,course;

Student(int rn,String sname,int

sage,String scourse){ rollno=rn;

name=snam

e; age=sage;

course=scou

rse;

static void check()throws


InvalidAgeException,InvalidNameException{
if(age>21||15>age){

throw new InvalidAgeException();

else if(false){

throw new InvalidNameException();

else
{
System.out.println("Name:

"+name);

System.out.println("Roll No:

"+rollno);

System.out.println("Course:

}
"+course);
}
System.out.println("Agee:
}
"+age);

class Students{

public static void

main(String args[]){
int rn,sage;

String sname,scourse;

try{

Scanner sc=new

Scanner(System.in);

rn=sc.nextInt();

sage=sc.nextI

nt();

sname=sc.nex

t();

scourse=sc.ne

xt();

Student s=new

Student(rn,sname,sage,scourse);

s.check();
}

catch(Exception e){

System.out.println("Excepti

on: "+ e);

}
3.Define class MyDate with members day, month and year. Define
default and parameterized constructors. Accept values from the
command line and create a date object. Throw user defined
exceptions

“InvalidDayException” or “InvalidMonthException” if the day or
month are invalid. If the date is valid, display message “Valid Date”.
Source Code:

class InvalidDayException extends

Exception{ public String

toString(){

return "Invalid Day Exception";

class InvalidMonthException

extends Exception{ public

String toString(){

return "Invalid Month Exception";

class MyDate{
static int

day,month;

MyDate(int day, int

month){ day =day;

month=month;

static void
datecheck()throws
InvalidMonthException,InvalidDa
yException{

if(day<0||day>31){

throw new InvalidDayException();


}

else if(month<0||month>12){

throw new InvalidMonthException();

else
{
System.out.println("Valid Date");

class MyDates{

public static void

main(String args[]){ try{

int

day=Integer.parseInt(args[

0]); int

month=Integer.parseInt(ar

gs[1]);

MyDate md=new
MyDate(day,month);

md.datecheck();

catch(Exception e){

System.out.println("Exception: "+e);

}
ASSIGNMENT-22(FILE READ & WRITE)

Q1.Write a program in Java to show read and write


operations in a text file. Create a file Student to store the record such as roll no and name of any
student. Also write a complete program to write records into the file, read all records from the
file, Search a record from the file.
Source Code:-
import java.util.Scanner; import
java.io.*;
class Student
{
public static void main(String k[]) throws Exception
{
Scanner s=new Scanner(System.in);
System.out.println("Enter how many entry you want to made:"); int n=s.nextInt();
int roll[]=new int[n];
String name[]=new String[n]; for(int i=0;i<n;i++)
{
System.out.println("Enter the details of " +(i+1) +" students:-"); System.out.print("Enter Roll
No:- ");
roll[i]=s.nextInt(); System.out.print("Enter Name:-
"); name[i]=s.next();
}
FileWriterw=new FileWriter("C:/Users/hp/Desktop/JAVA/Assignment-
22/record.txt");
w.write("STUDENT RECORD\n"); w.write(" \n");
w.write("ROLL NO\tNAME \n"); for(int
i=0;i<n;i++)
{
w.write(roll[i]+ "\t" +name[i] +"\n");
}
w.close();
String f="C:/Users/hp/Desktop/JAVA/Assignment-22/record.txt"; BufferedReader b=new
BufferedReader(new FileReader(f)); String str;
while((str=b.readLine())!=null)
System.out.println(str);
b.close();
System.out.println("Enter roll number you want to search from file: ");
String search=s.next();
Scanner scan=newScanner(new File("C:/Users/hp/Desktop/JAVA/Assignment-
22/record.txt")); while(scan.hasNext())
{
String line=scan.nextLine().toLowerCase().toString(); if(line.contains(search))
{
System.out.println(line);
}
}
}
}

You might also like