You are on page 1of 77

INDEX

PART:I
Function Overloading
1.
2.
3.
4.
5.
PART :II
Methods and Functions
1.
2.
3.
4.
5.
PART :III
Arrays in decision making
1.
2.
3.
4.
5.
PART :IV
Concept of Arrays
1.

2.
3.
4.
5.

PART :V
Menu driven programs
1.
2.
3.
4.
5.
PART :VI
Printing patterns
1.
2.
3.
4.
5.
PART :VII
Library classes
1.
2.
3.
4.
5.

Program1 :
Write a program to represent Bank Account. Include the following members :
Data Members
1 Name of The Depositor
2 Type of Account
3 Account number
4 Balance Amount in the account
Methods
1

To assign initial values

2 To Withdraw an amount after checking Balance


3 To display the name and balance
4 To deposit an amount
5 Do write proper constructor functions

package Constructors;
class BankAccount {
private String DepositorName;
private long AccountNumber;
private String AccountType;

private double BalanceAmount;


publicBankAccount() {
DepositorName=" ";
AccountNumber =0; AccountType = " ";
BalanceAmount= -1;}
publicBankAccount(String dName, long accno, String accType, double balAmount){
DepositorName=dName;
AccountNumber =accno; AccountType = accType;
BalanceAmount= balAmount;}
public void initialise (String dName, long accno, String accType,doublebalAmount){
DepositorName=dName;
AccountNumber =accno; AccountType = accType;
BalanceAmount= balAmount;}
public void display(){
System.out.println("Depositor name : " +DepositorName);
System.out.println("Account Number : " +AccountNumber);
System.out.println("Account Type : " +AccountType);
System.out.println(" Balance Amount :" +BalanceAmount);}
public void deposit(double amount){
BalanceAmount += amount;}
public void withdraw(double amount){
if(amount<=BalanceAmount)
BalanceAmount-=amount;}
public static void main(){
BankAccount acc1 = new BankAccount();
acc1.initialise("Chetan" , 31290, "Saving" , 8000);
BankAccount acc2 = new BankAccount("Ronald" , 41777, "current" , 70000 );

acc1.deposit(17000);
acc1.display();
acc2.withdraw(20000);
acc2.display();}}

Output :
Depositor name :Chetan
Account Number : 31290
Account Type : Saving
Balance Amount :25000.0
Depositor name : Ronald
Account Number : 41777
Account Type : current
Balance Amount :50000.0
Program 2
Write a program of class employee having the following description :
Data Members
1

Int pan

to store personal Account number

Instance variable
1

String name

To store name

2 Double Tax income


3 Double tax

To store annual Taxable income


To store tax that is calculated

Member Functions
1

Input()

To store pan number,name,taxable income

2 Calc()

To calculate tax for an employee

3 Display()

Output Details for an Employee

Write a Program to compute the tax according to the given condition and display the output
as per given format.
Total Annual taxable income

Tax rate

Upto Rs. 100000

No Tax

From 100001 to 150000

10% of the income


Exceeding 100000

From 150001 to 250000

Rs.5000+20% of the
Income exceeding
Rs.150000

Above 250000

25000+30% of the income


Exceeding 250000

package ClassAsA_userDefined;
import java.io.*;
public class Employee{
int pan;
String name;
doubletaxIncome;
double tax;
public void input()throws IOException {
BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter pan number");
pan=Integer.parseInt(br.readLine());
System.out.println("Enter name ");
name=br.readLine();
System.out.println("Enter taxable income ");
taxIncome=Double.parseDouble(br.readLine());}

public void calc(){


tax=0;
if(taxIncome<=100000)
tax=0;
else if(taxIncome<=150000)
tax=0.10*(taxIncome-100000);
else if(taxIncome<=250000)
tax=0.20*(taxIncome-150000)+50000;
else
tax=0.30*(taxIncome-250000)+25000;}
public void display(){
System.out.println("Pan Number\t Name \t Tax-incom\t Tax");
System.out.println(""+pan+"\t "+name+ "\t "+taxIncome+ "\t "+tax);}
public static void main(String[] args)throws IOException{
Employee empl=new Employee();
empl.input();
empl.calc();
empl.display();}}
OUTPUT
Enter pan number
1234
Enter name
DARSHAN
Enter taxable income
150000
Pan Number Name
1234

Tax-incom

DARSHAN 150000.0

Tax

5000.0

Program 3
Write a program of class student described as below :
Data members /instance variables
1)name,age,m1,m2,m3(marks in 3 subjects),maximum,average
Member methods:
1)a parameterized constructor to initialize the data members
2)to accept the details of a student
3)to compute the average and maximumout of three marks
4)to display the name,age,marks in 3 subjects,maximum and average
Write a main method to create an object of a class and call the above member methods

packageClassAsA_userDefined;
import java.io.*;
public class Student
{String name;
int age;
double m1,m2,m3,maximum,average;
public Student(){}
public Student(String nm,intag,double mk1,double mk2, double mk3){
name=nm;
age=ag;
m1=mk1;
m2=mk2;
m3=mk3;
maximum=0;
average=0; }
public void accept()throws IOException{

BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter name:");
name=br.readLine();
System.out.println("Enter age");
age=Integer.parseInt(br.readLine());
System.out.println("Enter marks in subject 1 :");
m1=Double.parseDouble(br.readLine());
System.out.println("Enter marks in subject 2 :");
m2=Double.parseDouble(br.readLine());
System.out.println("Enter marks in subject 3 :");
m3=Double.parseDouble(br.readLine());}
voidcalcMax_Avg(){
maximum=Math.max(m3,Math.max(m1,m2));
double total =m1+m2+m3;
average=total/3;}
voiddispResults(){
calcMax_Avg();
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("Marks in subject 1,2,3 are : "+m1+,+m2+,+m3);
System.out.println("Maximum marks : "+maximum);
System.out.println("Average marks : "+average);}
public static void main()throws IOException{
Student s1=new Student();
s1.accept();
s1.dispResults();}}
OUTPUT

Enter name:
Darshan
Enter age
14
Enter marks in subject 1 :
95
Enter marks in subject 2 :
98
Enter marks in subject 3 :
100
Name: Darshan
Age: 14
Marks in subject 1,2,3 are: 95.0, 98.0, 100.0
Maximum marks : 100.0
Average marks : 97.66666666666667
Program 4
An electronic shop has announced the following seasonal discounts on the purchase of certain
items.
Purchase amt.in$ discount on laptops
0-25000

0.0%

25001-57000

5.0%

57001-100000

7.5%

More than 100000 10.0%

Discount on Desktop Pc
5.0%

7.5%
10.0%
15.0%

Write a program based on the above criteria,to input name,address,amount of purchase and the
type of the purchase(l-laptop,d-desktop)By a customer.compute and print the net amount to be
paid by a customer along with his name & address.
[Hint:Discount =(Discount rate/100)*amount of purchase

Netamount=amount of purchase-discount.

import java.io.*;
public class Electronics{
String name;
doublepurchaseAmount;
double net;
double discount;
chartypeOfPurchase;
int L , D;
public void input()

throws IOException{

BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter name : ");
name = br.readLine();
System.out.println("Enter amount : ");
purchaseAmount = Double.parseDouble(br.readLine());
System.out.println("Enter type of purchase : L , D : ");
String dummy = br.readLine();
typeOfPurchase = dummy.charAt(0);}
public void calcDiscount() {
doublediscRate = 0;
switch (typeOfPurchase ) {
case 'L' : if(purchaseAmount<25000)
discRate = 0;
else if(purchaseAmount<=50000)
discRate = 5.0;

else if(purchaseAmount<=100000)
discRate= 7.5;
else
discRate = 10.0;
break;
case 'D' :if (purchaseAmount<25000)
discRate = 5.0;
else if(purchaseAmount<50000)
discRate = 7.5;
else if(purchaseAmount<70000)
discRate = 10.0;
else
discRate = 15.0;
break;}
discount = discRate /100 * purchaseAmount;
net = purchaseAmount - discount;}
void display(){
System.out.println("The name is " + name);
System.out.println("The amount is " + purchaseAmount);
System.out.println("The netAmount is " + net);}
public static void main() throws IOException{
Electronics el = new Electronics();
el.input();
el.calcDiscount();
el.display();}}
OUTPUT :
Enter name :

Sankalp
Enter amount :
70000
Enter type of purchase : L , D :
D
The name is Sankalp
The amount is 70000.0
The netAmount is 59500.0
Program 5
bob travels Pvt.Ltd Gives the following Discount to its customer:
Ticket amount

discount

Above 70000

18.0%

55001 to 70000

16.0%

35001 to 55000

12.0%

25001 to 35000

10.0%

Less than 25001

2.0%

WAP to input the name & ticket amount for the customer & calculate the discount Amount& the
Netamount to be paid.

importjava.util.*;
class travel{
String name[];
doubleticamt[], discount[], netamt[];
void input (){
name=new String[3];
ticamt=new double[3];

discount=new double[3];
netamt=new double[3];
Scanner kb=new Scanner(System.in);
for(int i=0; i<3;i++){
System.out.println("Name: ");
name[i]=kb.next();
System.out.println("Ticket amount:");
ticamt[i]=kb.nextDouble();
if (ticamt[i]>70000)
discount[i]=0.18*ticamt[i];
else if(ticamt[i] > 5000)
discount[i]=0.16*ticamt[i];
else if(ticamt[i]>35000)
discount[i]=0.12*ticamt[i];
else if (ticamt[i]>25000)
discount[i]=0.10*ticamt[i];
else
discount[i]=0.02*ticamt[i];
netamt[i]=ticamt[i]-discount[i];}}
void display(){
System.out.println("sl.no \t name \t ticket charges \t discount \t net amount");
for(int i=0;i<3;i++){
System.out.println((i+1)+"\t"+name[i]+"\t"+ticamt[i]+"\t"+discount[i]+"\t"+netamt[i]);}}
public static void main(){
travelob=new travel();
ob.input();
ob.display();}}

OUTPUT
Name:
Shashank
Ticket amount:
15000
Name:
Sankalp
Ticket amount:
12000
Name:
Vignesh
Ticket amount:
10000
sl.no

name

ticket charges

discount

Shashank15000.0

Sankalp

12000.0

1920.0

Vignesh

10000.0

1600.0

2400.0

net amount

12600.0
10080.0
8400.0

Program 6
WAP using a function called area () to compute the area of a:
(i)circle(pi*r*r)Where pi =3.14
(ii)Square(s*s)
(iii)Rectangle(l*b)
Display the menu to output the area as per user choice.

import java.io.*;
class Areas{
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));

public static void area(float radius) {


double res=0.0;
res=3.14*radius*radius;
System.out.println("Area of Circle :"+res); }
public void area(double side) {
double res=0.0;
res=side*side;
System.out.println("Area of Square :"+res); }
public void area(double len,doublebr) {
double res=0.0;
res=len*br;
System.out.println("Area of Rectangle :"+res); }
public void display()throws IOException {
System.out.println("ENTER CHOICE TO CALCULATE THE AREA OF:");
System.out.println("1) Circle");
System.out.println("2) Square");
System.out.println("3) Rectangle");
intch;
ch=Integer.parseInt(br.readLine());
getChoice(ch);}
public void getChoice(intch){
switch(ch){
case 1:float r=3.5f;
System.out.println("Calculating Area of Circle with radius 3.5");
area(r);
break;
case 2:double s=4.5;

System.out.println("Calculating Area of Square with side 4.5");


area(s);
break;
case 3:double l=4.5,b=3.5;
System.out.println("Calculating Area of Rectangle with length 4.5 and breadth 3.5");
area(l,b);
break;
default:System.out.println("Invalid Option");} }
public static void main()throws IOException{
Areas ar=new Areas();
ar.display(); }}
OUTPUT
ENTER CHOICE TO CALCULATE THE AREA OF:
1) Circle
2) Square
3) Rectangle
1
Calculating Area of Circle with radius 3.5
Area of Circle :38.465
Program 7
Define a class called mobike with the following description :
Instance Variables/data members :
Int bno

To store the bikes number

Int phno

To store the phone number of the customer

String name

To store the name of the customer

Int days

To store the number of days the bike was taken on rent

Int charge

To calculate and store the rental charge

MEMBER METHOD :
Void input()

Void compute()

To input and store the details of the customer


To compute the rental charge.

The rent for a mobike is charged on the following basis :


First five days

Rs.500 per day

Next five days

Rs. 400 per day

Rest of the days

Rs.200 per day

Void display()

to display the details in the foloeing format

Bike No.

Phone No.

______

_______

Name

No.of days
______

Charge

________

________

import java.io.*;
public class mobike{
intbno;
longphno;
String name;
int days;
int charge;
void input()

throws IOException{

BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter bike's number :");
bno = Integer.parseInt(br.readLine());
System.out.println("Eenter phone number of the customer:");

phno = Long.parseLong(br.readLine());
System.out.println("Enter name of the customer :");
name = br.readLine();
System.out.println("Enter number of days bike is taken on rent :");
days = Integer.parseInt(br.readLine());}
void compute(){
int temp;
if(days<5)
charge = days*500;
else if(days < 10){
temp = days - 5;
charge = temp *400 + (5*500);}
else
charge = (days -10) * 200 + (5 *400) + (5 * 500);}
void display(){
System.out.println("Bike no. \t Phone No. \t Name \t No.of Days \t Charge");
System.out.println(bno + "\t" + phno + "\t" + name + "\t" + days + "\t" + charge);}
public static void main() throws IOException{
mobikemb = new mobike();
mb.input();
mb.compute();
mb.display();}}
Output
Enter bike's number :
6789
Enter phone number of the customer:
9876543210

Enter name of the customer :


Sankalp
Enter number of days bike is taken on rent :
50
Bike no.

Phone No.

Name

6789 9876543210Sankalp

No.of Days
50

Charge

12500

Program 8
Write a program to input a number and print whether the number is a special number or not. (A
number is said to be a special number if the sum of the factorial of the digits of the number is
same as the original number).
Example: 145 is a special number, because 1! +4! +5! =1+24+120=145.

import java.io.*;
class Special{
public double fact(int x){
int i;
double f=1;
for(i=1;i<=x;i++){
f=f*i;}
return f;}
public static void main()throws IOException{
Special ob=new Special();
double r=0,n,s=0;
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter A Number");
int a=Integer.parseInt(br.readLine());

n=a;
while(a>0){
int k=a%10;
r=ob.fact(k);
s=s+r;
a=a/10;}
if(s==n)
System.out.println("Special Number");
else
System.out.println("Not a Special Number");}}
OUTPUT
Enter A Number
145
Special Number
Program 9
Write a menu Driven class to accept a number from the user & check whether number is
palindrome or perfect number.
(a)Palindrome number-a number is palindrome when read in reverse order is same as read in the
right order.
(b)Perfect number-a number is called perfect if it is equal to its factors other than the number
itself.

importjava.util.*;
public class number{
staticintnum;
public static boolean palindrome(intnum){
int num2=num;

intdig,q,rnum=0;
while(num2>0){
q=num2/10;
dig=num2%10;
rnum=rnum*10+dig;
num2=q;}
if (rnum==num)
return true;
else
return false;}
public static booleanPerfectTest(intnum){
int n=2,lim=num/2,sum=1;
for(n=2;n<=lim;n++){
if (num%n==0)
sum=sum+n;}
if (sum==num)
return true;
else
return false;}
public static void main(){
number2 n=new number2();
Scanner kb=new Scanner (System.in);
System.out.println("enter a number");
num=kb.nextInt();
System.out.println("menu");
System.out.println("1.palindrome number");
System.out.println("2.perfect number");

System.out.println("enter your choice(1/2)");


int choice=kb.nextInt();
if (choice==1)
if(palindrome (num)==true)
System.out.println(num+" IS a palindrome number.");
else
System.out.println(num+" IS not a palindrome number.");
else if (choice==2)
if (PerfectTest(num)==true)
System.out.println(num+" IS a perfect number.");
else
System.out.println(num + " IS not a perfect number");
else
System.out.println("wrong choice");}}
Output
enter a number
121
menu
1.palindrome number
2.perfect number
enter your choice(1/2)
1
121 IS a palindrome number.
Output 2
enter a number
6
menu

1.palindrome number
2.perfect number
enter your choice(1/2)
2
6 IS a perfect number.

Program 10
Write a program to input any given string to calculate the total number of characters and
vowels in the string and also reverse the string:
INPUT:-

Enter string

:SNOWY

OUTPUT:- Total number of character :05


Number of vowels
Reversed String

:01
:YWONS

classStringProcessing{
private String data;
publicStringProcessing(String str){
data=str;}
public void calculate(){
intnumberCharacters=data.length();
System.out.println("Number of Characters : " +numberCharacters+ "\n");
intnumberVowels=0;
char character;
for(int counter=0; counter<numberCharacters; counter++){
character=data.charAt(counter);
switch(character){
case 'a':case 'A':case 'e':case 'E':case 'i':case 'I':case 'o':case 'O':

case 'u':
case 'U':
numberVowels++;}}
System.out.println("Number of vowels : " +numberVowels+ "\n");
StringBufferrevStr= new StringBuffer(data);
revStr.reverse();
System.out.println("ReversedString : " +revStr+ "\n");}
public static void main(){
StringProcessingst = new StringProcessing("SNOWY");
st.calculate();}}
Output
Number of Characters : 5
Number of vowels : 1
ReversedString : YWONS

Program 11
Write a program to input store the weight of ten people .Sort and display them in
descending order using the selection sort technique.

import java.io.*;
class weight
{public void input(int w[]){
inttmp,i,j,small,pos;
for (i=0;i<w.length;i++)
{small=w[i];
pos=i;
for(j=i+1;j<=9;j++){

if(w[j]>small){
small=w[j];
pos=j;}}
tmp=w[i];
w[i]=w[pos];
w[pos]=tmp;}
for(int k=0;k<10;k++){
System.out.println(w[k]+"\t");}}
public static void main()throws IOException{
weightob=new weight();
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
int we[]=new int[10];
System.out.println("Enter Weights OF Ten People");
for(int a=0;a<10;a++)
we[a]=Integer.parseInt(br.readLine());
ob.input(we);}}
OUTPUT
Enter Weights OF Ten People
25
24
26
23
27
54
98
54
65

47
Array in Descending Order
98
65
54
54
47
27
26
25
24
23
Program 12
The annual examination results of 50 students in a class is tabulated as follows :
Roll no

subject

subject b

subject c
---------

-------------

------------

--------------

write a program to read the data , calculate the display the following
(a) Average mark obtained by each student.
(b) Print the roll number and average marks of the student whose average mark is
above 80.
(c) Print the roll number and average marks of the student whose average mark is
above 40.

package arrays;
import java.io.*;
class Result{

intRollno[];
doubleSubjectA[],SubjectB[],SubjectC[],Avg[];
void input()throws IOException{
Rollno=new int[3];
SubjectA=new double[3];
SubjectB=new double[3];
SubjectC=new double[3];
Avg=new double[3];
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<3;i++){
System.out.println("Roll no:");
Rollno[i]=Integer.parseInt(br.readLine());
System.out.println("Marks in subkect A:");
SubjectA[i]=Integer.parseInt(br.readLine());
System.out.println("Marks in subject B:");
SubjectB[i]=Integer.parseInt(br.readLine());
System.out.println("Marks in subject C:");
SubjectC[i]=Integer.parseInt(br.readLine());
Avg[i]=(SubjectA[i]+SubjectB[i]+SubjectC[i])/3;}}
void display(){
System.out.println("Average marks of all students");
System.out.println("Roll no \t Average");
for (int i=0;i<3;i++){
System.out.println(Rollno[i]+"\t"+Avg[i]);}
System.out.println("Average marks of students with average >80");
System.out.println("Rollno \t Average");
for(int i=0;i<3;i++){

if(Avg[i]>80)
System.out.println(Rollno[i]+"\t"+Avg[i]);}
System.out.println("Average marks of students with avarage<40");
System.out.println("Rollno \t Average");
for(int i=0;i<3;i++){
if(Avg[i]<40)
System.out.println(Rollno[i]+"\t"+Avg[i]);}}
public static void main()throws IOException{
Result ob=new Result();
ob.input ();
ob.display();}}
OUTPUT
Roll no:
12
Marks in subject A:
78
Marks in subject B:
98
Marks in subject C:
87
Roll no:
123
Marks in subject A:
45
Marks in subject B:
65
Marks in subject C:

66
Roll no:
1234
Marks in subject A:
78
Marks in subject B:
98
Marks in subject C:
68
Average marks of all students
Roll no

Average

112

87.66666666666667

123

58.666666666666664

1234 81.33333333333333
Average marks of students with average >80
Rollno Average
112

87.66666666666667

1234 81.33333333333333
Average marks of students with average<40

Program 13
Write a program to initialize an array of 5 names and initialize another array with their
respective telephone names. Search for the name input by the user, in the list. If found, display
Search Successful and print the name along with the telephone number, otherwise display
Search Unsuccessful. Name not enlisted.

import java.io.*;
public class Details{
String name[];
long[] ph;
Details(String n[],long p[]){
name=new String[5];
ph=new long[5];
for(int i=0;i<5;i++){
name[i]=n[i];
ph[i]=p[i];}}
public void Search(String nm){
int i;
for(i=0;i<5;i++){
if(name[i].equals(nm)==true){
System.out.println("Serch Successful");
System.out.println("Name:"+name[i]+",phone:"+ph[i]);}}
if(i==5)
System.out.println("Search unsuccessful .Name not enlisted");}
public static void main()throws IOException{
String n1[]=new String[5];
String n2;
longph[]=new long[5];
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<5;i++){
System.out.println("Enter your name");
n1[i]=br.readLine();
System.out.println("Enter your Phone no");

ph[i]=Long.parseLong(br.readLine());}
System.out.println("Enter your Serch name");
n2=br.readLine();
Details ob=new Details(n1,ph);
ob.Search(n2);}}
OUTPUT
Enter your name
varun
Enter your Phone no
123456789
Enter your name
darshan
Enter your Phone no
456789123
Enter your name
shankalp
Enter your Phone no
789456123
Enter your name
iqbal
Enter your Phone no
7891321456
Enter your name
Shashank
Enter your Phone no
78945261234
Enter your Serch name

Shashank
Search successful
Name:Shashank Phone:78945261234

Program 14
Define a class and stores the given city names in single dimensional array. Sort these names in
alphabetical order using the bubble sort technique only.
Input : Delhi, Bangalore , Agra , Mumbai , Calcutta.
Output: Agra , Bangalore , Calcutta , Delhi , Mumbai.

public class SortNames{


public static void main(){
String [] names = new String[]{"Delhi","Bangalore","Agra","Mumbai","Calcutta"};
inti,j;
String temp = "";
for(i=0;i<5;i++)
for(j= 0;j<5 - 1;j++){
if(names[j].compareTo(names[j+1])>0){
temp = names[j];
names[j] = names[j+1];
names[j+1] = temp;}}
System.out.println("Sorted array is : ");
for (i = 0;i<5;i++)
System.out.println(names[i]);}}
OUTPUT :
Sorted array is :

Agra
Bangalore
Calcutta
Delhi
Mumbai
Program 15
Write a program that asks the user to enter the size of the array first and then lets the
user enter the elements of the array in ascending order. Then it should ask the user to
specify a search item(key) and perform binary- search on the array

package Arrays;
import java.io.*;
public class ArrayOperation1{
public static void main(){
int length=0;
int key=0;
String inpStr=null;
BufferedReaderinbuf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the size of the array? ");
try{
inpStr=inbuf.readLine();
length=Integer.parseInt(inpStr);}
catch(Exception e){
System.out.println("Error in entering size of array!! ");
System.out.println("Exception :" +e);
return;}
int[]arr=new int[length];

System.out.println("Enter elements of array in SORTED order,otherwise the program shall not


work properly.");
try{
for(int i=0;i<arr.length;i++){
inpStr=inbuf.readLine();
arr[i]=Integer.parseInt(inpStr);}}
catch(Exception e){
System.out.println("Error in entering size of array!! ");
System.out.println("Exception :" +e);
return;}
System.out.println("Enter the elements to be searched for? ");
try{
inpStr=inbuf.readLine();
key=Integer.parseInt(inpStr);}
catch(Exception e){
System.out.println("Error in entering size of array!! ");
System.out.println("Exception :" +e);
return;}
int res=binarySearch(arr,key);
if(res==-1)
System.out.println("Element not found,Search Unsuccessful!!");
else
System.out.println("Element found at position " +(res+1));}
public static intbinarySearch(int[]a,int key){
int left=0;
int right=a.length-1;
int middle;

while(left<=right){
middle=(left+right)/2;
if(key==a[middle])
return middle;
else if(key<a[middle])
right=middle-1;
else
left=middle+1;}
return-1;}}
OUTPUT
What is the size of the array?
6
Enter elements of array in SORTED order,otherwise the program shall not work properly.
1
2
3
4
5
6
Enter the elements to be searched for?
3
Element found at position 3

Program 16

Write a program to input a string and print out the text with the uppercase and
lowercase letters reversed but all all other characters should remain the same as
before .
import java.io.*;

public class theString


{
public static void main()throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter string");
String str = br.readLine();
StringBuffer nstr =new StringBuffer(str);
Character ch1=' ';
for(int i=0;i<str.length();i++)
{
ch1= nstr.charAt(i);
if(ch1.isUpperCase(ch1))
nstr.setCharAt(i, ch1.toLowerCase(ch1));
else
nstr.setCharAt (i,ch1.toUpperCase(ch1));
}
System.out.println(nstr);
}
}
Output

Enter string
WelComE To School
wELcOME tO sCHOOL

PROGRAM 17:
Write a program that encodes a word into Piglatin. To translate word into a piglatin word,
convert the word into uppercase and then place the first vowel of the original word as the start
of the new word along with the remaining alphabets. The alphabets present before the vowel
being shifted towards the end followed byAY
import java .io.*;
class piglatin
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a word");
String s=br.readLine();
int x,y;
String c,d;
char b;
s=s.toUpperCase();
x=s.length();
System.out.println("The Piglatin word of the given String is ");
for(y=0;y<x;y++)
{
b=s.charAt(y);

if(b=='A'||b=='E'||b=='I'||b=='O'||b=='U')
break;
}
c=s.substring(y,x);
d=s.substring(0,y);
System.out.println(c+d+"AY");
}
}

Program:18
Write a program to accept a string .Convert the string to uppercase.Count and output the
number of double letter sequences that exist in the string.
Sample Input: SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE.
Sample output: 4.
Answer:
import java.util.Scanner;
public class ans6
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);

System.out.println("Please enter a String:");


String str = kb.nextLine();
str = str.toUpperCase();
int len = str.length();
char c,d;
int count = 0;
for (int i = 0;i<=len-2;i++)
{
c = str.charAt(i);
d = str.charAt(i+1);
if(c==d)
{
count = count+1;
}
}
System.out.println("Number of double letter sequences:"+count);
}
}
Output:
Please enter a String:
SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE
Number of double letter sequences:4

Program 19:

Design a class to overload a function polygon() as follows:


i.

Void polygon(int n,char ch) with one integer argument and one charcter type
argumentthat
draws a filled square of sides n using the charcter
stored in ch

ii.

Void polygon (int x,int y) with two integer arguments that draws a filled rectangle side
of
length x and breadth y using the symbol @

iii.

Void polygon () with no arguments that draws a filled triangle shown below.

Example:
i.

Input value of n=2,ch=O


Output:

OO
OO

ii.

Input value of x=2 and y=5


Output: @@@@@
@@@@@

iii.

Output:
*
**
***

SOLUTION:

package Question_2012;

public class Q19


{
public void polygon(int n,char ch)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
System.out.print(ch);
}
System.out.println();
}}
public void polygon(int x,int y)
{
for(int i=1;i<=x;i++)
{
for(int j=1;j<=y;j++)
{
System.out.print("@");
}
System.out.println();}}
public void polygon()
{
for(int i=1;i<=3;i++)
{

for(int j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}
public static void main()
{
Q19 o=new Q19();
o.polygon(2,'O');
o.polygon(2,5);
o.polygon();
}
}
OUTPUT:
OO
OO
@@@@@
@@@@@
*
**
***
Program 20:
Using the switch statement,write a menu driven program to

i.

Generate and display the first 10 of the Fibonacci series 0,1,1,2,3,5.


The first 2 Fibonacci numbers are 0 and 1 and each subsequent number is the sum of
previous two.

ii.

Find the sum of the digits of an integer that is input.


Sample input :

15390

Sample output:

sum of digits = 18

For an incorrect choice ,an appropriate error message should be displayed

Solution
import java.io.*;
class Q20
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int choice,i,a=0,b=1,c;
int n,digit,sum=0;
System.out.println("Menu:1.Fibonacci Series 2.Sum of Factors");
System.out.println("Enter Your Choice 1 or 2");
choice=Integer.parseInt(br.readLine());
switch(choice)
{
case 1:
System.out.print(a+","+b+",");
for(i=1;i<=8;i++)

{
c=a+b;
a=b;
b=c;
System.out.print(c);
if(i<8)
System.out.print(",");
}
break;
case 2:
System.out.println("Enter Number For Sum of Digits");
n=Integer.parseInt(br.readLine());
while(n>0)
{
digit=n%10;
sum+=digit;
n=n/10;
}
System.out.println(sum);
break;
default:System.out.println("Invalid Output");
}
}
}
Output

Menu:1.Fibonacci Series 2.Sum of Factors


Enter Your Choice 1 or 2
2
Enter Number For Sum of Digits
45
9

Program 21:
Define a class called Library with the following description:
Instance variable/date members:
Int acc_num

String title
String author

stores the accession number of the book


-

stores the title of the book

stores the name of the author of the book

Member Methods:
i.

Void input()- to input and store accession number,title and author

ii.

Void compute()- to accept the number of days late.Calculate and display the fine.

iii.

Void display()- to display the details in the following format

Accession number

Title

Author

Write a main method to create an object of a class and call the above member methods

SOLUTION
Import java.io.*;
public class Library

{
int acc_num;
String title,author;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void input()throws IOException
{
System.out.println("Enter Accession number");
acc_num=Integer.parseInt(br.readLine());
System.out.println("Enter Title");
title=br.readLine();
System.out.println("Enter Author");
author=br.readLine();
}
public void compute()throws IOException
{
System.out.println("Enter Number of Days Late");
int n=Integer.parseInt(br.readLine());
System.out.println("Late Fine=Rs"+n*2);
}
public void display()
{
System.out.println(" Accession number"+"\t"+"Title"+"\t"+"Author");
System.out.println("____________________"+"\t"+"________"+"\t"+"_______");
System.out.println(acc_num+""+"\t"+title+"\t"+author);
}

public static void main()throws IOException


{
Library ob=new Library ();
ob.input();
ob.compute();
ob.display();
}
}
OUTPUT
Enter Accession number
4209
Enter Title
Computer Applications
Enter Author
Sumita Arora
Enter Number of Days Late
9
Late Fine=Rs18
Accession number

Title

____________________
4209

Author
________ _______

Computer Applications

Sumita Arora

Program 22:
write a program to print the following pattern in separate methods
i)
*
*#
*#*#
*#*#*#
*#*#*#*#
ii)
54321

5432

543

54

5
Solution:
public class Q22
{
public void star()
{
System.out.print("*");
int i,j;
for(i=1;i<5;i++)
{

System.out.println();
for(j=1;j<=i;++j)
System.out.print("*#");
}
System.out.println();
}
public void num()
{
int i,j;
for(i=1;i<=5;++i)
{
System.out.println();
for(j=5;j>=i;--j)
System.out.print(j);
}
}
public static void main()
{
Q22 ob=new Q22 ();
ob.star();
ob.num();
}
}
Output:*

*#

*#*#

*#*#*#

*#*#*#*#

54321
5432
543
54
5

Program 23:
write a program to display the given pattern
a

aa

aaa

aaaa

aaaaa

aaaa

aaa

aa

Solution
public class Special
{
public static void main(String args[])
{
int i,j,m,k;
m=5;
for(i=1;i<=5;i++)
{
for(j=1;j<=m;j++)
System.out.print(" ");
for(k=1;k<=i;k++)
System.out.print(" "+"a");
System.out.println();
m=m-1;

}
m=2;
for(i=4;i>=1;i--)

for(j=1;j<=m;j++)
System.out.print(" ");
for(k=1;k<=i;k++)
System.out.print(" "+"a");
System.out.println();
m=m+1;

}
}
}
output:a

aa

aaa

aaaa

aaaaa

aaaa

aaa

aa

Program 24:
Using switch statement, write a menu driven program to calculate the maturity amount of a
bank deposit.
The user is given the following options:
(1) Term deposit
(2) Recurring deposit
For option (1) accept principal (p),rate of interest (r),and time period in years (t). calculate
and output the maturity amount (a) receivable using the formula:
a=p*(1+r/100)n .
For option (2) accept the monthly installment (p) , rate of interest(r) and time period in
months (n). calculate and output the maturity amount (a) receivable using formula:
a=p*n+p*n(n+1)/2*r/100*1/12.
For incorrect option, an appropriate error message should be displayed.

import java.io.*;
public class bank
{
public static void sampleMethod() throws IOException

{
double p,a=0,r,n,x;int choice;
BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
System.out.println(" Enter choice: ");
System.out.println("1) Term deposit ");
System.out.println("2) Recurring deposit ");
choice=Integer.parseInt(ob.readLine());
switch(choice)
{
case 1:
System.out.println(" enter principal ");
p=Double.parseDouble(ob.readLine());
System.out.println(" enter rate of interest ");
r=Double.parseDouble(ob.readLine());
System.out.println(" enter time period in years ");
n=Double.parseDouble(ob.readLine());
x=1.0+r/100.0;
a=p*(Math.pow(x,n));
break;
case 2:
System.out.println(" enter monthly instalment ");
p=Double.parseDouble(ob.readLine());
System.out.println(" enter rate of interest ");
r=Double.parseDouble(ob.readLine());
System.out.println(" enter time period in months ");

n=Double.parseDouble(ob.readLine());
x=p*n;
a=x+p*(n*(n+1)/2.0)*(r/100.0)*(1.0/12.0);
break;
default:
System.out.println(" invalid input ");
}
System.out.print(" amount = Rs."+a);
}
}

o/p:
Enter choice:
1) Term deposit
2) Recurring deposit
1
enter principal
100
enter rate of interest
5
enter time period in years
2
amount = Rs.110.25

o/p2:
Enter choice:
1) Term deposit
2) Recurring deposit
2
enter monthly instalment
100
enter rate of interest
5
enter time period in months
5
amount = Rs.506.25

Program 25:
A special two-digit number is such that when the sum of its digits is added to the product of its
digits , the result is equal to the original two digit number .
Write a program to accept a two-digit number. Add the sum of its digits to the product of its
digits. If the value is equal to the number input , output the message Special 2-digit otherwise the output message not a special 2-digit number.

import java.io.*;
public class special
{
public static void sampleMethod()

throws IOException

{
BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
System.out.println(" Enter a number ");
int num=Integer.parseInt(ob.readLine());
int digit,sumDigit=0,prodDigit=1,sum=0;
int n=num;
if(num>=10&&num<=99)
{
while(n>0)
{
digit=n%10;
sumDigit+=digit;
prodDigit*=digit;

n/=10;
}
sum+=sumDigit+prodDigit;
if(sum==num)
System.out.println(" special number ");
else
System.out.println(" not a special number ");
}
}
}
o/p:
Enter a number
36
Not a special number
o/p2:
Enter a number
59
Not a special number

Program 26:
Write a program to accept the year of graduation from school as an integer value from the
user. Using the binary search technique on the sorted array of integers given below, output the
message record exists , if the value input is located in the array . if not output the message
record does not exists.
{1982,1987,1993,1996,1999,2003,2006,2007,2009,2010}
import java.io.*;

public class binary


{
public static void main()

throws IOException

{
int a[]={1982,1987,1993,1996,1999,2003,2006,2007,2009,2010};
int s=0;
BufferedReader ob=new BufferedReader( new InputStreamReader(System.in));
System.out.println(" enter a number to search for ");
s=Integer.parseInt(ob.readLine());
boolean b=false;
int start,end,mid;
start=0;
end=a.length-1;
while(start<=end)
{
mid=(start+end)/2;
if(a[mid]==s)
{
System.out.println(" record exists ");
b=true;
break;
}
else if(a[mid]<s)
start=mid+1;
else
end=mid-1;
}
if(b==false)
System.out.println(" record does not exist ");
}
}
o/p:

Enter a number to search for


1999
Record exists
o/p2:
Enter a number to search for
1998
Record does not exists
Program 27
ISBN is based upon a 10-digit code.The ISBN is legal if:
1*digit1+2*digit2+3*digit3+4*digit4+5*digit5+6*digit6+7*digit7+8*digit8+9*digit9+10*digit10 is
divisible by 11.
Example: For an The International Standard Book Number ISBN) is a unique numeric book
identifier which is printed on every book. The ISBN 1401601499
Sum=1*1+2*4+3*0+4*1+5*6+6*0+7*1+8*4+9*9+10*9=253 which is divisible by 11.
Write a program to:
(i)
(ii)

Input the ISBN code as a 10-digit Integer.


If the ISBN is not a 10-digit integer,output the message, Illegal ISBN and

(iii)

terminate the program.


If the number is 10-digit,extract the digits of the number and compute the sum as
explained above.
If the sum is divisible by 11, output the message, Legal ISBN. If the sum is not
divisible by 11 ,output the message, Illegal ISBN.

import java.io.*;
public class ISBN
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public void input() throws IOException
{

System.out.println("Enter ISBN");
long num=Integer.parseInt(br.readLine());
sampleMethod(num);
}
public void sampleMethod(long num)
{
long i,digit,sum = 0;
if(num>9999999999L|| num<100000000L)
System.out.println("Illegal ISBN");
else
{
for(i = 10;i>=1;i--)
{
digit = num%10;
sum += digit*i;
num = num/10;
}
if(sum%11 == 0)
System.out.println("Legal ISBN");
else
System.out.println("Illegal ISBN ");
}
}
public static void main() throws IOException
{

ISBN ob = new ISBN();


ob.input();

}
}

Output1
Enter ISBN
123456789
Legal ISBN
Output2
Enter ISBN
1234567891
Illegal ISBN

Program 28:
Define a class named FruitJuice with the following description :
Data Members :
Int product_type

String flavour

String pack_type

stores product code number


stores the flavour of the juice

stores the type of packaging

Int pack_size

stores package size

Int product _price

stores the price of the product

Member methods :

i)fruitjuice ()

Default constructor to initaliseinteger data members to 0 and


string data member to .

ii) void input()

-to input and store the produt code ,flavor ,pack type,pack size
and product price.

Iii)void discount ()
iv)void display()

- To reduce the product price by 10.


- To display the product code,flavoure,packtype,pack size and

product price.

import java.io.*;
public class FruitJuice
{
int product_code,pack_size,product_price;
String flavour,pack_type;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public FruitJuice()
{
product_code=pack_size=product_price=0;
flavour=pack_type="";
}
public void input() throws IOException
{
System.out.println("Enter product code ");
product_code=Integer.parseInt(br.readLine());
System.out.println("Enter flavour ");
flavour=br.readLine();

System.out.println("Enter pack_type ");


pack_type=br.readLine();
System.out.println("Enter pack size ");
pack_size=Integer.parseInt(br.readLine());
System.out.println("Enter product price ");
product_price=Integer.parseInt(br.readLine());
}
public void discount()
{
product_price-=10;
}
public void display()
{
System.out.println("Product code= " +product_code);
System.out.println("Flavour= " +flavour);
System.out.println("Pack type= " +pack_type);
System.out.println("Pack size in ml= " +pack_size);
System.out.println("Product price= " +product_price);
}
public static void main() throws IOException
{
FruitJuice ob = new FruitJuice();
ob.input();
ob.discount();
ob.display();

}
}
Output
Enter product code
1
Enter flavour
Mango
Enter pack_type
bottle
Enter pack size
5
Enter product price
50
Product code= 1
Flavour= Mango
Pack type= bottle
Pack size in ml= 5
Product price= 40

Program 29
Design a class to overload a function series() as follows:
(i)

Double series(double n)with one double argument and returns the sum of the
series,
Sum=1/1+1/2+1/3+1/4..+1/n.

(ii)

Double series(double a, double n)with two double arguments and returns the sum of
series,
Sum=1/a2+4/a5+7/a8+10/a11+to n terms.

public class Overload


{
double sum,numerator,fraction,denominator;
int i,j;
public double series(double n)
{
sum=0.0;
numerator=1.0;
for(i=1;i<=n;i++)
{
denominator=(double)i;
fraction=numerator/denominator;
sum+=fraction;
}
return sum;
}
public double series(double a,double n)
{
sum=0;
denominator=1.0;
for(i=1;i<=n;i=i+3)
{

denominator=Math.pow(a,(i+1));
fraction=i/denominator;
sum+=fraction;
}
return sum;
}
public static void main()
{
Overload ob=new Overload();
System.out.println(ob.series(5.0));
System.out.println(ob.series(2.0,2.0));

}
}
Output
2.283333333333333
0.25

Program 30:
Write a program to accept a word and convert it into lower case if it is in upper case, and
display the new word by replacing only the vowels with the character following it.
Solution:
import java.util.*;
class Strings
{

public static String convert(String s)


{
StringBuffer str=new StringBuffer(s);
int n =s.length();
char ch;
for(int i=0;i<n;i++)
{
ch=str.charAt(i);
if(Character.isUpperCase(ch)==true)
str.setCharAt(i,Character.toLowerCase(ch));
ch=str.charAt(i);
if(str.charAt(i)=='a'||str.charAt(i)=='e'||str.charAt(i)=='i'||str.charAt(i)=='o'||
str.charAt(i)=='u')
{
str.setCharAt(i,(char)(ch+1));
}
}
return str.toString();
}
public static void main()
{
String word;
Scanner kb=new Scanner(System.in);
System.out.println("enter a word");
word=kb.next();

System.out.println(convert(word));
}
}
o/p :
enter a word
ComPtuER
cpmptvfr

Program 31:
Design a class to overload a function compare() as follows:
(i). void compare( int, int) - to compare two integer values and print the greater of two
integers.
(ii). void compare (char,char) to compare the numeric value of two characters and print
the character with higher numeric value.
(iii). Void compare(String ,String) to compare the length of two strings and print the
longer of the two.
Solution:
import java.io.*;
class check
{
void compare(int a, int b)
{
if(a>b)
System.out.println(a);
else
System.out.println(b);

void compare(char a, char b)


{
if(a>b)
System.out.println(a);
else
System.out.println(b);
}

void compare(String a, String b)


{
if(a.length()>b.length())
System.out.println(a);
else
System.out.println(b);
}
public static void main()
{
check ob=new check();
ob.compare(5,6);
ob.compare(a,b);
ob.compare("Shivanand","computer");
}
}

o/p:
6
b
Shivanand
Program 32:
Write a menu driven program to perform the following (use switch statement):
(a). To print the series 0,3,8,15,24n terms (value of n is to be an input by the
user).
(b). To find the sum of series given below :
s=1/2+3/4+5/6+7/8..19/20.
Solution:
import java.io.*;
class menu
{
public static void main() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(" 1. series 1");
System.out.println(" 2. series 2");
System.out.println("Enter your choice");
int choice=Integer.parseInt(br.readLine());
switch(choice)
{
case 1 :
double s2=0;

int n=Integer.parseInt(br.readLine());
for(int i=1;i<n;i++)
{
s2=Math.pow(i,2)-1;
System.out.println(s2);
}
break;
case 2 :
double s1=0.0d;
for(int i=1;i<=19;i++)
{ s1=s1+(double)i/(double)(i+1);
}
System.out.println(s1);
break;
default :
System.out.println("Invaild input");
}
}
}
o/p:
1. series 1
2. series 2
Enter your choice
1
Enter the value of n

10
0.0
3.0
8.0
15.0
24.0
35.0
48.0
63.0
80.0

Program 33
USING THE SWITCH STATEMENT,WRITE A MENU DRIVEN PROGRAM:
1.TO CHECK AND DISPLAY WHETHER A NUMBER INPUT BY THE USER IS A
COMPOSITA NUMBER OR NOT (A NUMBER IS SAID TO BE COMPOSITE,IF IT HAS
ONE OR MORE THAN ONE FACTOR EXCLUDING 1 AND THE NUMBER ITSELF).
EXAMPLE:-4,6,8,9.
2.TO FIND THE SMALLEST DIGIT OF AN INTEGER THAT IS INPUT.
SAMPLE INPUT:6524
SAMPLE OUTPUT:SMALLEST DIGIT IS 2.
FOR AN INCORRECT CHOICE ,AN APPROXIATE ERROR MESSAGE SHOULD BE
DISPLAYED
import java.util.*;
public class Overload1
{

public static void main()


{
Scanner ob = new Scanner(System.in);
System.out.println("Enter a number");
int num=ob.nextInt();
System.out.println("Menu");
System.out.println("1. COMPOSITE NUMBER OR NOT");
System.out.println("2. SMALLEST DIGIT");
System.out.println("Enter your choice");
int choice=ob.nextInt();
switch(choice)
{
case 1:
int c=1;
for(int i=2;i<=num/2;i++)
{
if(num%i==0)
c=c+1;
}
if(c>1)
System.out.println(num+ " is a composite number");
else
System.out.println(num+ " is not a composite number");
break;
case 2:

int smallest=9,digit;
while(num!=0)
{
digit=num%10;
if(digit<smallest)
smallest=digit;
num=num/10;
}
System.out.println("smallest digit is " +smallest);
break;
default:
System.out.println(" Invalid choice ");

}
}
}
Output1
Enter a number
4
Menu
1. COMPOSITE NUMBER OR NOT
2. SMALLEST DIGIT
Enter your choice
1

4 is a composite number
Output2
Enter a number
6524
Menu
1. COMPOSITE NUMBER OR NOT
2. SMALLEST DIGIT
Enter your choice
2
smallest digit is 2

You might also like