Live Coding Java
Live Coding Java
class Faculty{
private String name;
private double salary;
public Faculty(String name, double salary) {
this.name = name;
this.salary = salary;
}
public double bonus(float percent){
return (percent/100.0)*salary;
}
Page 2
}
class Hod extends Faculty{
private String personalAssistant;
public Hod(String name, double salary, String pa) {
super(name, salary);
this.personalAssistant = pa;
}
}
public class InheritanceTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Faculty obj1 = new Faculty(sc.next(), sc.nextDouble());
System.out.println(obj1.getDetails());
System.out.println(obj1.getDetails(10));
System.out.println(obj2.getDetails());
System.out.println(obj2.getDetails(10));
}
}
Page 3
Public test case 1:
Input:
Srihari 50000
Vishnu 80000 laxmi
Output:
Srihari, 50000.0
Srihari, 50000.0, bonus = 5000.0
Vishnu, 80000.0, laxmi
Vishnu, 80000.0, laxmi, 4000.0
Mohan 45000
Manoj 78000 dhanush
Output:
Mohan, 45000.0
Mohan, 45000.0, bonus = 4500.0
Manoj, 78000.0, dhanush
Manoj, 78000.0, dhanush, 3900.0
Manjula 65000
Ganesh 87000 Harsha
Output:
Manjula, 65000.0
Manjula, 65000.0, bonus = 6500.0
Ganesh, 87000.0, Harsha
Ganesh, 87000.0, Harsha, 4350.0
Page 4
Solution:
class Faculty{
private String name;
private double salary;
public Faculty(String name, double salary) {
this.name = name;
this.salary = salary;
}
public double bonus(float percent){
return (percent/100.0)*salary;
}
public String getDetails() {
return name + ", " + salary;
}
public String getDetails(float percent ) {
return getDetails()+ ", bonus = "+bonus(percent);
}
}
class Hod extends Faculty{
private String personalAssistant;
public Hod(String name, double salary, String pa) {
super(name, salary);
this.personalAssistant = pa;
}
public double bonus(float percent){
return 0.5*super.bonus(percent);
}
public String getDetails() {
return super.getDetails()+", "+ personalAssistant;
}
public String getDetails(float percent ) {
return getDetails()+", "+bonus(percent);
}
}
public class InheritanceTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Faculty obj1 = new Faculty(sc.next(), sc.nextDouble());
System.out.println(obj1.getDetails());
Page 5
System.out.println(obj1.getDetails(10));
System.out.println(obj2.getDetails());
System.out.println(obj2.getDetails(10));
}
}
Page 6
2. Write a Java program as instructed.
• Abstract class UPIPayment has two abstract methods: abstract void payment()
and abstract void rewards()
• Class PhonePay extends class UPIPayment and has the following members.
– private int amount as private instance variable
– Constructor to initialize the instance variable
– You should override method public void payment() such that the overridden
method displays the message "Phone pay:Payment success:" and invokes
method rewards().
– You should override method public void rewards() as follows.
∗ If amount < 500, then display the message "Sorry no rewards".
∗ Else, if amount >= 500, then display the message "10 off on next mobile
rc".
• Class Paytm extends class UPIPayment and has the following members.
– private int amount as private instance variable
– Constructor to initialize the instance variable
– You should override method public void payment() such that the overridden
method displays the message "Paytm:Payment success:" and invokes method
rewards().
– You should override method public void rewards() as follows.
∗ If amount < 500, then display the message "Sorry no rewards".
∗ Else, if amount >= 500, then display message "10 off on next DTH rc".
• Class UPIUser has the following method.
– Method public void transferAndGetRewards(UPIPayment obj) that invokes
method payment() using obj.
• Class AbstractTest has the main method, and has the following functionality.
– Creates an object of UPIUser
– Takes two amounts a1 for PhonePay and a2 for Paytm
– Invokes method transferAndGetRewards() first by passing an object of PhonePay
with amount a1 as parameter, and then by passing an object of Paytm with
amount a2 as parameter.
Page 7
this.amount = amount;
}
}
class Paytm extends UPIPayment{
private int amount;
public Paytm(int amount) {
this.amount = amount;
}
}
class UPIUser{
public void transferAndGetRewards(UPIPayment obj) {
obj.payment();
}
}
public class AbstractTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a1 = sc.nextInt();
int a2 = sc.nextInt();
UPIUser u = new UPIUser();
u.transferAndGetRewards(new PhonePay(a1));
u.transferAndGetRewards(new Paytm(a2));
}
}
Page 8
Public test case 1:
Input:
450
1000
Output:
5000
499
Output:
100
100
Output:
Page 9
Solution:
abstract class UPIPayment{
abstract void payment();
abstract void rewards();
}
class PhonePay extends UPIPayment{
private int amount;
public PhonePay(int amount) {
this.amount = amount;
}
public void payment() {
System.out.println("Phone pay:Payment success:");
rewards();
}
public void rewards() {
if(amount < 500)
System.out.println("Sorry no rewards");
else if(amount >= 500)
System.out.println("10 off on next mobile rc");
}
}
class Paytm extends UPIPayment{
private int amount;
public Paytm(int amount) {
this.amount = amount;
}
public void payment() {
System.out.println("Paytm:Payment success:");
rewards();
}
public void rewards() {
if(amount < 500)
System.out.println("Sorry no rewards");
else if(amount >= 500)
System.out.println("10 off on next DTH rc");
}
}
class UPIUser{
public void transferAndGetRewards(UPIPayment obj) {
obj.payment();
}
}
Page 10
public class AbstractTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a1 = sc.nextInt();
int a2 = sc.nextInt();
UPIUser u = new UPIUser();
u.transferAndGetRewards(new PhonePay(a1));
u.transferAndGetRewards(new Paytm(a2));
}
}
Page 11
3. Write Java code as instructed.
Page 12
// Define interface Appraisable
// Define interface SpecialAppraisable
InterfaceTest.printUpdatedTeachList(tArr);
Page 13
}
}
Page 14
Public test case 1:
Input:
Output:
Dharani 76000 96
Thanvi 56000 72
Thannya 90000 85
Output:
Kavya 54000 59
Chaithanya 65000 55
Sravani 73000 53
Output:
Page 15
Solution:
interface Appraisable{
default void appraisal(Teacher t){
t.setSalary(t.getSalary()+(t.getstuPassPer()/100)*5000);
}
public abstract void checkAndUpdateSalary();
}
interface SpecialAppraisable extends Appraisable{
default void spAppraisal(Teacher t){
t.setSalary(t.getSalary()+(t.getstuPassPer()/100)*10000);
}
}
class Teacher implements SpecialAppraisable{
private String name;
private double salary;
private double stuPassPer;
public Teacher(String name, double salary, double stuPassPer) {
this.name = name;
this.salary = salary;
this.stuPassPer = stuPassPer;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getstuPassPer() {
return stuPassPer;
}
public String toString() {
return name + ", " + salary + ", " + stuPassPer;
}
public void checkAndUpdateSalary() {
if(stuPassPer >= 60 && stuPassPer < 75)
appraisal(this);
else if(stuPassPer >= 75 && stuPassPer <= 100)
spAppraisal(this);
}
}
public class InterfaceTest {
public static void printUpdatedTeachList(Teacher[] tList) {
Page 16
for (int i = 0; i < tList.length; i++)
tList[i].checkAndUpdateSalary();
for (int i = 0; i < tList.length; i++)
System.out.println(tList[i]);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Teacher tArr[] = new Teacher[3];
for (int i = 0; i < tArr.length; i++)
tArr[i] = new Teacher(sc.next(), sc.nextDouble(), sc.nextDouble());
InterfaceTest.printUpdatedTeachList(tArr);
}
}
Page 17
4. Write a Java program that accepts list of student objects and updates the regular fees,
based on the number of backlogs that each student has.
Page 18
import java.util.Scanner;
interface Generatable{
abstract void feeGenerate(Student s);
}
class Student {
private String name;
private double fee;
private int backlogs;
public Student(String name, int backlogs) {
this.name = name;
this.backlogs = backlogs;
}
public void setFee(double fee) {
this.fee = fee;
}
public int getBacklogs() {
return backlogs;
}
public String toString() {
return name + ", " + fee + ", " + backlogs;
}
}
class ExamBranch{
private class Regular implements Generatable{
public void feeGenerate(Student s) {
s.setFee(1500.00);
}
}
private class Supple implements Generatable{
public void feeGenerate(Student s) {
if(s.getBacklogs() == 1)
s.setFee(1500 + 500);
else if(s.getBacklogs() == 2)
s.setFee(1500 + 1000);
else if(s.getBacklogs() >=3 )
s.setFee(1500 + 2000);
}
}
Page 19
public class PrivateClassTest {
Page 20
Public test case 1:
Input:
Ananya 0
Acharya 4
Ashok 2
Output:
Ananya, 1500.0, 0
Acharya, 3500.0, 4
Ashok, 2500.0, 2
Sharath 1
Shekar 0
Shhin 0
Output:
Sharath, 2000.0, 1
Shekar, 1500.0, 0
Shhin, 1500.0, 0
Bharath 3
Bharani 4
Balaji 5
Output:
Bharath, 3500.0, 3
Bharani, 3500.0, 4
Balaji, 3500.0, 5
Page 21
Solution:
import java.util.Scanner;
interface Generatable{
abstract void feeGenerate(Student s);
}
class Student {
private String name;
private double fee;
private int backlogs;
public Student(String name, int backlogs) {
this.name = name;
this.backlogs = backlogs;
}
public void setFee(double fee) {
this.fee = fee;
}
public int getBacklogs() {
return backlogs;
}
public String toString() {
return name + ", " + fee + ", " + backlogs;
}
}
class ExamBranch{
private class Regular implements Generatable{
public void feeGenerate(Student s) {
s.setFee(1500.00);
}
}
private class Supple implements Generatable{
public void feeGenerate(Student s) {
if(s.getBacklogs() == 1)
s.setFee(1500 + 500);
else if(s.getBacklogs() == 2)
s.setFee(1500 + 1000);
else if(s.getBacklogs() >=3 )
s.setFee(1500 + 2000);
}
}
public Generatable getRegularFee() {
return new Regular();
}
Page 22
public Generatable getSuppleFee() {
return new Supple();
}
}
public class PrivateClassTest {
public static Student[] getStudentsFee(Student sList[]){
ExamBranch obj;
for (int i = 0; i < sList.length; i++) {
if(sList[i].getBacklogs()==0) {
obj=new ExamBranch();
obj.getRegularFee().feeGenerate(sList[i]);
}
else {
obj=new ExamBranch();
obj.getSuppleFee().feeGenerate(sList[i]);
}
}
return sList;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Student[] sArr = new Student[3];
for (int i = 0; i < sArr.length; i++) {
sArr[i] = new Student(sc.next(), sc.nextInt());
}
sArr = PrivateClassTest.getStudentsFee(sArr);
for (int i = 0; i < sArr.length; i++) {
System.out.println(sArr[i]);
}
}
}
Page 23
5. Write a program that, given two integers, two doubles as x and y coordinates of two
points p1(x1,y1) and p2(x2,y2) on a two-dimensional plane as input, finds the mid-
point p3(x3,y3) of the line segment formed by p1 and p2 using the formula:
x1 + x2 y1 + y2
x3 = and y3 =
2 2
• The main method accepts the two input points. The first line of input will be two
integers of point p1. The second line of input will be two doubles of point p2. It
then invokes the method mid of one of the objects.
Sample input 1:
3 4
5 6
Output:
(4,5)
Sample input 2:
-3 4
-5 6
Output:
(-4,5)
import java.util.*;
Page 24
public class Test{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Point<Integer> p1 = new Point<Integer>(sc.nextInt(), sc.nextInt());
Point<Double> p2 = new Point<Double>(sc.nextDouble(), sc.nextDouble());
Point<Double> p3 = p1.mid(p2);
System.out.println(p3);
}
}
2 3
2.2 4.2
Output:
(2.1,3.6)
7 8
5 6
Output:
(6.0,7.0)
-3 2
-5 -6
Output:
(-4.0,-2.0)
5 3
3.2 5.2
Output:
(4.1,4.1)
Page 25
Solution:
import java.util.*;
class Point<T extends Number>{
T x, y;
public Point(T x, T y) {
this.x = x;
this.y = y;
}
public Point<Double> mid(Point<?> p){
Point<Double> pt = new Point<Double>(0.0, 0.0);
pt.x = (this.x.doubleValue() + p.x.doubleValue()) / 2;
pt.y = (this.y.doubleValue() + p.y.doubleValue()) / 2;
return pt;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
Page 26
6. Write a Java program that takes as input 4 Customer objects and the list of Customer
objects with attributes customer name, and expense. The program computes the dis-
count amount payable to each customer (assuming discount rate is 5% of the expense
value, and is applicable for all customers having expense value >= 1000) and prints the
discount amount in the format given in sample input-output. For customers who are
not eligible for discount, it prints Nondiscountable expense. Complete the program
as specified below:
• Define a checked exception (extends Exception) DiscountException that returns
the string Nondiscountable expense if getMessage method of DiscountException
is called.
• Define class Customer, which should have the following members:
– Instance variables – name and expense
– final variable – discountrate is
– a suitable constructor to initialize the instance variables
– accessors getName() to obtain the value of name
– method checkDiscount() that computes the discount amount if the expense
is >= 1000; otherwise, throws DiscountException.
• Class ExceptionTest has the main method and the method displayCustomers.
In function displayCustomers, invokes the checkDiscount() on each customer
object.
Sample Input:
Mark 1200
Adam 100
Jose 1100
Raj 1900
Output:
Mark : 60.0
Adam : Nondiscountable expense
Jose : 55.0
Raj : 95.0
import java.util.*;
Page 27
// iterate through cus and invoke checkDiscount() on each customer object
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
var cus = new LinkedList<Customer>();
for(int i = 0; i < 4; i++){
cus.add(new Customer(sc.next(),sc.nextDouble()));
}
displayCustomers(cus);
}
}
Jack 700
Adam 100
Jose 1100
Raj 1900
Output:
Lata 900
Puja 1100
Vinita 1900
Sudha 130
Output:
Page 28
Anil 150
Nisha 700
Amrit 2500
Arun 800
Output:
Sona 900
Raj 1900
Puja 1000
Vinita 1990
Output:
Page 29
Solution:
import java.util.*;
class DiscountException extends Exception{
DiscountException(){
super("Nondiscountable expense");
}
}
class Customer{
private String name;
private double expense;
final double discountrate = 0.05;
public Customer(String n, double e){
name = n;
expense = e;
}
public String getName(){
return name;
}
public double checkDiscount() throws DiscountException{
if(expense < 1000)
throw new DiscountException();
return expense * discountrate;
}
}
public class ExceptionTest{
static void displayCustomers(LinkedList<Customer> cus){
for(var c : cus){
System.out.print(c.getName() + " : ");
try{
System.out.println(c.checkDiscount());
}catch(DiscountException ex){
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
var cus = new LinkedList<Customer>();
for(int i = 0; i < 4; i++){
cus.add(new Customer(sc.next(),sc.nextDouble()));
}
displayCustomers(cus);
Page 30
}
}
Page 31
7. Write a Java program that takes as input 4 Shop objects and the list of Shop objects
with attributes shop name, and number of items sold nsold. The program should add
each customer name as key and number of items as value to the map object. After
adding all objects to the map, display the shop name which has sold maximum number
of items as shown in the test cases. Complete the program as specified below:
Sample Input:
Orion 45
Ambience 115
Orion 45
Orion 10
Output:
Ambience : 115
import java.util.*;
import java.util.*;
class Shop{
private String name;
private int nsold;
public Shop(String s, int ns){
this.name = s;
this.nsold = ns;
}
Page 32
public String getName(){
return name;
}
public int getItemSold(){
return nsold;
}
}
public class MapTest {
public static void printShopName(ArrayList<Shop> sList) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
String shop = "";
int sold = 0;
// iterate through sList and add each shop object to map ”m”
System.out.println(shop+" : "+sold);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Shop> list = new ArrayList<Shop>();
for (int i = 0; i < 4; i++) {
list.add(new Shop(sc.next(), sc.nextInt()));
}
printShopName(list);
}
}
SuperBazar 30
More 40
Shopsy 30
More 30
Output:
More : 70
Lulu 40
Lulu 34
DLF 54
DLF 67
Page 33
Output:
DLF : 121
HiLITE 56
Sarath-City 40
Z-Square 54
World-Trade 43
Output:
HiLITE : 56
Mantri-Square 56
Mantri-Square 76
Mantri-Square 11
Phoenix 590
Output:
Phoenix : 590
Page 34
Solution:
import java.util.*;
class Shop{
private String name;
private int nsold;
public Shop(String s, int ns){
this.name = s;
this.nsold = ns;
}
public String getName(){
return name;
}
public int getItemSold(){
return nsold;
}
}
public class MapTest {
public static void printShopName(ArrayList<Shop> sList) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
String shop = "";
int sold = 0;
for(Shop s: sList)
m.put(s.getName(), m.getOrDefault(s.getName(),0)+s.getItemSold());
for (HashMap.Entry<String, Integer> entry : m.entrySet()){
if(entry.getValue()> sold) {
shop = entry.getKey();
sold = entry.getValue();
}
}
System.out.println(shop+" : "+sold);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Shop> list = new ArrayList<Shop>();
for (int i = 0; i < 4; i++) {
list.add(new Shop(sc.next(), sc.nextInt()));
}
printShopName(list);
}
}
Page 35
8. Complete the Java code below that takes a list of student objects as input, and removes
students from the list that satisfy the defined property.
Complete the program as specified below:
import java.util.*;
class Student{
String name;
double attendance;
public Student(String name, double attendance) {
this.name = name;
this.attendance = attendance;
}
public String toString() {
return name + ", " + attendance;
}
}
class RemoveStudent{
public boolean property(double value) {
if(value<65)
return true;
return false;
Page 36
}
public void detained(ArrayList<Student> sList) {
}
}
public class IteratorTest {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
ArrayList<Student> list = new ArrayList<Student>();
for (int i=0; i<6; i++) {
list.add(new Student(scanner.next(),scanner.nextDouble()));
}
RemoveStudent obj=new RemoveStudent();
obj.detained(list);
}
}
virat 23.0
johny 78.9
suchith 56.9
juhee 45.00
karthik 90.0
shannu 67.0
Output:
johny, 78.9
karthik, 90.0
shannu, 67.0
Nani 34.0
Bala 89.0
Chiru 70.0
Venky 56.0
Nag 97.0
Raj 52.0
Page 37
Output:
Bala, 89.0
Chiru, 70.0
Nag, 97.0
Devi 56.0
Anup 64.0
Thaman 34.0
Thamiza 44.0
Choutha 55.0
Yuvan 69.0
Output:
Yuvan, 69.0
Page 38
Solution:
import java.util.*;
class Student{
String name;
double attendance;
public Student(String name, double attendance) {
this.name = name;
this.attendance = attendance;
}
public String toString() {
return name + ", " + attendance;
}
}
class RemoveStudent{
public boolean property(double value) {
if(value<65)
return true;
return false;
}
public void detained(ArrayList<Student> sList) {
Student obj;
Iterator<Student> it = sList.iterator();
while (it.hasNext()) {
obj = it.next();
if(property(obj.attendance))
it.remove();
else
System.out.println(obj);
}
}
}
public class IteratorTest {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
ArrayList<Student> list = new ArrayList<Student>();
for (int i=0; i<6; i++) {
list.add(new Student(scanner.next(),scanner.nextDouble()));
}
RemoveStudent obj=new RemoveStudent();
obj.detained(list);
}
}
Page 39
9. Write the java program that creates 3 objects of students and prints the name of student
with highest total. Implement the code as follows:
Define class Student with following members:
• String name, double[] marks (array length is 3) as instance variables which rep-
resents the name and marks of student
• Constructor to initialize instance variables
• Accessor method getName() that returns the name of student
• Method findTotal( ) that returns the total marks of the student
• Method getMax() which takes Student[] as parameter and returns the name of
the student with highest total.
• main() method, that creates 3 instances of Student, stores them in an array and
invokes the method getMax() by passing that Student[]
import java.util.*;
ram 67 78 90
latha 72 79 89
sonu 77 92 45
Output:
latha
Page 40
Public test case 2:
rahul 23 45 67
divya 34 48 69
rohit 45 51 78
Output:
rohit
s1 34.5 56.7 68
s2 45.4 66 78
s3 73 45.4 56
Output:
s2
s2 38.5 56.7 90
s1 45.4 66 78
s3 73 45.4 56
Output:
s1
Solution:
import java.util.*;
class Student {
private String name;
private double marks [];‘
public Student(String name, double[] marks) {
this.name = name;
this.marks = marks;
}
public String getName() {
return (this.name);
Page 41
}
public double findTotal() {
double total = 0.0;
for (double i : this.marks) {
total = total + i;
}
return (total);
}
}
class Test {
public static String getMax(Student[] student) {
double max_marks = 0.0;
String max_student = "";
for (Student i : student) {
double total_marks = i.findTotal();
if (total_marks > max_marks) {
max_student = i.getName();
max_marks = total_marks;
}
}
return max_student;
}
public static void main(String[] args) {
Student[] arr = new Student[3];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 3; i++){
String name = sc.next();
double[] m = {sc.nextDouble(), sc.nextDouble(), sc.nextDouble()};
arr[i] = new Student(name, m);
}
System.out.println(getMax(arr));
}
}
Page 42
10. Employee e1 does a set of projects. Employee e2 also does all the projects did by e1
except the first project, in place of which e2 does another project. Write a program that
defines two classes Employee and Test. Define copy constructor to create e2 from e1 in
such a way that changing the values of instance variables of either e2 or e1 should not
affect the other one. The code takes name of e2 and new project done by e2 as input.
Complete the program as specified below.
Test Cases
Sneha PJ5
Output:
Surya: PJ1
Sneha: PJ5
Test Cases
Rohan PJ7
Output:
Surya: PJ1
Rohan: PJ7
Page 43
Private test case 1 (Input):
Megha PJ4
Output:
Surya: PJ1
Megha: PJ4
Srija PJ0
Output:
Surya: PJ1
Srija: PJ0
Template Code
import java.util.*;
class Employee{
String name;
String[] projects;
//***** Define constructor(s) here
public void setName(String n) {
name = n;
}
public void setProject(int index, String proj) {
projects[index] = proj;
}
public String getName() {
return name;
}
public String getProject(int indx) {
return projects[indx];
}
}
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] proj = {"PJ1", "PJ2", "PJ3"};
Employee e1 = new Employee("Surya", proj);
Employee e2 = new Employee(e1);
Page 44
e2.setName(sc.next());
e2.setProject(0, sc.next());
System.out.println(e1.getName() + ": " + e1.getProject(0));
System.out.println(e2.getName() + ": " + e2.getItem(0));
}
}
Solution:
import java.util.*;
class Employee{
String name;
String[] projects;
public Employee(String n, String[] proj){
name = n;
projects = proj;
}
public Employee(Employee e){
this.name = e.name;
int l = e.projects.length;
this.projects = new String[l];
for(int i = 0; i < l; i++){
this.projects[i] = c.projects[i];
}
}
public void setName(String n) {
name = n;
}
public void setProject(int index, String proj) {
projects[index] = proj;
}
public String getName() {
return name;
}
public String getProject(int indx) {
return projects[indx];
}
}
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] proj = {"PJ1", "PJ2", "PJ3"};
Page 45
Employee e1 = new Employee("Surya", proj);
Employee e2 = new Employee(e1);
e2.setName(sc.next());
e2.setProject(0, sc.next());
System.out.println(e1.getName() + ": " + e1.getProject(0));
System.out.println(e2.getName() + ": " + e2.getItem(0));
}
}
Page 46
11. Employee e1 does a set of projects. Employee e2 also does all the projects did by e1
except the first project, in place of which e2 does another project. Write a program that
defines two classes Employee and Test. Create copy of e1, say it as e2 in such a way
that changing the values of instance variables of either e2 or e1 should not affect the
other one. The code takes name of e2 and new project done by e2 as input. Complete
the program as specified below.
• Class Employee that implements Cloneable interface and has the following mem-
bers:
– Private instance variables String name and String[] projects to store name and
projects respectively
– Define required constructor
– Define accessor methods getName( ) and getProject( ) to get name of em-
ployee and project at specific index.
– Define mutator methods setName( ) and setProject( ) to set name of em-
ployee and project at specific index.
– Override the method clone( )
• Class Test that has the method main which does the following:
– Two objects of Employee e1 and e2 are created. e2 is created using e1.clone()
– Input to update name of e2 and second item bought by e2 are taken Names
of e1, e2 and first project done by e1 and e2 are printed.
Template Code
Solution:
Page 47
import java.util.*;
class Employee implements Cloneable{
String name;
String[] projects;
public Employee(String n, String[] proj){
name = n;
projects = proj;
}
public void setName(String n) {
name = n;
}
public void setProject(int index, String proj) {
projects[index] = proj;
}
public String getName() {
return name;
}
public String getProject(int indx) {
return projects[indx];
}
public Employee clone() throws CloneNotSupportedException{
Employee e = (Employee)super.clone();
e.projects = e.projects.clone();
return e;
}
}
public class Test {
public static void main(String[] args) throws CloneNotSupportedException{
Scanner sc = new Scanner(System.in);
String[] proj = {"PJ1", "PJ2", "PJ3"};
Employee e1 = new Employee("Surya", proj);
Employee e2 = e1.clone();
e2.setName(sc.next());
e2.setProject(0, sc.next());
System.out.println(e1.getName() + ": " + e1.getProject(0));
System.out.println(e2.getName() + ": " + e2.getProject(0));
}
}
Page 48