Solutions For Java Practice Coding
Solutions For Java Practice Coding
Q1.Fahrenheit to Celsius
Complete the static methods in the class Utility as per following requirements
This method should convert farhenheit in to celcius based on the formula [celcius =
(farhenheit - 32) X 5 / 9]
Should calculate the sum of all array elements and return a String as per below rules
HIGH - when sum is greater than or equal to 100, MEDIUM - when sum is greater than or
Program should take console input and call appropriate methods of Utility class based on the
Input.
Input and Output sample formats are given below in Example section
In case of option 2, the second input should be number of elements in the array, followed by
the array elements In case of incorrect option, program should display 'Invalid Option'
Sample Input:
1 // Option
100 // temperature in Farhenheit
Expected Output:
38
Sample Input:
1
95.5
Expected Output:
35
Sample Input:
2 // option
3 // number of elements in array
40 // array elements
50 // array elements
11 // array elements
Expected Output:
HIGH
Sample Input:
2
4
10
20
5
10
Expected Output:
LOW
Solution:
import java.lang.Math;
import java.util.Scanner;
class Utility {
int celcius;
celcius=(int)Math.round(((farhenheit-32)*5)/9);
return celcius;
int sum=0,i;
for(i=0;i<array.length;i++)
sum+=array[i];
if(sum>=100)
return "HIGH";
return "MEDIUM";
else if(sum<70)
return "LOW";
else
return null;
//CODE END
int choice=scan.nextInt();
switch(choice)
farhenheit=scan.nextDouble();
System.out.println(u1.fahrenheitToCelcius(farhenheit));
break;
case 2:int n,i;
n=scan.nextInt();
for(i=0;i<n;i++)
ar[i]=scan.nextInt();
System.out.println(u2.getLevel(ar));
break;
default:
System.out.println("Invalid Option");
break;
scan.close();
*****************************************************************************
Q2.Prime Larger
Write a Java program that accepts two integer values from the user and prints the larger
value if both the values are prime numbers otherwise it prints smaller value and
Example:
Sample Input:
5
11
Expected Output:
11
Sample Input:
5
16
Expected output:
5
Sample Input:
5
5
Expected output:
0
Solution:
import java.util.Scanner;
int result=-1;
int a = in.nextInt();
int b = in.nextInt();
if(a == b){
result=0;
}
else if(isPrime(a) & isPrime(b)) {
if(a>b)
result=a;
else
result=b;
else
if(a>b){
result=b;
else
result=a;
System.out.println(result);
boolean flag=true;
if(num % i == 0) {
flag = false;
break;
return flag;
**********************************************************************************
Q3.Count HR Designations
Example:
Sample Input:
4
HRExecutive
Accountant
HRManager
SalesMan
Expected output:
Total 2 designations in HR Department
HREXECUTIVE
HRMANAGER
Sample Input:
2
Operator
Programmer
Expected output:
No designation of HR department found in given data
Sample Input:
-2
Operator
Programmer
Expected output:
INVALID INPUT
Solution:
import java.util.Scanner;
int no = scanner.nextInt();
if(no>0){
int count=0;
input[i] = scanner.next();
for(int i=0;i<no;i++){
if(input[i].contains("HR")){
designations[count]=input[i];
count++;
if(count>0)
for(int j=0;j<count;j++)
System.out.println(designations[j].toUpperCase());
}
else
else {
System.out.println("INVALID INPUT");
studentId : int
studentName : String
college: String
Write code in another given class EngineeringStudent which should inherit Student class
stream : String
Accept the input from the user to create Student or EngineeringStudent object and display
the details using getDetails method. Other then "Student " or "EngineeringStudent" input, it
Example
Sample Input:
Student
111
Ram
National College
Expected output:
Student ID: 111
Student Name: Ram
College: National College
Sample Input:
EngineeringStudent
123
Ananya
IIT
Computer
Expected output:
Student ID: 123
Student Name: Ananya
College: IIT
Stream: Computer
Sample Input:
Trainer
Expected output:
Invalid Input
Solution:
import java.util.Scanner;
class Student {
super();
this.studentId = studentId;
this.studentName = studentName;
this.college = college;
}
public int getStudentId() {
return studentId;
this.studentId = studentId;
return studentName;
this.studentName = studentName;
return college;
this.college = college;
this.stream = stream;
return stream;
this.stream = stream;
super.getDetails();
if (object.equals("EngineeringStudent")) {
scanner.nextLine();
scanner.nextLine();
Student.getDetails();
} else if (object.equals("Student")){
int studentId = scanner.nextInt();
scanner.nextLine();
scanner.nextLine();
Student.getDetails();
}else {
System.out.println("Invalid Input");
Q5.RollNumber Validator
studentId : int
studentName : String
college: String
Write code in another given class EngineeringStudent which should inherit Student class and have
to override getDetails() with additional information stream to be displayed.
stream : String
Accept the input from the user to create Student or EngineeringStudent object and display the
details using getDetails method.
Other then "Student " or "EngineeringStudent" input, it must display "Invalid Input".
Example
Sample Input:
Student
111
Ram
National College
Expected output:
Student ID: 111
Student Name: Ram
College: National College
Sample Input:
EngineeringStudent
123
Ananya
IIT
Computer
Expected output:
Student ID: 123
Student Name: Ananya
College: IIT
Stream: Computer
Sample Input:
Trainer
Expected output:
Invalid Input
import java.util.Scanner;
class Student {
super();
this.studentId = studentId;
this.studentName = studentName;
this.college = college;
return studentId;
}
this.studentId = studentId;
return studentName;
this.studentName = studentName;
return college;
this.college = college;
this.stream = stream;
}
return stream;
this.stream = stream;
super.getDetails();
if (object.equals("EngineeringStudent")) {
scanner.nextLine();
scanner.nextLine();
Student.getDetails();
} else if (object.equals("Student")){
scanner.nextLine();
String studentName = scanner.next();
scanner.nextLine();
Student.getDetails();
}else {
System.out.println("Invalid Input");
Create a java class Coach.Coach's job is to coach the Batsman and Bowler.
Implement loose coupling by introducing an Abstract class Player.
Create both the Batsman and Bowler classes, they must extend Player class.
Player class must have abstract method play() and returns void.
play() : void
Coach class has one private attribute:
player : Player
will print “Batsman is batting”, if Batsman object is passed and “Bowler is bowling”, if Bowler Object
is passed to the setPlayer method.Print "Invalid Input" if other then Batsman or Bowler is given as
Sample Input .
Pass the Batsman object or Bowler object to the setPlayer method and call the coach() method to
print the information.
Example
Sample Input:
Batsman
Expected output:
Batsman is batting
Sample Input:
Bowler
Expected output:
Bowler is bowling
Sample Input:
Umpire
Expected output:
Invalid Input
Solution:
import java.util.Scanner;
class Coach {
this.worker = worker;
worker.play();
interface IPlayer
void play();
@Override
public void play() {
System.out.println("Batsman is batting");
@Override
System.out.println("Bowler is bowling");
if(type.equals("Batsman")) {
Coach.setWorker(new Batsman());
Coach.coach();
}else if(type.equals("Bowler")) {
Coach.setWorker(new Bowler());
Coach.coach();
} else {
System.out.println("Invalid Input");
}
Q7. Search Doctor
Complete the application as per the below design to search for doctors based on speciality/years of
experience.The application consists of 3 classes : Doctor, DoctorService and SearchDoctorApp.
Complete the given classes as below.
class Doctor This pre-written class contains the instance variables: name, speciality and experience,
Getters/Setters, Constructors and overridden toString method. This class may need some changes
based on the requirement.
getExperiencedDoctors(int):List<Doctor>
getSpecialityDoctor(String):Set<Doctor>
- This method takes speciality(case insensitive) as input
parameter and returns a Set of Doctors who have this speciality
- The returned Set should be sorted in ascending order of name of
Doctor
class SearchDoctorApp This class contains a static variable doctorsData which is initialized with
details of 9 doctors in the below format.
name-speciality-experience;name-speciality-experience;...
1. Create Doctor objects using the data present in doctorsData variable and add these objects
to a ArrayList of Doctors
2. Initialize the doctorsRepository variable of DoctorService with the above ArrayList
3. Accept 1 or 2 as choice from the user through Console.
4. If choice is 1, accept years of experience as second input. Invoke appropriate method of
DoctorService and display the doctors as per the below format
5. If choice is 2, accept speciality as second input. Invoke appropriate method of DoctorService
and display the doctors as per the below format
6. Display "No Doctors Found", if there are no doctors matching the search criteria
7. Display "Invalid Choice", if the first input is not 1 or 2
Example
Sample Input:
1 10
Expected Output:
Jim Cardiology 25
David Dermatology 15
John Dermatology 10
Amy Pediatrics 16
Mavis Pediatrics 11
Sample Input:
1 30
Expected Output:
No Doctors Found
Sample Input:
2 Cardiology
Expected Output:
Jim Cardiology 25
Solution:
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
public Doctor() {
super();
super();
this.name = name;
this.speciality = speciality;
this.experience = experience;
@Override
return name;
this.name = name;
this.speciality = speciality;
return experience;
this.experience = experience;
@Override
return name.compareToIgnoreCase(doc.name);
class DoctorService {
this.doctorsRepository = doctorsRepository;
if(doctorsRepository==null||doctorsRepository.isEmpty())
return null;
Iterator itr=doctorsRepository.iterator();
while(itr.hasNext())
Doctor docs=(Doctor)itr.next();
if(exp1>=exp)
res.add(docs);
@Override
return -1;
else
return 1;
});
@Override
return o1.getSpeciality().compareToIgnoreCase(o2.getSpeciality());
});
return res;
if(doctorsRepository==null||doctorsRepository.isEmpty())
return null;
Iterator itr=doctorsRepository.iterator();
while(itr.hasNext())
Doctor docs=(Doctor)itr.next();
if(spec1.equalsIgnoreCase(spec))
res1.add(docs);
Collections.sort(res1);
res.addAll(res1);
return res;
static {
doctors.append("John-Dermatology-10;");
doctors.append("David-Dermatology-15;");
doctors.append("Bob-Pediatrics-6;");
doctors.append("Cathy-Dermatology-5;");
doctors.append("Mavis-Pediatrics-11;");
doctors.append("Robin-Pediatrics-7;");
doctors.append("Minty-Dermatology-9;");
doctors.append("Jim-Cardiology-25;");
doctorsData = doctors.toString();
List<Doctor> docs;
String arr[]=doctorsData.split(";");
int n = 3*arr.length;
arr1=arr[i].split("-");
int j =0;
docs.add(new Doctor(arr1[j],arr1[j+1],Integer.parseInt(arr1[j+2])));
if(choice==1)
docs1=services.getExperiencedDoctors(exp);
if(docs1==null||docs1.isEmpty())
else
Iterator itr2=docs1.iterator();
while(itr2.hasNext())
Doctor st=(Doctor)itr2.next();
}
}
else if(choice==2)
docs2=services.getSpecialityDoctor(spec);
if(docs2==null||docs2.isEmpty())
else
Iterator itr2=docs2.iterator();
while(itr2.hasNext())
Doctor st=(Doctor)itr2.next();
else
System.out.println("Invalid Choice");
}
Q8. Email Crawler
Create a code which will allow the user to search and email depending upon the word ,this
application will be at the initial stages of implementation further this application would be enhanced
by some more features.
Currently this application will search and display the message if the given word passed has a input is
available in the email or not,if available/unavailable suitable message would be displayed which can
been seen in the sample output provided below.
1.Document
2.Email
3.Source--->This would be already available in the coding editor.
Document class members
private String emailText;
toString() ---> will return emailText;
Sample Input 1:
Manzoor----> From (Sender)
Jagadish---->To (Recipent)
Webinar---->Subject heading
Kindly discuss codeathon related questions in webinar ----->Detailed email message
questions---->---->Word to search in the email message
Sample output 1:
Email contains the word:questions
From:Manzoor
To:Jagadish
Webinar
Kindly discuss codeathon related questions in webinar
Sample Input 2:
Naveen----> From (Sender)
Jagadish----> To (Recipent)
Review------> Subject heading
Kindly re-review the questions for codeathontest----->Detailed email message
codingtest ---->Word to search in the email message
Sample output 2:
Email does not contain the word:codingtest
From:Naveen
To:Jagadish
Review
Kindly re-review the questions for codeathontest
Solution:
import java.util.*;
class Document
this.text=text;
return text;
super(textDoc);
this.sender = sender;
this.recipient = recipient;
this.title = title;
return sender;
return recipient;
return title;
return super.toString();
}
public void setSender(String sender)
this.sender = sender;
this.recipient = recipient;
this.title =title;
if (docObject.toString().indexOf(keyword, 0) >= 0)
return true;
return false;
String from=s.next();
String to=s.next();
String subject=s.next();
s.nextLine();
String message=s.nextLine();
String searchword=s.next();
if (ContainsKeyword(email1,searchword))
else
System.out.println(email1.toString());
}
Q9. Payments App
Define a abstract class named Payment that contains a method named paymentDetails
which should be declared abstract in this class,that outputs payment details w.r.t to
CreditCardPayment and CashPayment.
Next, define a class named CashPayment that is derived from Payment. This class should
redefine the paymentDetails method to indicate that the payment is in cash. Include
appropriate constructor(s).
Define a class named CreditCardPayment that is derived from Payment. This class should
contain instance variables for the name on the card, expiration date, and credit card number.
Include appropriate constructor(s). Finally, redefine the paymentDetails method to include
all credit card information in the printout.
In the main method create CashPayment and CreditCardPayment objects with different
values and calls paymentDetails for each.
public abstract String paymentDetails()---> this method returns the information depending
on the type of Payment (Credit/CashPayment),it has to be redefined or oveririden in
Credit/Cash classes and return the the reuqired sample output data mentioned below.
Note:
Sample Output 1:
Amount:9500.0CardNo:***1234Validty:12/21Name:Ajay
Sample Input:2
2-------> Choice to be entered should be int type
6500-------> total amount
Ramesh------>customer name
Sample Output 2:
CashPayment:6370.0Customer:Ramesh
Note:
1.6370 is the amount after discount of 2%
2.9500.0 is the amount after discount of 5%
Solution:
mport java.util.*;
String custname;
double amount;
this.amount=amount;
this.custname=custname;
double tamount=amount*0.02;
return amount-tamount;
double amount;
//super(value);
this.amount=amount;
this.number = number;
this.expDate = expDate;
this.name = name;
double tamount=amount*0.05;
return amount-tamount;
{
double totalamount =payableAmount();
return"Amount:"+totalamount+"CardNo:"+number+"Validty:"+expDate+"Name:"+name;
int choice=s.nextInt();
if(choice==1)
double amount=s.nextDouble();
String name=s.next();
String expdate=s.next();
String card=s.next();
System.out.println(x.paymentDetails());
else if(choice==2)
double amount=s.nextDouble();
String name=s.next();
Main class Source should have the functionality to validate the input hexadecimal and decimal
colour codes.
Create two static methods in class ColourCodeValidator as per the below signature
validateHexCode(String):int
validateDecimalCode(String):int
Both the methods return 1 for valid codes and -1 for invalid
codes. Rules for valid codes are given below
• Format: #A1BC23
• Must start with "#" symbol
• Must contain six characters after #
• It may contain alphabets from A-F or digits from 0-9
• Format: rgb(x,y,z)
• x,y and z are values from 0 to 255 inclusive
Example
Sample Input:
1 #ABCDEF
Expected Output:
Valid Code
Sample Input:
2 rgb(9,99,249)
Expected Output:
Valid Code
Sample Input:
9
Expected Output:
Invalid choice
Solution:
import java.util.Scanner;
// CODE HERE
// CODE START
int q = sc.nextInt();
if(q==1) {
String n = sc.next();
int u = (Source.validateHexCode(n));
if(u==1)
System.out.println("Valid code");
else
System.out.println("Invalid code");
else if(q==2) {
String j = sc.next();
//System.out.println(j.length());
int y = (Source.validateDecimalCode(j));
if(y==1)
System.out.println("Valid code");
else
System.out.println("Invalid code");
else
System.out.println("Invalid choice");
int k = 0,c = 0;
for(int i=0;i<s2.length();i++) {
chars[i]= s2.charAt(i);
char a = s2.charAt(i);
if(a ==',') {
int m = i;
k=m+1;
//System.out.println(string);
c++;
}
}
//System.out.println(string1);
c++;
//System.out.println(c);
if(c==3)
return 1;
else
return -1;
int c= 0;
// System.out.println(s.length());
for(int i = 1;i<s.length();i++) {
c = 1;
break;
if(c==1)
return 1;
else
return -1;
Q11. Code-Exception
2.The code should also handle InputMismatchException ,if the input is not a numerical value that is
read by the Scanner class.
4.If the inputs are right then it should display the result.
Sample Input 1:
10 -----------> Input 1
R -----------> Input 2
Sample Output 1:
ERROR501 ---->Note this message should be issued from the constructor of custom exception class
Sample Input 2:
10 -----------> Input 1
0 -----------> Input 2
Sample Output 2:
ERROR502
Sample Input 3:
10 -----------> Input 1
8 -----------> Input 2
Sample Output 3:
1.25
Solution
import java.util.Scanner;
import java.util.InputMismatchException;
{
public DivisionByZeroException()
super("ERROR502");
super(msg);
double r;
try
n1 = scan.nextInt();
n2 = scan.nextInt();
if(n2 == 0)
throw new DivisionByZeroException();
r = (double) n1 / n2;
System.out.println(r);
catch(DivisionByZeroException dbze)
System.err.println(dbze.getMessage());
catch(InputMismatchException imme)
//scan.nextLine();
System.err.println("ERROR501");