Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
100%
(1)
100% found this document useful (1 vote)
2K views
Lex All Assignment Answers
Uploaded by
Mayuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Lex All Assignment Answers For Later
Download
Save
Save Lex All Assignment Answers For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
100%
(1)
100% found this document useful (1 vote)
2K views
Lex All Assignment Answers
Uploaded by
Mayuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Lex All Assignment Answers For Later
Carousel Previous
Carousel Next
Save
Save Lex All Assignment Answers For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 90
Search
Fullscreen
Java programming DAY 1. class Tester ( public static void main(String[] args) { System.out printin(*My name is Sonakshi Gupta\n My designation is System Engineer."), 1/ \mplement your code here } J 2. class Tester { public static void main(String[] args) { ‘System.out printin("House no: 761 \n Ward No. 37 \n City: Jammu \n Pin code: 180007"), // implement your code here 1. class Tester { public static void main(Stringl] args) { int principal-5000; float rate= 10.0f; byte times 5; float interest= 0.0f, ‘System. out printin((principal*rate*time)/100);, // \mplement your code here , 2. class Tester { Public static void main(Stringl] args) { int principal=5000; float rate= 10.0f; byte time= 5; float interest= 0.0f; ‘System.out.printin((prineipal*ratettime)/100), int prin=3250, float t= 7.0f; byte t= 3; float Sinterest= 0.0f; ‘System.out.printin((prin*r*t)/100); // implement your code here } , 3. class Tester { public static void main(String[] args) { byte ra float area=(float) (3.14%rad*rad); ‘System out printin(area); byte radius=10, float ar=(Fioat) (3.14*radiustradius), ‘System.out printin(at); // implement your code here v7} Edit with WPS Office) 4. class Tester { public static void main(Stringl} args) { float fahr= 32; float far= 50; float cels= (float) (((fahr-32)/9)*5); float)(((far-32)/9)*5); System.out printin(cels); ‘System out printin(cel; Day3 1. class Tester { public static void main(Stringl] args) { int num? =3; int num2: it num3= if{oumt>num2) if{numt>num3) {System.out printin(num’+* is the maximum number’); } else {System out printin(num3+ * is the maximum number’); } else ( {System.out.printin(num2+ is the maximum number’); ) , 2, REVERSE OF A NUMBER class Tester ( public static void main(String[] args) { int inputNumber = 7865; int sumOfDigits = 0; int temp = 0; while (inputNumber > 0) { inputNumber % 10; sumOfDigits = sumOfDigits*10+ temp; inputNumber = inputNumber / 10; } ‘System.out.printin(’Sum of digits are :"+ sumOfDigits); ) 3, SUM OF DIGITS IN A NUMBER]| USING WHILE LOOP. class Tester ( public static void main(String[] args) { v7} Edit with WPS Officeint inputNumber int sumofDigits = int temp = 0; 865; while (inputNumber > 0) { temp = inputNumber % 10; sumOfDigits = sumOfDigits*10+ temp; inputNumber = inputNumber / 10; ¥ ‘System.out.printin("Sum of digits are :* + sumOfDigits); a 4, INFINITE WHILE LOOP class Tester ( Public static void main(Stringl] args) { int totalCost = 0; char wantToAddFooditem ="; int unitPrice = 10; int quantity = while (wantToAddFooditem == 'Y') { totalCost = totalCost + (quantity * unitPrice); ‘System.out printin(‘Order placed successfully’ System.out printin("Total cost: "+ totalCost); ‘System.out printin(’Do you want to add one more food item to the order?” } ‘System.out.printin("Thank you for ordering the food! It will reach you shortly.."); , TREATING ININITE WHILE LOOP class Tester ( Public static void main(Stringl] args) { int totalCost = 0; char wantToAddFooditem =Y; int unitPric int quantity = 1; while (wantToAddFooditem == 'Y) ( totalCost = totalCost + (quantity * unitPrice); ‘System out printin(‘Order placed successfully") System.out printin("Total cost: "+ totalCost); ‘System. out printin(’Do you want to add one more food item to the order?" wantToAddFooditem = 'N; } System out printin("Thank you for ordering the food! it wll reach you shortly") J 5, SUM OF DIGITS IN A NUMBER]| USING DO-WHILE LOOP class Tester { Public static void main(String[] args) { int inputNumber = 96: int sumOfDigits int temp = 0; v7} Edit with WPS Officedo{ temp = inputNumber % 10; sumoOfDigits inputNumber } while (inputNumber > 0); System.out printin(’Sum of digits :* + sumOFDigits); } , 6. FOR LOOP EXECUTION class Customer { public static void main(String[] args) { // The below code generates customerid int totalNoOfCustomers = 12; String customerid ="; for (int counter = 1; counter <= totalNoOfCustomers; counter++) { if (counter <= 9) customerid = "CO" + counter, else customerid = °C" + counter, ‘System.out printin(’Customer Id for customer *+ counter + is * + customerid); , 7. NESTED FOR LOOP|| PATTERN FORMATION class Tester ( public st. ic void main(Stringl] args) { for (int row = 1; row <= 4; row#+) { fort (int value = 1; value <= 5; value++) { ‘System.out.print(value + "“); } System.out printing; , class Tester ( Public static void main(String[] args) { for (int row = 1; row <= 4; row++) { for(int value = 1; value <= row; value++) { ‘System. out print(value + **); } ‘System out printin(); } , 8, FACTORIAL OF A NUMBER class Tester ( Public static void main(String[] args) {temp= temp*a; a } ‘System.out.printin(temp); // implement your code here } ) 9, GEOMETRIC SEQUENCE class Tester ( public static void main(String[] args) { 5: ‘System.out.printin(z); int x= (int)Math pow(c); zeatx; , , *SELECTION CONTROL STRUCTURE ASSIGNMENT* 1. class Tester ( Public static void main(Stringl] args) { {sum= a+b; , else{ ‘sum= 29(atb); } ‘System.out printin(sum); ) ) 2. class Tester { Public static void main(String[] args) { inta=1, b= float di float x1=0F, float x2=0F, dis= (Float)((b*b)-4¥a*c); System. out printin(dis), if(dis: { ‘System.out printin(‘the value of roots are equal"); } else if(dis>0) { ‘System.outprintin(‘the value of roots are unequal: "); else v7} Edit with WPS Office‘System.out.printin(the value of roots are not real"); loat)((-b+dis)/(2*a)); joat)(Cb-dis)/(2*a); System out prntin(x1} System out prntin(x2); } d 3. class Tester { public static void main(String[] args) { x= bt; else if(b==) { xc, else if(c==7) } else { x= tbr; } ‘System out printin(); 4-class Tester ( Public static void main(Stringl] args) { char foodType=! int output= 0; int total=0; int extra=( int extra? } if quan>= 1) { total= cost* quan; v7} Edit with WPS Office‘System.out.printin(‘total cost is $* + total); } else( ‘System.out printin(“invalid selection’) output =-1; ‘System out printin("total bill amount is*+ output); ‘System.out printin(‘order cannot be placed"); ist=1) i (dist<=3) ‘ ‘System.out.printin(‘no delivery charges"); dice if(diste=6) ‘System.out printin(‘Additional delivery charges for $1 per km"); extra= disttextral; else if(dist<=m) { System.out printin(‘Additional delivery charges of $3 and $2 per km’); extra= 3+ ((dist-6)*extra2); } outputs total+ extra; ‘System.out printin("your order has been successfully placed worth $" + output); else { , } ‘System.out.printin(“invalid selection * +" order cannot be placed"); , 5. class Tester { public static void main(Stringl] args) { int accnmbr=1001; int acebal= 250000; int salary= 40000; String loantype= “Car int loanAmExpected- 300000, int emis= 30; int count=0; int eligibleloanAmount= 500000; int eligibleEmis= 36; int a= aconmbr; while(a!=0) a=a/10; count++; J if(coun { int firstdigit-acenmbr/1 000; if(firstdigit: 4) ‘System.out printin("You can proceed further *) Edit with WPS Office} } else{ ‘System.out printin(’LOAN WILL NOT BE PROVIDED! , if(accbal>=1000) { ‘System.out printin("You are eligible for loan! d else( ‘System. out.printin("LOAN WILL NOT BE PROVIDED!!"); } ‘System.out.printin(*Checking whether the bank approves for loan’); if(loanAmExpected<= eligibleloanAmount) { if(emis
=5) { n5=2/5, 2=2-(n5"5); } } for(int i=1; i<=%; 4+) if(nt>x) { ‘System.out printin(’-1"); } v7} Edit with WPS Officeelset ‘System.out print("$1 notes needed= System out printin(nt); if(n5>y) { ‘System.out printing else( ‘System out print("$5 notes needed="); ‘System. out printin(n5); 7. class Tester { public static void main(String[] args) { int day=1; int month=9; int year=15, if(mont 5 month==7]| month { iN(d { day=1 month=month + 1; ) else day=dayt; &8 (year%100!=0)) || (year%401 System.out printin('Leap year’); if(da‘System.out print(day + * ‘System out print(month +"), ‘System.out print("20" + year); 8. class Tester ( public static void main(String[] args) { int 0) ifln% ‘System.out printin(’Zoom"); 08& n%: { Mise if{n% t ‘0) System out printin(Zap"); ) System.out printin('Zip'), else if(n%: { } else ‘System out printin("invalid’); } } , *ITERATION CONTROL STRUCTURE* 1. class Tester { public static void main(Stringl] args) { 16763; v7} Edit with WPS Office"610; Juo*10)+rem,; ‘System out printin(*Reverse of given number is: "+ quo), if(quo=: ‘System out printin(n + "is a pallindrome number"); else System.out printin(n + "is not a pallinérome number"); 2. class Tester { Public static void main(Stringl] args) { intheads=150, legs=500; || (legs%2!=0)) ‘System out printin("The number of chickens and rabbits cannot be found"); i(eadsetens) (heads: } else( 1 (int)((legs+(-2*heads))/2); c= (int)(heads-); System.out printin(*Chickens System.out printin( Rabbit “40) +0 3. class Tester { Public static void main(Stringl] args) { int 2-123, n=a, rem=0, temp=0, sum=0; while(n!=0) + sum); ‘System out printin(a +" is divisible by sum of its digits"); else ‘System.out printin(a +" is not divisible by sum of its digits"); 4. class Tester { public static void main(String[] args) { v7} Edit with WPS Office‘System out printin(x + "is a seed of "+ y); } else{ ‘System.out printin(x + "is not a seed of "+ y); } d 5. class Tester { public static void main(Stringl] args) { double temp=0; int sum=0; rem=2%10; aa/10; temp=Math.pow(rem, 3); sum=(int) (sum+ temp); } System.out printin(sum); if(eum==n) {System.out.printin(n + *is an Armstrong number’); } else{ ‘System. out printin(n + "is not an armstrong number’), } , 6. class Tester ( public static void main(String[] args) { String a="1623"; int sum: for(int { int temp= a.charAt()” sum=sum+(temp*temp); } if(sum%9==0) { ‘System out printin(a + "is a lucky number’); } else { ‘System.out printin(a + "is not a lucky number’); } v7} Edit with WPS Office) ) 7. class Tester { public static void main(String[] args) { int num1=7, num2=9, lem=0, max=0; if{numt>num2) maxenumt; else max=num2; max=maxtstep; } ‘System.out printin(lern); , 8. class Tester { Public static void main(String[] args) { intn=5; for(int i=1; ic=ni+4) ‘System.out.print(*" + } ‘System.out.printinQ;, DAY4 1. CLASS INTRODUCTION TRYOUT class Customer { public String customerid; public String customerName; public long contactNumber; Public String address; Public void displayCustomerDetails() { ‘System out printin(*Displaying customer details \ntwrstersttensevenenrentenss?) ‘System.out.printin(’Customer Id: "+ customerid); ‘System out printin(*Gustomer Name : "+ customerName); ‘System out printin(*Contact Number :" + contactNumber); System out printin(‘Address :* + address); ‘System.out printin(); v7} Edit with WPS Officeclass Tester ( public static void main(Stringl] args) { 1/ Object creation Customer customer = new Customer(); 1/ Assigning values to the instance variables customer.customerid = "C101"; customer.customerName = "Stephen Abram”; ‘customer. contactNumber = 7856341287L; customer.address = "D089, St. Louis Street, Springfield, 62729"; // Displaying the customer details ‘customer. cisplayCustomerDetails(); // Move the above statement immediately after the object creation 1/ statement and observe the output, , 2. CLASS AND OBJECT-EXERCISE 1 class Customer { Public String customerid; public String customerName; Public long contactNumber; Public String address; public void displayCustomerDetails() { ‘System.out.printin(‘Displaying customer details \n*#+##ssttsettanesseeesseie); ‘System.out printin(*Customer Id: "+ customerid); ‘System.out.printin(’Customer Name : “+ customerName); ‘System.out printin(*Contact Number :* + contactNumber); System out printin(*Address : "+ address); ‘System.out printin(); ) class Tester { Public static void main(String[] args) { 1/ Object creation ‘Customer customer = new Customer(); 1/ Assigning values to the instance variables customer.customerid = "C101"; customer.customerName = "Stephen Abram"; customer.contactNumber = 78563412871; customer.address = "D089, St. Louls Street, Springfield, 62729"; // Displaying the customer details, customer.cisplayCustomerDetails(); // Move the above statement immediately after the object creation // statement and observe the output Edit with WPS Office) 3, LOCAL VARIABLE-TRYOUT class Demo { public int vari; // instance variable of the class public void printValue() { int var2 = 20; // Local variable of the method System.out printin(vart); System out printin(var2); // Local variable is accessible only inside 11 the method } ) class Tester ( public static void main(String args[) { Demo demo = new Demo); demo.var' = 10; // Instance variable can be accessed from outside the 7/ Cass with the help of object demo printValue(); // Local variables cannot be accessed outside a method 7/ Below lines will lead to a compilation error saying that var2 is not 11 afield or variable 1/ System.out printin(demo.var2}; J/ System out printin(var2), , ) 4, *METHODS- EXERCISE 1* class Calculator { public double findAverage(int number’, int number2, int number3) { double sum= (number1 +number2+number3); double average= sumn/3; double roundoff= Math.round(average*100.0)/100.0; return roundoff; } ) class Tester { public static void main(String args[) { Calculator calculator = new Calculator(); double x=calculator.findaverage(12.8,15); ‘System.out.printin(x); // invoke the method findAverage of the Calculator class and display the average Edit with WPS Office1, CONSTRUCTOR AND THIS KEYWORD: EXERCISE 1 class Customer { public String customerid; public String customerName; public long contactNumber, public String address; Customer(String customerName, long contactNumber, String address) { customerid= customerid; this.customerName= customerName; this.contactNumber= contactNumber; this address= address; public void displayCustomerDetails(){ ‘System.out printin( Displaying customer details"); ‘System out printin(*Customer Id:" + customerid); ‘System out printin(*Gustomer Name: "+ customerName); ‘System out printin(*Gontact Number : "+ contactNumber); System out printin(‘Address :* + address); ‘System.out.printin(); ) class Tester ( Public static void main(String[] args) { Customer customer = new Customer("Jacob", 627295480, “St. Louis, New York’); customer displayCustomerDetalls(); »METHODS-ASSIGNMENT* 1. class Order{ public int orderid; Public String orderedFood; Public double totalPrice; Public String status; public double calculateTotalPrice(int unitPrice) { ‘System.out.printin("Order Details’); totalPrice= unitPrice* (1+(5/100.0)); return totalPrice; } public void displayDetalls() { ‘System.out printin("Order id: "+ orderid); ‘System.out.printin(*Ordered Food: "+ orderedFood);, ‘System.out printin(*Order Status: * + status); Edit with WPS Office) class Tester{ public static void main(String args{]{ Order o= new Order(); o.orderid= 101; o.displayDetails(); ‘System.out.printin(‘Total Price: * +x); 2. class Restaurant{ Public float rating: public String restaurantName; public long restaurantContact; public String restaurantAddress; public void displayRestaurantDetails() { ‘System.out printin("Restaurant Details\nt#+t#+eves+esnetenenvaas), ‘System out printin(‘Restaurant Name: + restaurantName); ‘System out printin(*Restaurant Contact: "+ restaurantContact); ‘System out printin(*Restaurant Address: * + restaurantAddress); ‘System.out printinRating: "+ rating); } ) class Tester( public static void main(String args{}{ Restaurant r= new Restaurant(); r-restaurantName= "Dominos", rrestaurantContact= 2534512; rrestaurantAddress= "Janipur colony’; rrating= 4.3f, -displayRestaurantDetails(); } ) 3. class Calculator { public int num; Public int sumOfDigits() { int a=num,sem=0, sum=0; while(a sum=sum+rem; } return sum; , d class Tester ( public static void main(String args{) { Edit with WPS OfficeCalculator calculator = new Calculator(); calculator.num= 123; int x= calculator.sumOfDigits(); System out prntin(s); // Assign a value to the member variable num of Calculator class // Invoke the method sumOfDigits of Calculator class and display the output 4. class Rectangle ( public float length; public float width; public double calculateArea() { double a= length* width; double area Math.round(a*100.0)/100.0; return area; public double calculatePerimeter() double p= 2* (length+ width) double perimeter= Math.round(p*100.0)/100.0; return perimeter, } ) class Tester ( public static void main(String args[}) { Rectangle rectangle=new Rectangle(); //Assign values to the member variables of Rectangle class rectangle width= 5f; //invoke the methods of the Rectangle class to calculate the area and perimeter double x= rectangle.calculaterea(); double y= rectangle calculatePerimeter() //Display the area and perimeter using the lines given below ‘System. out printin(“Area of the rectangle is "+ x); ‘System.out.printin("Perimeter of the rectangle is "+ y); d ‘CONSTRUCTORS AND THIS KEYWORD* 1. class Order{ public int orderid; public String orderedFood; public double totalPrice; public String status; public Order() Edit with WPS Officestatus= "ordered"; , public Order(int orderid, String orderedFood) this orderld= orderld; this orderedFood= orderedFood; status="Ordered’; } ) class Tester( public static void main(String args[){ Order 01= new Order() System out printin(’Status of order 1:"+ 01 status); Order 02= new Order(1001, "Pizza"); System.out printin(’Status of order 2: "+ 02.status); System out printin(‘Order Id of order 2:* + o2.orderid); System.out printin(‘Ordered Food for order 2:* + 02.0rderedFood); 2. class Restaurant{ public float rating; public String restaurantName; public long restaurantContact; public String restaurantAddress; public void displayRestaurantDetails() { ‘System.out printin(‘Restaurant Details \nt+sreererstseseeesserest), System.out printinRestaurant Name: + restaurantName); ‘System out printin(*Restaurant Contact: "+ restaurantContact); System.out printin(’Restaurant Address: "+ restaurantAddress); System out printinRating: "+ rating); + public Restaurant(String name, long restaurantContact, String restaurantAddress, float rating) 4 restaurantName= name; this restaurantContact= restaurantContact; this restaurantAddress= restaurantAddress; ‘this rating= rating; , class Tester( public static void main(String args[){ Restaurant r= new Restaurant("Dominos",2534512,"Janipur colony’, 4.3f ); r-displayRestaurantDetails(; *ENCAPSULATION-EXRECISE 1* class Employee { private String employeetd; private String employeeName; private int salary; Edit with WPS Officeprivate int bonus; private int jobLevel; public String getEmployeeid({ return employeeld; } Public void setEmployeetd(String employeetd){ this.employeeld= employeeld; } public String getEmployeeName(){ return employeeName; , Public void setEmployeeName(String employeeName)( this.employeeName= employeeName; , Public int getSalary(X retum salary, } Public void setSalary(int salary){ this salary= salary, } Public int getBonus(){ return bonus; Public void setBonus(int bonus}{ this bonus= bonus; , public int getJobLevel(){ return jobLevel; } Public void setJobLevel(int jobLevel}{ this jobLevel= jobLevel; public void calculateSalary() { if (thisjobLevel >= 4) { this bonus = 100; yelse{ this bonus = 50; } this salary += this.bonus; ) class Tester ( Public static void main(String args[) { Employee employee = new Employee() employee setEmployeeld(’C101"); employee.setEmployeeName((Steve employee.setSalary(650); employee.setJobLevel(4); employee.calculateSalary(); v7} Edit with WPS Office‘System.out.printin("Employee Details"), ‘System out printin("Employee id: * + employee. getEmployeeid(); ‘System out printin(*Employee Name: " + employee getEmployeeName(); ‘System.out printin('Salary. * + employee. getSalary(); *ENCAPSULATION ASSIGNMENT* 1. class Order{ private int orderld; Private String orderedFood; private double totalPrice; private String status; Public void setOrderedFood{ String orderedFoody this orderedFood= orderedFood; , public String getOrderedFood(}{ return orderedFood; Public void setStatus(String status){ this status status; } public String getStatus(){ retum status; } public void setOrderld(int orderidy this orderid= orderid; } public int getOrderld({ return orderld; } public double calculateTotalPrice(int unitPrice) { ‘System out printin("Order Details") totalPrice= unitPrice* (14(5/100.0)); return totalPrice; } class Tester( public static void main(String args[)}{ Order o= new Order(); o.setOrderid(101); o.setOrderedFood( "Pasta", o.setStatus(‘ordered’); double x= 0.calculateTotalPrice(100); System out printin‘Order Id: "+ 0.getOrderld(); System out printin("Ordered Food: "+ o,getOrderedFood(); System out printin("Order Status: * + o.getStatus(); ‘System.out.printin(‘Total amount to be paid: * + x); Edit with WPS Office) , 2. class MovieTicket { private int movield; private int noOfSeats; private double costPerTicket; public void setMovield(int movield){ ‘this movield= movield; , Public int getMovield( return movield; } Public void setNoOfSeats(int noOfSeats){ this noOfSeats= noOfSeats; } public int getNoOfSeats(){ return noOfSeats; } Public void setCostPerTicket(double costPerTicket){ this.costPerTicket= costPerTicket; } Public double getCostPerTicket(){ retum costPerTicket; } Public MovieTicket(int movield, int noOfSeats) { this. movield= movield; this.noOfSeats= noOfSeats; public double calculateTotalAmount() { double a; switch(movield) { case 111: costPerTicket= 7; break; case 112: costPerTicket: break; case 113: costPerTicket=8.5, break; default: costPerTicket d a= costPerTicket*noOfSeats; ‘double amount= a*(1+(2/100.0)); return amount, , , class Tester ( Public static void main(String[] args) { MovieTicket movieTicket = new MovieTicket(112, 3) movie Ticket setCostPerTicket(7); double amount = movieTicket calculateTotalAmount(); Edit with WPS Officeif (amount==0) ‘System.out printin('Sorry! Please enter valid movie Id and number of seats") else System.out printin("Total amount — for -—_—booking s+ Math.round(amount*100)/100.0); } d *STRING METHODS-TRYOUT* class Tester { public static void main(String args{) { J/ length String str = "Welcome"; System.out printin(str length); 1 concat)) String s = "Hello® s.concat(" World’); System.out printin(s); 1/ sis stil "Hello" // String objects are immutable which means they cannot be changed // Hete, when we concat the two strings a new string object gets created String s1 = s.concat("World’); System out printin(s) 11 + operator ci String fname = *Jack’; String Iname = “Black”; ‘System out printin(fname +"* + Iname); also be used for string concatenation J/ equals) ‘System out printin(s.equals( "Hello // equals compares only the values of the strings String s2 = new String("Hello") ‘System.out printin(s.equals(s2)); // == compares the object reference and will return false in the below I case ‘System. out.printin( 82); J/ equalsignoreCase() ‘System.out.printin(s.equalsignoreCase(‘hello’)); // toLowerCase() and toUpperCase() ‘System.out.printin(str-toLowerCase()); ‘System. out printin(str-toUpperCase()); J substring() String subs = "Learning is fun*; ‘System. out printin(subs.substring(4, 8)); ‘System out printin(subs substring(4)); 1/ charat() System.out printin(subs.charAt(10)); 17 contains() ‘System.out printin(subs.contains(‘is")), Edit with WPS Office1/ replace), ‘System. out printin(subs.replace(','k)); } , *STRING EXERCISE* class Tester{ public static String removeWhiteSpaces(String str){ String noSpaceStr = str.replaceAli(’\\s","*); // using built in method //implement your code here and change the return value accordingly return noSpacestr, } Public static void main(String args{}){ String str="Hello Howare you str = removeWhiteSpaces(str); System.out printin(str), , DAY6 *MULTIDIMENSIONAL ARRAY-TRYOUT* /Program_o illustrate the use of multidimensional array class Tester ( Public static void main(Stringl] args) { 17 Declaring and initializing 20 array int] dayWiseTemperature = new intl] {{ 29, 21 },( 24, 23 } { 26, 22}, 28, 23}, 29, 24}.{ 23, 20}, 29, 21); 1/ Displaying 2D array for (iti = 0;1< 7; #4) { for (int = 0;) < 2:j+4){ ifG==0) ‘System out printin(’Max Temperature is" + dayWiseTemperaturelil] +" on day * +i); else ‘System.out.printin(‘Min Temperature is" + dayWiseTemperaturelili]+" on day "+); } , *ARRAY-EXERCISE 1* class Tester { public static int calculateSumOfEvenNumbers(intl] numbers} knumbers.length; i++) int a=numbers[i]%2; if@ { } sum=sum+numbers[i]; v7} Edit with WPS Office} return sum; } public static void main(String[] args) { int] numbers = {68,79 86,99,23,2,41,100}; ‘System.out printin(*Sum of even +calculateSumOfEvenNumbers(numbers)); } , *STRING ASSIGNMENT* 1. class Tester( public static String moveSpecialCharacters(String str}{ String regex= "['a-2A-Z0-9\\s4]'; for(int =O; ic str.lengthQ; i+) { char ch= str.charAt(); if(String.valueOf(ch) .matches(regex)) { specialCharacters= specialCharacters+ch; elset inputData= inputDatatch; } String result= inputData+specialCharacters; return result, } Public static void main(String argsI}{ String str = "He@#Slo!*8"; ‘System out printin(moveSpecialCharacters(str)): 2. class Tester( public static boolean checkPalindrome(String str){ int length str.length(); rev= rev + str.charAt(i): if (strequals(rev)) return true; return false; + public static void main(String args[)){ String str = radar’, v7} Edit with WPS Office numbers’if(checkPalindrome(str)) System. out printin("The string isa palindrome!’ else ‘System.out printin( ‘The string is not a palindrome!") } ) 3, class Tester { public static String reverseEachWord(String str){ String words{] = str.split(” String reversedStrin« for(int i=0; iewords.lengthi++) { String word= words; String reverseWord: for(int j=word.length() iiP=Oj-) reverseWord=reverseWord+ word.charAt(); } reversedString= reversedStringt reverseWord# **; return reversedString trim); ¥ public static void main(String args[){ String str = "Ilove programming’, System out printin(reverseEachWord( sti); } d 4. class Tester { public static int findHighestOccurrence(String str){ int counter=0; for(int i-O;
max_counter) { } } return max_counter, ‘max_counter=counter; } Public static void main(String args{ String str = "success"; ‘System out printin(findHighestOccurrence(str); 5. class Tester{ public static String removeDuplicatesandSpaces(String str){ v7} Edit with WPS OfficeString result =" for (inti = 0;i< striength(); i++) { if(result.contains(String valueOf(str.charAt()))) { result += String valueOf{(str.charAt(i)); } } return result.replace(* } public static void main(String args[)}{ String str = “object oriented programming’; ‘System.out.printin(removeDuplicatesandSpaces(str)); *ARRAY-ASSIGNMENTS* 1. class Teacher ( private String teacherName; private String subject; private double salary, Public void setTeacherName(String teacherName){ this.teacherName= teacherName; } public String getTeacherName(){ return teacherName; } public void setSubject(String subject){ this.subject= subject, } public String getSubject( return subject; } Public void setSalary(double salary){ this.salary= salary; public double getSalary(){ return salary, + public Teacher(String teacherName, String subject, double salary) { this.teacherName= teacherName; this subject= subject, this.salary= salary, , class Tester ( Public static void main(Stringl] args) { Teacherl] teacherobjects= new Teacher teacherobjects{0]= new Teacher(‘Alex, "Java Fundamental, 1200.0); "RDBMS, ", 800.0 ) teacherobjects|2]= new Teacher('Sam, "Networking, °900.0 ); v7} Edit with WPS Officeteacherobjects[3]= new Teacher("Maria, ","Python, "900.0 ); for(int i=0; ic teacherobjects.length; i++) { ‘system. out print(‘Name: "+teacherobjectsti].getTeacherName()+* ‘System out print(‘Subject: “tteacherobjectslil. getSubject(}+"*); System out printin('Salary: “tteacherobjects[il. getSalary(}+ *); } , 2, class Tester { public static doublel] findDetails(double[] salary) { //implement your code here and change the return value accordingly doubiel] arr = new double[3]; double avg = 0; for(int i = 0; < salary.length; i++)( salarylil; = salary length -1) avg /= (double)(i+1); arr{0] = avg; double greater = 0, lesser = 0; for(double data: salary){ if(data > avg) greater++; if(data < avg) lesser++; arti] = greater; anf(2]= lesser, return ar, } Public static void main(Stringl] args) { doublel] salary = { 235000, 25080.0, 28760.0, 22340.0, 19890.0 }; doublel] details = findDetalls(salary); ‘System out printin("Average salary: + details[0)); ‘System.out printin(’Number of salaries greater than the average salary: "+ details[1)); ‘System.out.printin(*Number of salaries lesser than the average salary: “+ details{2)); class Tester { public static int] findLeapYears(int year)( //implement your code here and change the return value accordingly int{] ans = new int{15}; int first = year, while(true){ if(first % 4 == 0} if(first % 100 == 0 if(irst % 400 == 0) break; Jelse break; Edit with WPS Officeans[a++] = } retum ans; } Public static void main(Stringl] args) { int year = 1684; int{] leapYears, leapYears=findL eapYears(year); for (int index = 0; indexcleapYears.length: index++ ){ ‘System .out printin(leapYears[index]); ) } , 4. class Student{ private intl] marks; private chart] grade; public ntl] getMarks() { return marks; , public void setMarks(intl] marks) { this. marks = marks; , public char] getGrade() { retum grade; ) public void setGrade(charl] grade) { this. grade = grad ) public Student(int(] marks) { this. marks= marks; grade = new charlmarks.length]; } public void findGrade() 4 for(int i=0; ic marks.length,; i++) { if(marks[i]>=92) { gradeli]= tise i{marksib=85 &8 marksl82) bral Use i(marsP=70 && marks 88) fyadels Bs Use i(marksP=65 &8 marks 70) ( gradell='C; v7} Edit with WPS Office) else { gradel]= Di class Tester( public static void main(Stringl] args) { intl] marks = { 79, 87, 97, 65, 78, 99, 66}; Student student = new Student(marks); student findGrade(); ‘System.out printin(’Grades corresponding to the marks are ="); charl] grades = student getGrade(); for (int index = 0; index < grades. length; index++) { System. out print(gradeslindex] + **); ) ) ) 5. class Tester { public static intl] findNumbers int nurn1, int num2) { int{] numbers = new int{6]; // \mplement your code here if(numt > num2) return numbers; if(oumt >= 100 || num2-< 10) return numbers; inta=0; for(int i = nut >= 10? num1+1 : 10; 1 <= num? 88 < 100; i+) iff % 5 == 0 && i % 3 == 0) numberslat4] =i; } return numbers; } public static void main(Stringl] args) { intnumt indNumbers(nurn1, num2); if (numbers[o] == 0) { ‘System.out printin("There is no such number!" Jelse{ fort (int index = 0; index if (numbers[index) break; } ‘System.out.printin(numbers|index)); numbers length - 1; indext+) ( of b + , 6. class Tester {public static int findTotalCount(intl] numbers) { int length= numbers. length; ; iclength-1; i++) if(numbers{i]==numbersli+1)) count= count+1; , J return count; a public static void main(Stringl] args) { intl] numbers = 1, 1, 5, 100,-20, 6, 0,0 System.out printin("Gount of adjacent occurrence: “HfindTotalCount(numbers)); d 7. class Tester{ Public static Stringl] findPermutations(String str}{ //implement your code here and change the return value accordingly Stringl] ans = new String[6]; inta=0; for(int i = 0; < str-lengthQ; i+4){ ‘String x = ““+str.charAt(i) for(int ifG for(int k = 0; k< str.lengthQ; k++){ if(k ) ) int duplicates = 0; for(int = 0;i
= 4.5 && driver. getAverageRating()<=5){ rewardAmount= 10*driver.getAverageRating(); } else if(criver getAverageRating()>= 4 && driver getAverageRating()<4.5){ tewardAmount= 5¢driver getAverageRating); } else{ rewardAmount= } Edit with WPS Office} else if(cabServiceName.equals(‘Aber’))( if(driver.getAverageRating()>= 4.5 && driver getAverageRating()<=5){ rewardAmount= 8*driver.getAverageRating(); } else if(driver.getaverageRating()>= 4 88 driver getAverageRating()<4.5{ rewarcAmount= 3¥driver.getAverageRating(); } else{ rewardAmount= 0.0; d else rewardAmount=0.0; } bonus= Math round(rewardAmount*100.0)/100.0; return bonus; ) class Driver { private String driverName; private float averageRating; public Driver(String driverName, float averageRating) this.driverName=driverName; this averageRating=averageRating; ) public String getDriverName({ return this.criverName; } public void setDriverName(String driverName){ this.driverName=driverName; } Public float getAverageRating(){ return this.averageRating, } Public void setAverageRating(float averageRating){ this averageRating=averageRating; ) //D0 NOT MODIFY THE METHOD /Nout exercise might not be verified if the below method is modified Public String toString(){ return “Driver\ndriverName: “+this.driverName+"\naverageRating, “+this.averageRating; , , class Tester ( public static void main(String args{}{ CabServiceProvider cabServiceProvider1 = new CabServiceProvider("Halo”, 50); Edit with WPS OfficeDriver drivert = new Driver(‘Luke', 4.8) Driver driver2 = new Driver("Mark",4.2f); Driver driver3 = new Driver(‘David', 3.9f} Driverl] driversList = { driver, driver2, driver3 } for (Driver driver: driversList) ( ‘System out printin(‘Driver Name: “+driver.getDriverName()); double bonus = cabServiceProvider1.calculateRewardPrice( driver); if (bonus>0) ‘System. out printin("Bonus: $"+bonus+"\n"); else ‘System.out printin("Sorry, bonus is not available!"); } [Create more objects of CabServiceProvider and Driver classes for testing your *ASSIGNMENTS* STATIC 1, package aggregation; class Food { Public String foodName; public String cuisine; Public String foodType; public int quantityAvailable; public double unitPrice; } class Ordert private static int orderCounterld; private int orderid; private Food!) orderedFoods; private double totalPrice; private String status; static( orderCounterld= 100; , public Order(}{ , Public Order(Foodl] orderedFoods){ this.orderedFoods= orderedFoods; orderid= ++orderCounterid; , Public static int getOrderCounterld() { return orderCounterid; ) Public static void setOrderCounterld(int orderCounterld) { Order.orderCounterid = orderCounterid; ) public int getOrderld() ( return orderld; ) Public void setOrderid(int orderld) { this. orderld = orderld; ) public Food] getOrderedFoods() { v7} Edit with WPS Officereturn orderedFoods; ) public void setOrderedF oods Foodl] orderedFoods) { this.orderedFoods = orderedFoods; ) public double getTotalPrice() { return totalPrice; , Public void setTotalPrice (double totalPrice) { this.totalPrice = totalPrice; ) Public String getStatus() { return status; public void setStatus(String status) { this.status = status; } public static int getTotalNoOfOrders({ retumn(Order.orderCounterid - 100); ) public double calculateTotalPrice(String paymentMode) { double foodPrice = 0; double finalPrice = 0; float serviceCharge = Of, int unitPrice = 100; foodPrice+=unitPrice*1; if (paymentMode. equals(‘Credit Card’) || paymentMode.equals(“Debit Card") { serviceCharge = 2.0f, ) else if (paymentMode.equals("PayPal)) ( serviceCharge = 2.9f; } finalPrice = foodPrice+foodPrice*(serviceCharge/100); this setTotalPrice(finalPrice); return finalPrice; ) ) class Tester2 { public static void main(String args() { Food food! Food food2 Food food3 Food foods Food foods Food|] totalFoods = { food1, food2, food3, food4, foods }; Order order= new Order(); ‘System out printin(order.calculateTotalPrice(‘Credit Card")); ‘System. out printin(order.getOrderedFoods()); ) , 2 class Participant private static int counter; private String registrationid; private String name; private String city; private long contactNumber; Edit with WPS Officepublic Participant(String name, long contactNumber, String city) this name= name; this.contactNumber= contactNumber; this.city= city, registrationid= “D" + ++counter, 10000; } public static int getCounter() { return counter, } public static void setCounter(int counter) { Participant.counter = counter, } public String getRegistrationld() { return registration|¢; public String getName() ( return name; Public void setName(String name) { thisname = name; } Public String getCity() return city, } Public void setCity(String city) { this.city = city, ) Public long getContactNumber() { return contactNumber; Public void setContactNumber(long contactNumber) { this.contactNumber = contactNumber, } ) class AssignmentStatic2 ( public static void main(Stringl] args) { Participant participant] = new Participant( ‘Franklin’, 76567843231, "Texas’); Participant participant2 = new Participant("Merina’, 78904231121, “New York’); J/Create more objects and add them to the participants array for testing your code Participant{] participants = { participant, participant2 }; for (Participant participant : participants) { ‘System.out printin('Hi “+participant.getName()+"! Your registration id is “+participant.getRegistrationld(); 3. class Booking( private String customer ma v7} Edit with WPS Officeprivate int seatsRequired: private boolean isBooked; private static int seatsAvailable; statio{ seatsAvailable= 400; , public Booking (String customerEmailint seatsRequired){ this.customerEmail= customerEmai this. seatsRequired= seatsRequired; iff seatsRequirede=seatsAvailable){ isBooked= true; seatsAvailable= seatsAvailable-seatsRequired; else isBooked: false; } , public String getCustomerEmail() { return customerEmall, public void setCustomerEmail(String customerEmail) { this.customerEmail = customerEmail; ) Public int getSeatsRequired() { return seatsRequired; ) Public void setSeatsRequired(int seatsRequired) { this. seatsRequired = seatsRequired; d public boolean isBooked() { return isBooked; , Public void setBooked(boolean isBooked) { this.isBooked = IsBooked; ) Public static int getSeatsAvailable() { return seatsAvailable; Public static void setSeatsAvailable(int seats Available) ( Booking.seatsAvailable = seatsAvailable; , class Tester ( Public static void main(String[] args) { Booking booking! = new Booking("
[email protected]
’, 100); Booking booking2 = new Booking("
[email protected]
’, 350); 1/Create more objects and add them to the bookings array for testing your code Bookingl] bookings = { booking1, booking? }; for (Booking booking : bookings) { if (booking isBooked() { ‘System.out.printin(booking getSeatsRequired(}#" seats successfully booked for “tbooking.getCustomerEmail); } else{ ‘System.out.printin(’Sorry “+booking.getCustomerEmail(}#", required Edit with WPS Officenumber of seats are not available!"); ‘System.out.printin("Seats available: '+Booking getSeatsAvailable(); *ASSIGNMENTS* *AGGREGATION* 1. class Food { private String foodName; private String cuisine; ate String foodT ype: ate int quantityAvailable; private double unitPrice; public String getFoodName() { return foodName; ) Public void setFoodName(String foodName) { this.foodName = foodName; ) Public String getCuisine() { return cuisine; Public void setCuisine(String cuisine) { this. cuisine = cuisine; ) public String getFoodType() ( return foodType; Public void setFoodType(String foodType) { this.foodType = food ype; ) public int getQuantityAvailable() { return quantityAvailable; ) public void setQuantityAvailable(int quantityAvailable) { ‘this.quantityAvailable = quantityAvailable, public double getUnitPrice() { return unitPrice; , Public void setUnitPrice(double unitPrice) { this.unitPrice = unitPrice; ) ) class Address( fate String doorNo; private static String street; private static String city, private int zipcode, ‘Address(String doorNo, String street, String city, int zipcode) this.doorNo= doorNo; Address street= street, ‘Adgress.city= city, this.zipcode= zipcode; Edit with WPS Office) public String getDoorNol) { return doorNo; , Public void setDoorNo(String doorNo) { this.doorNo = doorNo; ) Public static String getStreet() { return street; ) public void setStreet(String street) { Address street = street; } Public static String getCity() { return city; ) public void setCity(String city) { Adgress.city = city; ) public int getZipcode() { return zipcode; ) ppublic void setZipcode(int zipcode) { this zipcode = zipcode; ) ) class Customert private String customerid; private String customerName; private long contactNumber; private Address address; public Customer( } public Customer(String customerid,String customerNameong contactNumber,Address address){ this.customerid= customerid; this.customerName= customerName, this.contactNumber= contactNumber, this.address= address; ) public Customer(String customerName.long contactNumber Address address) this.customerName= customerName, this.contactNumber= contactNumber, this.address= address; d public String getCustomerid() { return customerld; d Public void setCustomerld(String customerld) { this.customerid = customerld; , public String getCustomerName() { return customerName; Public void setCustomerName(String customerName) { this.customerName = customerName; ) Public long getContactNumber() { return contactNumber; Edit with WPS Officepublic void setContactNumber(long contactNumber) { this.contactNumber = contactNumber, ) Public Address getAddress() { return address; ) public void setAddress(Address address) { this.address = address; ) public boolean generateBill(Order order) { System.out printin(Bill details \ntmsseseee0), System.out.printin(Items ordered :); for (Food food : order.getOrderedFoods() { System.out printin(food.getFoodName(); ) double payableAmount = order.calculateTotalPrice(‘Credit Card’); ‘System. out.printin(Payable Amount : $* + (int) (payableAmount * 100) 7100.0); return true; ) Public void displayCustomerDetails(){ System.out.printin("Customer Id is: "+ getCustomerld(); System.out printin(*Customer Name is: "+ getCustomerName()); ‘System.out printin(“Contact Number is: "+ getContactNumber()); System.out printin(“Address is: "+ Address.getCity()+ "" + Address.getStreet(); ) ) class Order( private static int orderCounterid; private int orderid; fate Foodl] orderedFoods; private double totalPrice; private String status; private Customer customer; public Customer getCustomer() { return customer; public void setCustomer(Customer customer) { this.customer = customer, ) static{ orderCounterld= 100; ) public Order(){ ) Public Order(Food!] orderedFoods, Customer customer){ this.orderedFoods= orderedFoods; this.customer= customer; orderid= ++orderCounterid; ) public static int getOrderCounterld() { return orderCounterld; ) Public static void setOrderCounterld(int orderCounterid) { Order orderCounterid = orderCounterid; ) public int getOrdertd() ( return orderid; , Edit with WPS Officepublic void setOrderid(int orderte) { this.orderld = orderld; ) public Food] getOrderedFoods() { return orderedFoods; ) Public void setOrderedFoods Food] orderedFoods) { this.orderedFoods = orderedFoods; , Public double getTotalPrice() { return totalPrice; , Public void setTotalPrice (double totalPrice) { this.totalPrice = totalPrice: , Public String getStatus() { return status; ) public void setStatus(String status) { this.status = status; ) public static int getTotalNoOfOrders(){ return(Order.orderCounterid - 100); ) Public double calculateTotalPrice(String paymentMode) { double foodPrice = 0; double finalPrice = 0; float serviceCharge = Of, for (Food food : orderedFoods) ( foodPrice+=food.getUnitPrice()*1; ) if (paymentMode.equals( Credit Care!) || paymentMode.equals(‘Debit Carc’) { serviceCharge = 2.0F; ) else if (paymentMode.equals("PayPal’)) { serviceCharge = 2.9f; } finalPrice = foodPrice¥foodPrice”(serviceCharge/100); this setTotalPrice(finalPrice); return finalPrice; d public class Tester { , 2, class Author{ ivate String name; private String emailid; private char gender; public Author(String name, String emailid, char gender this.gender=gender, Public String getName() { return name; ) Public void setName(String name) { this.name = name; Edit with WPS Office) public String getEmailid() { return emailld, ) Public void setEmailid(String emailld) this.emailld = email ) public char getGender() { Feturn gender, ) public void setGender(char gender) { this.gender = gender, ) ) class Book{ ate String name; private double price; private int quantity, private Author author, public Book(String name, double price, int quantity, Author author){ this. name=name; this.price=price; ) public void displayAuthorDetails(){ System.out printin(‘Displaying author details"), System out printin(*Author Name: “+ author.getName()); System out printin(*Author Email id: “+ author.getEmailid(); System out printin(*Author Gender: "+ author. getGender(); ) Public String getName() { return name; public void setName(String name) { this.name = name; ) public double getPrice() { retum price; ) Public void setPrice(double price) { this.price = price, ) Public int getQuantity() { Feturn quantity, ) Public void setQuantity(int quantit ‘this.quantity = quantity; d Public Author getAuthor() { return author, ) public void setAuthor(Author author) { this.author = author; d class Testert ( Public static void main(String args[){ ‘Author author1= new Author( Joshua Bloch’,
[email protected]
’, 'M}); Edit with WPS OfficeBook book1= new Book("Effective Java 1", book .displayAuthorDetalls(); ) d 3, class Room { 15.0, 15, author); //implement your code here //Uncomment the below method after implementation before verifying 7/00 NOT MODIFY THE METHOD private int roomNo; private int capacity; private static int roomCounter; static{ roomCounter= 499; } public Room(X capacity’ roomN +4roomCounter, } public int getCapacity( { return capacity, } Public void setCapacity(int capacity) { this capacity = capacity, , Public static int getRoomCounter() { return roomCounter; hi Public static void setRoomCounter(int roomCounter) { Room.roomCounter = roomCounter, } public int getRoomNo() { return roomNo; } public String toString(){ return "Room \nroomNo: “+this.roomNo#"\ncapacity: “tthis.capacity, , J class Member { /fimplement your code here //Uncomment the below method after implementation before verifying //D0 NOT MODIFY THE METHOD private int memberid; v7} Edit with WPS Officeprivate String name; private Room room; public Member(int memberid, String name){ this memberld= memberid; ‘this:name=name; public int getMemberld() { return memberid; , Public void setMemberid{int memberld) { this. memberld = memberid; } public String getName() ( return name; } public void setName(String name) { ‘this.name = name; } Public Room getRoom() { return room; ) public void setRoom(Room room) { this.room = room; } public String toString()( return "Member\nmemberld: "+this.memberld+"\nname: "+this.name; } ) class Admin { implement your code here Public void assignRoom(Roomi] rooms, Member member){ for(Room room: rooms){ if(room.getCapacity()>0 && room. getCapacity(}<=4){ ‘member setRoom(room); room.setCapacity(room.getCapacity(-1); break; } } } ) class Tester (public static void main(String args[]) { Room room! = new Room(); Room room? = new Room(). Room room3 = new Room(), Room roomd = new Room(); Room rooms = new Room(). Room] totalRooms = { room1, room2, room’, room4, rooms }; ‘Admin admin = new Admin(); ‘Member member = new Member(101, “Serena’); ‘Member member? = new Member(102, "Martha’); Member member3 = new Member(103, Nia’); ‘Member member4 = new Member(104, "Maria"); ‘Member member5 = new Member(105, Eva’); ‘Memberl] members = { member1, member2, member3, member4, member5 }; for (Member member : members) { ‘admin assignRoom totalRooms, member); if(member.getRoom()!=null) { ‘System.out.printin(’Hi “tmember.getName(}#"! Your room number is “+member. getRoom().getRoomNo()); else { b ‘System.out.printin("Hi “+member.getName()+"! No room available"); DAY2 *CONSTRUCTOR CALL IN INHERITANCE- TRYOUT* class Employee { Employeed) { ‘System.out.printin("Employee constructor invoked"); } ) class Manager extends Employee { Manager() { System.out printin(’Manager constructor invoked"); } ) class Tester ( public static void main(String[] args) { ‘Manager manager = new Manager(); *NEED FOR SUPER CONSTRUCTORS= TRYOUT* class Customer { Edit with WPS Officeprivate String customerid; private String customerName; Public Customer(String customerid, String customerName) { this.customerld = customerid; ‘this.customerName = customerName; ¥ public Customer() { ‘System. out.printin(*Parent parameterless constructor’); } public String getCustomerld() { return customerld; } public void setCustomerld(String customerld) { this.customerld = customerid; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { ‘this.customerName = customerName; } Public void displayCustomerDetails() { ‘System.out printin(‘Displaying customer details \n*#+##settenenannsaneesnei): ‘System.out printin(*Customer Id: "+ this.customerld); ‘System.out.printin(*Customer Name : * + this.customerName); System.out printin(); , ) class RegularCustomer extends Customer { private float discount, public RegularCustomer(String custld, String custName) { this.setCustomerld(custld); this. setCustomerName(custName); this discount = 5.0f; ‘System.out.printin(‘Child parameterized constructor’); } public float getDiscount() { return discount; } public void setDiscount(float discount) { this discount = discount; + Edit with WPS Officeclass Tester ( public static void main(String[] args) { RegulerCustomer regularCustomer = new RegularCustomer(’C1010", “Johns Kore") regularCustomer.displayCustomerDetails(); *INHERITANCE TRYOUT* class Employee { int employeeld; String employeeName; // Parameterized constructor Employee(int employeeld, String employeeName) { this.employeeld = employeeld:; this employeeName = employeeName; } public int getEmployeeld() { return employeeld, } Public void setEmployeetd{int employeeld) { this.employeeid = employeetd; } public String getEmployeeName() { return employeeName; } Public void setEmployeeName(String employeeName) { this.employeeName = employeeName; public void display() { ‘System.out.printin("Employee details"); ‘System out printin(*Employee Id: "+ employeetd); ‘System.out.printin("Employee Name: * + employeeName); d class Manager extends Employee { private String designation; Manager(int employeeid, String employeeName, String designation) { super(employeeld, employeeName); this designation = designation, } public String getDesignation() ( return designation; } public void setDesignation(String designation) { ‘this designation = designation; Edit with WPS Office) class Tester ( public static void main(Stringl} args) { Manager obj = new Manager(101, “Joh obj dispiay(); ‘System. out.printin("Designation: * + obj.getDesignation()); ead’); ¥ d *INHERITANCE-EXERCISE 1* class Camera { private String brand; private double cost; public Camera) { this.brand = "Nikon"; } public Camera(String brand, double cost}{ this brand-brand; this.cost= cost; ¥ public String getBrand0 { return brand; } Public void setBrand(String brand) { this brand = brand; ) Public double getCost() { return cost, Public void setCost(double cost) { this.cost = cost; } , class DigitalCamera extends Camera { private int memory, Public DigitalCamera(String brand, double cost) { super(brand, cost); ‘this memory = 16; + Public int getMemory() { retum memory; } Public void setMemory(int memory) { this memory = memory, } J class Tester { public static void main(Stringl] args) { DigitalCamera camera = new DigitalCamera(*Canon’,100); ‘System.out printin(camera getBrand()}+" “+camera.getMemory()); } v7} Edit with WPS Office “scamera.getCost()+") “METHOD OVERLOADING: TRYOUT* class Shape { // Method to find the area of circle public float calculateArea(float radius) { return 3.14F* radius * radius; } // Method to find the area of rectangle Public float calculateArea(float length, float breadth) { return length * breadth; } // Code another overloaded method to find the area of triangle ) class Tester ( Public static void main(Stringl] args) { Shape shape = new Shape(); float circleArea = shape.calculateArea(1.79) float rectangleArea = shape.calculateArea(2.5f, 3.4f); ‘System out printin("Area of circle: " + circleArea); ‘System.out.printin("Area of rectangle: * + rectangleArea); // \nvoke the method to find the area of triangle 1/ Display the ares of triangle *METHOD OVERLOADING-EXERCISE 1* class Point { //implement your code here private double xCoordinate; private double yCoordinate; public Point(double xCoordinate, double yCoordinate){ public double calculateDistance(){ double x2= this.xCoordinate, x1=0.0, y2= this yCoordinate, y1=0.0; double d= ((x2-x1)*(x2-x1}+ (y2-yI)*(y2-y1)); double distance= Math.sqrt(d); return Math.round(distance*100.0)/100.0; Public double calculateDistance(Point point){ double x2= thisxCoordinate, x1=pointxGoordinate, 2= this yCoordinate, yl=point yCoordinate; double d= ((x2-x1)*(x2-x1)+ (y2y1)"y2-Y1)); double distance= Math.sqrt(d); return Math.round(distance*100.0)/100.0; } public double getxCoordinate() { v7} Edit with WPS Officereturn xCoordinate; Public void setxCoordinate(double xCoordinate) { this xCoordinate = xCoordinate; } public double getyCoordinate() { return yCoordinate; } Public void setyCoordinate(double yCoordinate) { ‘this yCoordinate = yCoordinate; , class Tester { Public static void main(Stringl] args) { Point point = new Point(3.5, 1.5); Point point2 = new Point(6, 4); ‘System out printin(‘Distance of point1 from origin is “tpoint1 calculateDistance()); ‘System.out.printin(*Distance of point2 from origin is “+point2.calculateDistance(); System.out printin(‘Distance of _~—pointi. © from ~—point2. is “+point1 calculateDistance(point2)); 1/Create more objects for testing your code } ) “sINHERITANCE-ASSIGNEMENT 1#(INCORRECT) class Employee { //implement your code here //Uncomment the below method after implementation before verifying 7/00 NOT MODIFY THE METHOD. private int employeeld, private String employeeName; private double salary, public Employee(int employeetd, String employeeName){ this.employeeld= employeeld; this.employeeName= employeeName; } public int getEmployeeld() { Feturn employeeld; , public void setEmployeeld(int employeeld) { ‘this.employeeld = employeeld; ) public String getEmployeeName() { return employeeName; ) public void setEmployeeName(String employeeName) { Edit with WPS Officethis.employeeName = employeeName; d public double getSalary() { return salary; , public void setSalary(double salary) { ‘this salary = salary, ) public String toString(){ retum “Employee\nemployeeld: __“+this. getEmployeeld()+"\nemployeeName: “+this. getEmployeeName()+"\nsalary: "+this.getSalary(); } d class PermanentEmployee extends Employee { //implement your code here //Uncomment the below method after implementation before verifying 7/00 NOT MODIFY THE METHOD. private double basicPay, private double hra; private float experience; Public PermanentEmployee(int empld, String namedouble basicPay, double hra, float experience){ super(empld, name); this.basicPay= basioPay; this hra= hra; this.experien experience; , public void calculateMonthlySalary() { float experienceComponentPercentage = Of, if (this experience >= 3 88 this experience < 5) { experienceComponentPercentage = 5; } elseif (this.experience >= 5 &8 this experience < 10) { experienceComponentPercentage = 7; } else if (this experience >= 10) { experienceComponentPercentage = 12; } double salary = (float) ((this.basicPay * (experienceComponentPercentage/100)) + this.basicPay + this.hra); this.setSalary(salary); , public double getBasicPay() { return basicPay, ) public void setBasicPay(double basicPay) { this basicPay = basicPay, ) public double getHra() { Edit with WPS Officereturn hra; ) public void setHra(double hra) ( ‘this.hra = hra; ) Public float getExperience() { return experience; ) public void setExperience(float experience) { this. experience = experience; ) public String toString(){ return *PermanentEmployee\nemployeeld: “+this. getEmployeeld)+"\nemployeeName: “+this. getEmployeeName()+\nsalary: “+this.getSalary()¥"\nbasicPay: "+this getBasicPay()+"\nhra: "+this.getHra()#"\nexperience: “+this.getExperience(); ) class ContractEmployee extends Employee ( J/ignplement your code here //Uncomment the below method after implementation before verifying //00 NOT MODIFY THE METHOD private double wage; private float hours Worked: public ContractEmployee(int empid, String name, double wage, float hoursWorked){ ssuper(empld, name), this wage= wage; this hoursWorked= hoursWorked; } public void calculateSalary(){ setSalary(hoursWorked*wage); } Public double getWage() { return wage; } Public void setWage(double wage) { this.wage = wage; + public float getHoursWorked() { return hoursWorked; } Public void setHoursWorked(float hoursWorked) { this hoursWorked = hoursWorked; } public String toString(){ return “ContractEmployee\nemployeeld: “+this.getEmployeeld()+"\nemployeeName: “+this.getEmployeeName()+"\nsalary: “+this getSalary()+"\nwage: “+this.getWage()#"\nhoursWorked: “#this.getHoursWorked); } d Edit with WPS Officeclass Tester ( public static void main(String[] args) { PermanentEmployee permanentEmployee = new PetmanentEmployee(711211, "Rafael", 1850, 115, 3.51); permanentEmployee.calculateMonthlySalary(); ‘System.out.printin("Hi"+permanentEmployee.getEmployeeName()+", your salary is -+Math,round(permanentEmployee.getSalary()*100)/100.0); Contractémployee contractEmployee = new ContractEmployee(102, “Jennifer’, 16, 90); contractEmployee.calculateSalary(); System out printin(Hi “+contractEmployee.getémployeeName()+", your salary is $+Math.round(contractEmployee.getSalary()*100)/100. //Create more objects for testing your code } *METHOD OVERLOADING ASSIGNMENT 1* class Bill{ //implement your code here public double findPrice(int itemid){ double price=0; switch (itemnid){ case 1001: price=25; break; case 1002: price=20; break; case 1003: price=23; break; ‘case 1004: price=18; break; default: price=0; } retum price; } Public double findPrice(String brandName, String itemType, int size) double pric if(brandName.equals(Puma’)){ if(itemType.equais("T-shirt?)){ if(size: pric } } tee fitemType equate Skirt) “40){ } else if(brandName.equals("Reebok’)){ if(itemType.equals("T-s set if{size==34 || size: price=23; } Edit with WPS Office» else iffitemType equals(‘Skirt"){ retum price; } d class Tester ( public static void main(String[] args) { Bill bil = new Bill; double price = bill indPrice(1001); if(price>0) ‘System out printin('Price of the selected item is $"¢price); else ‘System.out printin(’The Item Id is invalid’); price = bill indPrice(‘Reebok","T-shirt’34), if(price>0) ‘System out printin('Price of the selected item is $"¢price); else ‘System.out printin(’The values are not vali’); J *METHOD-OVERLOADING ASSIGNMENT 2* class Point( //Reuse the code of Method Overloading - Exercise 1 //Uncomment the below method after implementation before verifying //00 NOT MODIFY THE METHOD. private double xCoordinate; private double yCoordinate; public Point(double xCoordinate, double yCoordinate){ this xCoordinate= xCoordinate; this yCoordinate= yCoordinate; public double calculateDistance(){ double x2= this.xCoordinate, x1=0.0, y2= this yCoordinate, y1=0.0; double d= ((x2-x1)*(x2-x1}+ (y2-yI)*(y2-y1)); double distance= Math.sqrt(d); return Math.round(distance*100.0)/100.0; Public double calculateDistance(Point point){ double x2= thisxCoordinate, x1=pointxGoordinate, 2= this yCoordinate, yl=point yCoordinate; double d= ((x2-x1)*(x2-x1)+ (y2y1)"y2-Y1)); double distance= Math.sqrt(d); return Math.round(distance*100.0)/100.0; } public double getxCoordinate() { v7} Edit with WPS Officereturn xCoordinate; Public void setxCoordinate(double xCoordinate) { this xCoordinate = xCoordinate; } public double getyCoordinate() { return yCoordinate; } Public void setyCoordinate(double yCoordinate) { ‘this yCoordinate = yCoordinate; , public String toString(){ return *Point\nxCoordinate: “4this.getxCoordinate()+"\nyCoordinate: “this. getyCoordinate(); , , class Triangle { /fimplement your code here private Point point; private Point point2; private Point point3; public Triangle(){ point = new Point(0,0); point2= new Point(1,1); point3= new Point(2,5); ) public Triangle(double ——_point1XCoordinate,double point YCoordinate,double point2xCoordinate.double point2YCoordinate.double oint3XCoordinatedouble point3¥Coordinate){ point = new Point(point1XCoordinate,point1 Coordinate); point2= new Point(point2XCoordinate,point2¥ Coordinate); point3= new Point(point3XCoordinate,point3¥Coordinate): Public Triangle(Point point1, Point point2, Point point3){ ‘this point1= point1; ‘this point2= point2; ‘this point3= point3; ) Public double calculatePerimeter(){ double perimeter.ab.c, ointt.calculateDistance(point2); int2.calculateDistance(point3); 0int3.calculateDistance(point1); perimeter= atbtc; return Math.round(perimeter*100)/100.0; d public double calculateArea(){ double areas.a.b.c; int calculateDistance(point2); int2.calculateDistance(point3); 0int3.calculateDistance(point1); s4bt0)/2; area Math. sqrt(s'(s-a)*(s-b)“(s-c)); return Math.round(area*100)/100.0; ) Public Point getPoint1() { v7} Edit with WPS Officereturn point; ) public void setPoint1 (Point point1) { ‘this pointt = point; ) Public Point getPoint2() { return point2; , public void setPoint2(Point point2) { this point2 = point2; d Public Point getPoint3() { return point3; ) public void setPoint3(Point point3) { this, point3 = point3; ) , class Tester ( public static void main(Stringl] args) { Triangle triangle = new Triangle(); Triangle triangle2 = new Triangle(1, 2, 6,5, 5, 1); Point pointt = new Point(2, 1); Point point2 = new Point(4, 4) Point point3 = new Point(9, 1); Triangle triangle3 = new Triangle(point1, point2, point3); ‘System.out printin("Perimeter of triangle! is “+triangle1.calculatePerimeter(); ‘System out printin("Area of triangle’ is “+triangle1.calculatesrea()); ‘System out printin("Perimeter of triangle? is "“+triangle2 calculatePerimeter(); ‘System out printin(*Aree of triangle? is “#triangle2.calculaterea(); ‘System out printin("Perimeter of triangle3 is “+triangle3 calculatePerimeter(); ‘System.out.printin(*Area of triangled is #triangle3.calculaterea(); //Create more objects of Triangle class for testing your code DAY3 *METHOD OVERRIDING- TRYOUT* 1. class Tester { Public static void main(String[] args) { ‘Customer customer = new Customer(); ‘System. out printin(‘Final bill amount: “+customer. payBill(40.0)); Edit with WPS Office1/ Parent Reference > Parent Object, RegularCustomer regularCustomer = new RegularCustomer(); ‘System. out printin(Final bill amount: “tregularCustomer payBill(40.0)); // Child Reference -> Child Object Customer regCust = new RegularCustomer(); // Parent Reference -> Child Object System out printin*Final Bil :*+ regCust.payBill40.0)); } ) class Customer { public double payBill(double totalPrice) { ‘System.out.printin(‘Final bill for the customer is calculated here"); return totalPrice; , ) class RegularCustomer extends Customer { @Overtide public double payBill(double totalPrice) { ‘System.out.printin(‘Final ill for the regular customer is calculated here"); double priceAfterDiscount = totalPrice * (1 - (5f / 100); return priceAfterDiscount; ) 2 class Tester { Public static void main(String args[}) { Bank bank; bank = new ABCBank(; ‘System.out printin(*ABCBank - Rate of Interest(%):* + bank getRateOfinterest(); bank = new DEFBank(); ‘System.out.printin("DEFBank - Rate of interest(%):" + bank getRateOfinterest(); bank = new GHIBankQ; ‘System.out printin(’GHiBank - Rate of interest(%):* + bank getRateOfinterest(); } ) class Bank { Public float getRateOfinterest() { return 0; ‘// remove the access specifier and observe the output ) class ABCBank extends Bank { Public float getRateOfinterest() { return €.99f; } // Keeping the parent access specifier as public, remove the child access // specifier and observe the output Edit with WPS Office) class DEFBank extends Bank { Public float getRateOfinterest() { return 9.4f; } // Keeping the parent access specifier as public, change the child access // specifier to private/protected and observe the output d class GHiBank extends Bank { Public float getRateOfinterest() { return 8.1f; , , *GENERIC METHOD TRYOUT* class DynamicBindingTester { Public static void main(Stringl] args) { Employee employee = new Employee(); Manager manager = new Manager(); Employee eduEmployee = new Educator(); Educator managerEdu = new Manager() displayEmployeeDetails(employee); displayEmployeeDetails(manager); displayEmployeeDetails(eduEmployee); displayEmployeeDetails(managerEdu); } // Employee reference can accept its object and any of the child object public static void displayEmployeeDetails(Employee employee) { employee.displayDetails(); // displayDetails invoked will be based on the object received ? , class Employee { String name = "James Anthony’; public void displayDetalls(){ ‘System.out.printin(name+” is an employee"), } Class Educator extends Employee { public void displayDetails(){ ‘System. out printin(name+* is an educator’); } ) class Manager extends Educator { public void displayDetails(){ ‘System out printin(name#* is a manager’); } , *METHOD OVERRIDING EXERCISE* class User{ //impiement your code here private int id; Edit with WPS Officeprivate String userName; private String emaild; private double walletBalance; public User(int id String userName, String emailld,double walletBalance){ ‘this.emailld= emailid; this.walletBalanc } Public boolean makePayment(double billAmount){ if(this.getWalletBalance()>=billAmount){ double x= (double)(this.getWalletBalance()-billAmount); this. setWalletBalance(x); return true; } else( retum false; } } public int getld() { return id; } Public void setid(int id) { thisid } public String getUserName() { return userName; Public void setUserName(String userName) { this.userName = userName; } public String getEmailld() { return emailid; } Public void setEmailld(String emailld) { this.emailid = emailid; } public double getWalletBalance() { return walletBalance; } Public void setWalletBalance(double walletBalance) { ‘this.walletBalance = walletBalance; , class PremiumUser extends User{ // implement your code here private int rewardPoints; Public int getRewardPoints() { return rewardPoints; Public void setRewardPoints(int rewardPoints) { this rewardPoints = rewardPoints; Public PremiumUser(int id String userName, String emailld,double walletBalance){ super(id, userName, emailld, walletBalance); @overtide public boolean makePayment(double billAmount){ Edit with WPS Officeif(this.getWalletBalance()>-billAmount){ t y= (int) this.rewardPoints+ (billAmount*10)/100)); this setRewardPoints(y); double z= (double) this.getWalletBalance()-billAmount); this setWalletBalance(z); retum true; elset return false; } , ) class Tester ( Public static void main(Stringl] args) { User user = new User(101, "Joe",
[email protected]
’, 100); PremiumUser premiumUser = new PremiumUser(201, ‘il’ ‘
[email protected]
", 300); processPayment(user, 70); processPayment(premiumUser, 150); processPayment(premiumUser, 80); processPayment(premiumUser, 120); ) Public static void processPayment(User user, double billAmount) { if (user makePayment(billAmount)) { ‘System.out printin(’Congratulations * + user.getUserName() +", payment of $"+ billAmount + * was successful") Jelse { ‘System.out printin('Sorry * + user.getUserName() +", you do not have enough balance to pay the bill } ‘System.out printin(*Your wallet balance is $* + user.getWalletBalance()); if (user instanceof PremiumUser) { PremiumUser premiumUser = (PremiumUser) user; ‘System.out printin("You have * + premiumUser.getRewardPoints() +" points!’); 7 ‘System.out.printin(); *EQUAL OBJECTS TRYOUT* class Food { private String foodName; private String cuisine; private String foodType; Edit with WPS Officeprivate int quantityAvailable; private double unitPrice; public String getFoodName() { return foodName; } Public void setFoodName(String foodName) { this foodName = foodName; } Public String getCuisine() { return cuisine; , Public void setCuisine(String cuisine) { this.culsine = cuisine; , public String getFoodType(){ return foodType; } public void setFoodType(String foodType) { ‘this foodType = foodType; } Public int getQuantityAvailable() { retum quanttyAvailable; , public void setQuantityAvailable(int quantityAvailable) { this.quantityAvailable = quantityAvailable; } public double getUnitPrice() { return unitPrice; } Public void setUnitPrice(double unitPrice) { this.unitPrice = unitPrice; } , class Tester { public static void main(String[] args) { Food foodOne = new Food(); foodOne setFoodName("Sandwich foodOne.setCuisine(‘Continental’); foodOne.setFoodType("Veg"), foodOne setQuantityAvailabie(100), foodOne.setUnitPrice(10); Food foodTwo = new Food(); foodTwo.setFoodName("Sandwich’); foodTwo.setCuisine(“Continental’); foodTwo.setFoodTypet"Veo"); foodTwo.setQuantityAvailable(200); foodTwo setUnitPrice(10); Edit with WPS Officeif (foodOne == foodTwo) { ‘System out printin("The food objects are same"); Jelse { ‘System.out printin(’The food objects are different”); } k , *EQUALS TRYOUT* class Food { private String foodName; private String cuisine; private String foodType; private int quantityAvailable; private double unitPrice; public String getFoodName() { return foodName; } Public void setFoodName(String foodName) { this foodName = foodName; } Public String getCuisine() { return cuisine; } public void setCuisine(String cuisine) { this cuisine = cuisine; } public String getFoodType() { return foodType; ) public void setFoodType(String foodType) { this.foodType = foodType; } public int getQuantityAvailable() { return quantityAvailable; } public void setQuantityAvailable(int quantityAvailable) { this.quantityAvailable = quantityAvailable; } public double getUnitPrice() { return unitPrice; , public void setUnitPrice(double unitPrice) { this.unitPrice = unitPrice; } // equals method of Object class overridden for comparing two Food objects // based on foodName and foodType Edit with WPS Officed @override Public boolean equals(Object obj) { Food otherFood = (Food) obj; if (this foodName.equals(otherFood.foodName)) { if (his. foodType.equals(otherFood.foodType)) return true; retum false; class Tester { J Public static void main(String[] args) { Food foodOne = new Food(); foodOne.setFoodName("Sandwich’); foodOne setCuisine("Continental"); foodOne.setFoodType("Veg"); foodOne.setQuantityAvailabie(100), foodOne.setUnitPrice(10); Food foodTwo = new Food(); foodTwo.setFoodName("Sandwich’); foodTwo.setCuisine(“Continental’); foodTwo.setFoodTypet"Veo"); foodTwo.setQuantityAvailabie(200), foodTwo.setUnitPrice(10); if (foodOne.equals(foodTwo)) { System.out printin(*foodOne and foodTwo are same"); Jelse { ‘System out printin(foodOne and foodTwo are different! } Food foodThree = new Food) foodThree.setFoodName("Burger’); foodThree.setCuisine(*Continentat’); foodThree setFoodType("Veg"); foodThree.setQuantityAveilabie(100); foodThree.setUnitPrice(10); if (foodOne.equals(foodThree)) { ‘System.out printin('foodOne and foodThree are same!"); yelse{ ‘System.out printin('foodOne and foodThree are different”); ; + ‘*HASHCODE TRYOUT* class Food { private String foodName; private String cuisine; private String foodType; private int quantityAvailable; private double unitPrice; Public String getFoodName() { return foodName; Edit with WPS Office, public void setFoodName(String foodName) { this foodName = foodName; } public String getCuisine() { return cuisine; } Public void setCuisine(String cuisine) { ‘this.cuisine = cuisine; , public String getFoodType() { return foodType; } public void setFoodType(String foodType) { this.foodType = foodType; } public int getQuantityAvailable() { return quantityAvailable; } Public void setQuantityAvailable(int quantityAvailable) { this.quantityAvailable = quantityAvailable; } Public double getUnitPrice() { return unitPrice; } Public void setUnitPrice(double unitPrice) { this.unitPrice = unitPrice; + // equals method of Object class overridden for comparing two Food objects // based on foodName and foodType @Override Public boolean equals(Object obj) { Food otherFood = (Food) obj; if (this.foodName.equals(otherFood.foodName)) { if (this. foodType.equals(otherFood.foodType)) return true; } return false; } // hashCode method overridden @Overtide Public int hashCode() { int result =1; result = result + (foodName hashCode); return result, } , class Tester ( Edit with WPS OfficePublic static void main(Stringl] args) { Food foodOne = new Food(); foodOne.setFoodName("Sandwich’); foodOne.setCuisine(‘Continental’); foodOne setFoodType("Veg"); foodOne.setQuantityAvailable(100); foodOne.setUnitPrice(10); Food foodTwo = new Food(); foodTwo.setFoodName("Sandwich’); foodTwo.setCuisine(“Continental’); foodTwo.setFoodType("Veo"); foodTwo.setQuantityAvailable(200); foodTwo.setUnitPrice(10); if (foodOne.equals(foodTwo)) { ‘System.out printin('foodOne and foodTwo are same!” Jelse { ‘System out printin('foodOne and foodTwo are different!" } ‘System.out.printin("Hash code for foodOne : "+ foodOne.hashCode()}; ‘System.out printin("Hash code for foodTwo :* + foodTwo hashCode()) Food foodThree = new Food(); foodThree.setFoodName("Burger’); foodThree.setCuisine(*Continentat’); foodThree.setFoodType("Ver foodThree.setQuantityavailabie(100); foodThree.setUnitPrice(10): if (foodOne.equals(foodThree)) { ‘System. out printin("foodOne and foodThree are same! }else{ ‘System out printin("foodOne and foodThree are different!’ } ‘System.out printin("Hash code for foodOne :* + foodOne-hashCode()); ‘System.out.printin("Hash code for foodThree : + foodThree.hashCode()); } , *to-STRING TRYOUT* class Food { private String foodName; Private String cuisine; private String foodType; private int quantityAvailable; private double unitPrice; public String getFoodName() { retum foodName; } public void setFoodName(String foodName) { ‘this foodName = foodName; } Edit with WPS Officepublic String getCuisine() { return cuisine; } public void setCuisine(String cuisine) { this cuisine = cuisine; } public String getFoodType() { retum foodType; } Public void setFoodType(String foodType) { this foodType = foodType; } public int getQuantityAvailable() { return quantityAvailable; public void setQuantityAvailable(int quantityAvailable) { this.quantityAvailable = quantityAvailable; } public double getUnitPriceQ { return unitPrice; } Public void setUnitPrice(double unitPrice) { this unitPrice = unitPrice; } // equals method of Object class overridden for comparing two Food objects ///based on foodName and foodType @Override Public boolean equals(Object obj) { Food otherFood = (Food) obj; if (this foodName.equals(otherFood.foodName)) { if (this. foodType.equals(otherFood.foodType)) return true; retum false; } // hashCode method overridden @Override public int hashCode() { int result = 1; result = result + (foodName.hashCode(); return result; } //0String is overridden to provide a custom textual representation @Override Public String toString() return "Food >" + "Food name: "+ this. foodName + *, Cuisin + this cuisine +", Food type: "+ this foodType +", Quantity avaialable: "+ this.quantityAvailable +" unitPrice:" + unitPrice; Edit with WPS Officed class Tester ( public static void main(String[] args) { Food foodOne = new Food(); foodOne.setFoodName("Sandwich’); foodOne.setCuisine(‘Continental’); foodOne.setFoodType("Veg"); foodOne. setQuantityAvailabie(100), foodOne.setUnitPrice(10); 1/ Comment the toString in the Food class and execute the code System out printin(foodOne), *WRAPPER CLASSES TRVOUT* class Tester { public static void main(Stringl] args) { // Comparison of integer objects Integer x= 5; Integer y = new integer(5); ‘System.out printin('x ‘System.out.printin(*x.equals(y) int data converted to Integer object “+ (x==y)); )." + xequals(y)); 1/ Wrap the primitive content into wrapper class objects Integer number = Integer.valueOf(x); ‘System out printin(‘Wrapping x to its Integer: * + number); ‘System. out printin(*Check if number is of type Integer: * + (number instanceof integer)); // Wrappers can be used to convert numeric strings to numeric datatypes String numStr = "123"; int numint = Integer. parseint(numStr); ‘System.out printin(*String to integer: * + numnint); double numDouble = Double parseDouble(
=85 && this.aggregateMarks<90) { bonus=10; } else if(this.aggregateMarks>=90 && this aggregateMarks<95){ bonus=15; } else (this aggregateMarks>=95 &8 this.aggregateMarks<=100} bonus=20; } int good: (int)(bonus+ this. STIPEND); retum good; v7} Edit with WPS Officeclass Tester ( public static void main(Stringl] args) { ‘Student student! = new Student; student? setStudentid(1212); student! setAggregateMarks(93); double totalStipend = student1 .calculateTotalStipend(); System out printin("The final stipend of * + studenti.getStudentid()+" is $* + totalStipend); ‘Student student2 = new Student; student2.setStudentld(1222); student? setAggregateMarks(84); totalStipend = student2.calculateTotalStipend(); System.out.printin("The final stipend of " + student2.getStudentld(}* is $* + totalStipend); } *DAY 4" *ABSTRACT CLASS AND METHODS-TRYOUT* abstract class GrandParent { abstract void display(); ) abstract class Parent extends GrandParent { // Can we remove the abstract keyword from here? final void displayinParent() { ‘System.out.printin("in Parent’ } , class Child extends Parent { void display() { ‘System.out printin("Child completes Parent and GrandParent super.displayinParent(); d final class GrandChild extends Child { void display() { ‘System.out.printin(‘in GrandChild"); super display , /fUncomment the code given below and observe /(class GreatGrandChild extends GrandChild {} class Tester ( Public static void main(String[] args) { new GrandChild() display(); } Edit with WPS Office*INSTANCE OF- TRYOUT* abstract class Employee( private String employeetd; private String name; private static int counter; statio{ counter=101; } Public Employee(String name){ 1/Checking the type of the current instance if(this instanceof PermanentEmployee) employeeld="P"+counter++; else if(this instanceof ContractEmployee) employeeld="C"+counter++; setName(name); } public abstract void calculateSalary(); Public String getEmployeeld({ return employeeld; } Public String getName(){ retun name; } public void setName(String name){ this name=name; F ) class PermanentEmployee extends Employee public PermanentEmployee(String name){ super(name); @Override public void calculateSalary(){ ‘System out printin("Calculating salary of PermanentEmployee"); + public void calculateBonus() ‘System.out.printin(*Calculating bonus of PermanentEmployee") } class ContractEmployee extends Employeet public ContractEmployee(String name){ super(name); @Override public void calculateSalary(){ Edit with WPS Office‘System.out.printin(*Calculating salary of Contractemployee"); , class SalarySlipGenerator{ public void displaySalarySlip(Employee employee){ employee.calculateSalary(); //{Checking if employee is an instance of PermanentEmployee if(employee instanceof PermanentEmployee){ //Type casting parent class reference to child class for accessing child class method PermanentEmployee permanentEmployes permanentEmployee.calculateBonus(); (PermanentEmployee)employee; class Tester{ Public static void main(Stringl] args) { PermanentEmployee permanentEmployee=new PermanentEmployee(’Angie"); ‘System.out printin(‘Details of permanent employee"); ‘System.out printin("Employee id: "tpermanentEmployee.getEmployeeld()); ‘System.out.printin(’Name: “+permanentEmployee.getName()); ‘System out printin(); ContractEmployee contractEmployee=new Contractémployee("Roger’); System. out printin(‘Details of contract employee"); System. out.printin("Employee Id: “+contractEmployee. getEmployeeld()); System out printin(*Name: “#contractmployee.getName()); ‘System.out printin(); SalarySlipGenerator salarySlipGenerator=new SalarySlipGenerator(); System.out printin('Salary of permanent employee"); salarySlipGenerator displaySelarySlip(permanentEmployee); System.out printin(; ‘System.out.printin(‘Salary of contract employee’); salarySlipGenerator displaySelarySlip(contractEmployee); , *ABSTRACT EXERCISE 1* abstract class Student { //implement your code here private String studentName; private int []testScores; private String testResult; public Student(String studentName) { this. studentName = studentName; testScores=new int(4]; abstract public void generateResult(); public String getStudentName() { Edit with WPS Officereturn studentName; public void setStudentName(String studentName) { this. studentName = studentName; } public intl] getTestScores() { return testScores; Public void setTestScore(int testNumberint testScore) { this.testScores|testNumber] = testScore; } Public String getTestResult() { return testResult; public void setTestResult(String testResult) ( this.testResult = testResult; } class UndergraduateStudent extends Student { Public UndergraduateStudent(String studentName) { super(studentName), } public void generateResult() { int [ltestScores=super.getTestScores(), int total = 0; for(int i=0;ictestScores lengthii++) ( total+=testScores[il; double average=total/testScores length; if(average>=60) { super setTestResult(‘Pass") Jelse if(average<60) { super setTestResult('Fail’ } } class GraduateStudent extends Student { Public GraduateStudent( String studentName) { ‘super(studentName); } Public void generateResult() ( int [lestScores=super.getTestScores(); jictestScores.lengthii++) { testScores|il; double average=total/testScores length; iffaverage>=70) { super.setTestResult(‘Pas: Jelse if(average<70) { super.setTestResult(‘Fail’); v7} Edit with WPS Officeclass Tester { public static void main(String[] args) { UndergraduateStudent undergraduateStudent = new UndergraduateStudent( Philip’ undergraduateStudent.setTestScore(0, 70); undergraduateStudent setTestScore(1, 69); undergracuateStudent setTestScore(2, 71); undergraduateStudent setTestScore(3, 55); undergraduateStudent.generateResult(); ‘System.out printin( "Student name: “+undergraduateStudent.getStudentName()); ‘System out printin(*Result: "tundergraduateStudent.getTestResult(); ‘System.out printin(); GraduateStudent graduateStudent = new GraduateStudent(‘Jerry"); graduateStudent setTestScore(0, 70); GraduateStudent setTestScore(1, 69); GraduateStudent setTestScore(2, 71); GraduateStudent setTestScore(3, 55); graduateStudent.generateResult(); ‘System out printin(*Student name: "+ graduateStudent.getStudentName()); System out printin(*Result: “+ graduateStudent.getTestResult); //Create more objects of the classes for testing your code , ) *INTERFACE TRYOUT* interface DemoOne { int number = 5; , interface DemoTwo extends DemoOne{ void display); , class DemoClassOne implements DemoTwo{ public void display() { ‘System.out printin(number); , , class Tester ( Public static void main(Stringl] args) { DemoTwo obj = new DemoClassOne(); obj-display(); *INTERFACE EXERCISE 1* v7} Edit with WPS Officeinterface Taxt double calculateTax(double price); ) class PurchaseDetails implements Tax( private String purchaseld; private String paymentType; private double taxPercentage; Public String getPurchaseld( { return purchaseld; } Public void setPurchaseld (String purchaseld) { this purchaseld = purchaseld; } public String getPaymentType() ( return paymentType, } Public void setPaymentType(String paymentType) { this paymentType = payment ype; public double getTaxPercentage() ( return taxPercentage; Public void setTaxPercentage(double taxPercentage) { ‘this taxPercentage = taxPercentage; } public PurchaseDetails(String purchaseld,String paymentType) { this purchaseld=purchaseld; this paymentType=paymentType; public double calculateTax(double price) { double total if(this paymentType.equals(‘Debit Card’) { total=price+(price*0.02); this setTaxPercentage(2); } else if(this.paymentType.equals(‘Crecit Card") { total=price+(price*0.03); this. setTaxPercentage(3); } else{ total=pricet(price*0.04), this. setTaxPercentage(4); } return total; J class Seller implements Tax{ private String location; private double taxPercentage; Public String getLocation() { return location; Public void setLocation(String location) { this location = location; } public double getTaxPercentage() { return taxPercentage; Edit with WPS OfficePublic void setTaxPercentage(double taxPercentage) this.taxPercentage = taxPercentage; } public Seller(String location) { ‘this location=location; } public double calculateTax(double price) { double tax=0; if(this.location.equals("Middle east’)) { tax=price*0.15; this setTaxPercentage(15); else if(this.location.equals("Europe’)) { tax=price*0.25, this. setTaxPercentage(25); else if(this location. equals("Canada") { tax=price*0.22; this setTaxPercentage(22); else if(this location. equals("Japan")) { tax=price"0.12; this setTaxPercentage(12); } return tax; } ) class InterfaceExercise { public static void main(String[] args) { // TODO Auto-generated method stub ‘System.out.printin("Purchase Details\n*™*****"); PurchaseDetails purchaseDetails = new PurchaseDetalls('P1001"/Credit Card’); System out printin("Total purchase ‘amount 7 Math round(purchaseDetails.calculateTax(100)*100)/100.0); ‘System out printin("Tax percentage: "+purchaseDetails.getTaxPercentage()); ‘System out printin( "Seller Detalls\n##44+ Seller seller = new Seller("Middle east’); Systemout printin(’Tax tobe paid + by the _seller: Math round(seller.calculateTax(100)*100)/100.0); ‘System.out printin("Tax percentage: “+seller.getTaxPercentage(); *ASSIGNMENTS* 1, METHOD OVERRIDING 1 class Faculty( implement your code here private String name; private float basicSalary, private float bonusPercentage; private float carAllowancePercentage; Edit with WPS Office +Public Faculty(String name,float basicSalary){ this name= name; this basicSalary= basicSalary; this bonusPercentage=4f, this.carAllowancePercentage= 2.5f; } public double calculateSalary(){ double facultySala this. qs TH .getBonusPercentage()/100)+(this. getCarAllowancePercentage() 7100)); this setBasicSalary((float) facultySalary); return facultySalary, } Public String getName() { return name, Public void setName(String name) { this.name = name; } Public float getBasicSalary() { return basicSalary, Public void setBasicSalary(float basicSalary) { this basicSalary = basicSalary; Public float getBonusPercentage() { return bonusPercentage; Public void setonusPercentage(float bonusPercentage) { this.bonusPercentage = bonusPercentage; } Public float getCarAllowancePercentage() { return carAllowancePercentage; } public void setCarAllowancePercentage (float carAllowancePercentage) { this.carAllowancePercentage = carAllowancePercentage;, } , class OfficeStaff extends Faculty( implement your code here private String designation; Public OfficeStaff(String name, float basicSalary, String designation){ super(namebasicSalary); this.designation= designation; } @override public double calculateSalary()( double additionalPay =super.calculateSalary(); double staffSalary= if(this.getDesignation().equals("Accountant")}{ staffSalary= additionalPay+10000.0; } else if(this.getDesignation().equals("Clerk’){ staffSalary= additionalPay+7000.0; } else if(this.getDesignation().equals(’Peon’)){ staffSalary= additionalPay+4500.0; } Edit with WPS Officeelset staffSalary= additionalPay, super. setBasieSalary((float) staffSalary); return staffSalary; ) Public String getDesignation() ( retun designation; } public void setDesignation(String designation) { this.designation = designation; a class Teacher extends Faculty( implement your code here private String qualification; public Teacher(String name, float basicSalary, String qualification) super(namebasicSalary); this.qualification= qualification; } @override Public double calculateSalary(){ double additionalPay =super.calculateSalary(); double teacherSalary=0; if(this.getQualification().equals(*Doctoral)){ teacherSalary= additionalPay+20000 0; } else if(this.getQualification().equals(*Masters")){ teacherSalary= additionalPay+18000.0; ; else if(this.getQualification().equals("Bachelors")){ teacherSalary= additionalPay+1 5500.0; } else if(this.getQualification().equals("Associate’)){ teacherSalary= additionalPay+10000.0; } else( teacherSalary= additionalPay, } this setBasicSalary((float) teacherSalary); return teacherSalary, } Public String getQualification() { return qualification; } ublic void setQualification(String qualification) { this qualification = qualification; } class Tester ( Public static void main(Stringl] args) { Teacher teacher = new Teacher(‘Caroline’, 30500f, "Master OfficeStaff officeStaff = new OfficeStaff(James", 24000f, "Accountant’) ‘System.out printin(*Teacher Details\n##eteeeneatee): Edit with WPS Office‘System.out.printin(’Name: “+teacher.getName()); ‘System.out printin(‘Qualification: “+teacher.getQualification()); System out printin(*Total salary: Fe + Math round(teacher.calculateSalary()*100)/100.0); ‘System.out.printin(); ‘System.out printin("Office Staff Details\n**=*#e+++++e+#"); System out printin('Name: tofficeStaff.getName(); ‘System.out printin("Designation: “+officeStaff.getDesignation()); ‘System.out printin("Total salary: Math, round(officeStaff.calculateSalary()*100)/100.0); 1/Create more objects for testing your code } d 2, METHOD OVERRDING-2 class Event{ //mplement your code here private String eventName; private String participantName; private double registrationF public Event(String eventName, String participantName){ this.eventName= eventName; ‘this participantName= participantName; Public void registerEvent(){ if(this. getEventName().equals("Singing’)){ this setRegistrationFee(@); } else if(this.getEventName().equals("Dancing’)}{ this setRegistrationFee(10); } else if(this.getEventName().equals("DigitalArt’))( this setRegistrationFee(12); } else if(this.getEventName().equals("Acting’)){ this.setRegistrationFee(15); } else( this setRegistrationFee(0); } } Public String getEventName() { return eventName; } Public void setEventName(String eventName) { this.eventName = eventName; } public String getParticipantName() { return participantName; public void setParticipantName(String participantName) { this participantName = participantName; } Public double getRegistrationFee() { return registrationFee; } Edit with WPS Officepublic void setRegistrationFee(double recistrationFee) { this registrationFee = registrationFee; , class SoloEvent extends Event{ //mplement your code here private int participantNo; Public SoloEvent(String eventName, String participantName, int participantNo){ super(eventName, participantName); ‘this participantNo= participantNo; , @Override public void registerEvent(){ super.registerEvent(; Public int getParticipantNo() { return participantNo; ) public void setParticipantNo(int participantNo) { this participantNo = participantNo; ) , class Team€vent extends Event{ //implement your code here private int noOfParticipants; private int teamNo; Public TeamEvent(String eventName, String participantName, int noOfParticipants, int ‘teamNo){ ‘super(eventName, participantName); this.noOfParticipants= noOfParticipants; @override public void registerEvent(){ double fee=0; if(this.getNoOfParticipants()>1){ if(this.getEventName().equals("Singing")){ fee= (double)(this. getNoOfParticipants()*4); this. setRegistrationFee(fee); } else if(this.getEventName() equals(‘Dancing’)){ fee= (double)(this. getNoOfParticipants()*6); this. setRegistrationFee(fee); } else if(this.getEventName().equals("DigitalArt’)){ fee= (double)(this.getNoOfParticipants()*8); this. setRegistrationFee(fee); } else if(this.getEventName().equals(“Acting’)){ fee= (double)(this.getNoOfParticipants()*10); this setRegistrationFee(fee); } else( this. setRegistrationFee(0); } } Edit with WPS Office) public int getNoOfParticipants() { return noOfParticipants; d Public void setNoOfParticipants(int noOfParticipants) { this.noOfParticipants = noOfParticipants, ) Public int getTeamNo() ( return teamNo; , public void setTeamNo(int teamNo) { this.teamNo = teamNo; a , class Tester ( public static void main(Stringl] args) { SoloEvent soloEvent = new SoloEvent("Dancing’, "Jacob", 1); soloEvent registerEvent if (soloEvent.getRegistrationFee() = 0){ ‘System.out printin(’Thank You " + solo€vent getParticipantName() +" for your participation! Your registration fee is $° + soloEvent getRegistrationFee(); ‘System.out printin("Your participant number is * + soloEvent.getParticipantNo(); yelse{ ‘System.out printin("Please enter a valid event" } ‘System.out.printin(); ‘TeamEvent teamEvent = new TeamEvent(‘Acting’, "Serena’, 5,1); teamEvent.registerEvent(); if (teamEvent.getRegistrationFee() = 0) { ‘System.out printin(’Thank You * + teamEvent.getParticipantName() +" for your participation! Your registration fee is $* + teamEvent.getRegistrationFee(); ‘System.out printin(*Your tear number is * + teamEvent. getTeamNo(); Jelse{ ‘System.out printin('Please enter a valid event"); 3, FINAL 1 class Circle{ private final double PI=3.14; private double diameter, private double circumference; private double area; public double getDiameter() { return diameter, Public void setDiameter(double diameter) { ‘this diameter = diameter, } Edit with WPS Office
You might also like
Debugging Questions in JAVA
PDF
No ratings yet
Debugging Questions in JAVA
20 pages
FA1 Hands
PDF
50% (2)
FA1 Hands
7 pages
Sample - Core Java Developer Assessment - 1635359098862
PDF
0% (1)
Sample - Core Java Developer Assessment - 1635359098862
10 pages
Assignment 2 - Flow Conrtrol Statement
PDF
0% (1)
Assignment 2 - Flow Conrtrol Statement
8 pages
Java MCQ
PDF
No ratings yet
Java MCQ
2 pages
LEX Assignments5645654654
PDF
No ratings yet
LEX Assignments5645654654
123 pages
Exp 06
PDF
100% (1)
Exp 06
43 pages
Code To Solve Set of Problems
PDF
No ratings yet
Code To Solve Set of Problems
17 pages
Core Java Code Snippets
PDF
No ratings yet
Core Java Code Snippets
11 pages
Java Program
PDF
100% (1)
Java Program
25 pages
TCS Ninja Interview Questions
PDF
No ratings yet
TCS Ninja Interview Questions
1 page
Final Slips
PDF
No ratings yet
Final Slips
29 pages
Cs Question
PDF
No ratings yet
Cs Question
7 pages
Midterm 2
PDF
No ratings yet
Midterm 2
8 pages
Assessment Milestone
PDF
100% (1)
Assessment Milestone
37 pages
Week-09Assignment MCQ
PDF
100% (1)
Week-09Assignment MCQ
5 pages
Java
PDF
67% (3)
Java
94 pages
Capgemini Pseudo Code MCQS: Telegram
PDF
No ratings yet
Capgemini Pseudo Code MCQS: Telegram
15 pages
Topic Wise Java Questions
PDF
No ratings yet
Topic Wise Java Questions
9 pages
Strings and Queries
PDF
No ratings yet
Strings and Queries
5 pages
Try Catch
PDF
No ratings yet
Try Catch
5 pages
Assignment No 1 (Java Lab)
PDF
100% (3)
Assignment No 1 (Java Lab)
42 pages
Deepakpresentation
PDF
No ratings yet
Deepakpresentation
20 pages
Java Control Statements PPT
PDF
100% (1)
Java Control Statements PPT
51 pages
37 Alphabet Pattern Programs
PDF
No ratings yet
37 Alphabet Pattern Programs
109 pages
All 17 PDF Free
PDF
No ratings yet
All 17 PDF Free
636 pages
Hashedin
PDF
No ratings yet
Hashedin
2 pages
Core Java
PDF
50% (2)
Core Java
42 pages
JAVA Practical Questions
PDF
No ratings yet
JAVA Practical Questions
2 pages
Java Aptitude Inreview Questions N Answers
PDF
100% (1)
Java Aptitude Inreview Questions N Answers
125 pages
Sample Paper Wiley Edge Graduate Recruitment
PDF
No ratings yet
Sample Paper Wiley Edge Graduate Recruitment
12 pages
D. Null Operator
PDF
100% (2)
D. Null Operator
49 pages
Milestones BITS Final
PDF
No ratings yet
Milestones BITS Final
87 pages
BCA II Year Java Practical Solution
PDF
No ratings yet
BCA II Year Java Practical Solution
20 pages
Collection & Maps Question 1
PDF
No ratings yet
Collection & Maps Question 1
12 pages
25 Java Programs
PDF
No ratings yet
25 Java Programs
36 pages
Java Coding
PDF
100% (4)
Java Coding
332 pages
ML2 All MCQ's
PDF
No ratings yet
ML2 All MCQ's
22 pages
Assignment: JAVA: AIM: Write A Menu Driven Java Program Which Will Read A Number and Should
PDF
100% (1)
Assignment: JAVA: AIM: Write A Menu Driven Java Program Which Will Read A Number and Should
5 pages
TCS IPA MCQs For IPA Exam
PDF
No ratings yet
TCS IPA MCQs For IPA Exam
3 pages
100 Java Programs
PDF
No ratings yet
100 Java Programs
38 pages
Final Assesment All-In-One-Domain
PDF
No ratings yet
Final Assesment All-In-One-Domain
38 pages
Cts Auto Fix Set 3
PDF
100% (2)
Cts Auto Fix Set 3
11 pages
Quiz Java Final
PDF
No ratings yet
Quiz Java Final
4 pages
PRP Ques
PDF
No ratings yet
PRP Ques
14 pages
Java Interfaces: Attribute Datatype
PDF
100% (1)
Java Interfaces: Attribute Datatype
33 pages
Pattern Programs in Java
PDF
No ratings yet
Pattern Programs in Java
2 pages
Phonebook Java Program
PDF
0% (3)
Phonebook Java Program
4 pages
Java Pracs
PDF
No ratings yet
Java Pracs
30 pages
Milestone 1 Questions With Answer
PDF
No ratings yet
Milestone 1 Questions With Answer
33 pages
Java - Lab File (Shubham Patel - 500053376) PDF
PDF
No ratings yet
Java - Lab File (Shubham Patel - 500053376) PDF
49 pages
Data Types in Java: Multiple Choice Questions (Tick The Correct Answers)
PDF
100% (1)
Data Types in Java: Multiple Choice Questions (Tick The Correct Answers)
12 pages
Logical Ability: Directions For Questions 1 and 2: Answer The Questions Based On The
PDF
No ratings yet
Logical Ability: Directions For Questions 1 and 2: Answer The Questions Based On The
27 pages
Java Practical
PDF
No ratings yet
Java Practical
50 pages
MCA Sem Java Program Solution
PDF
No ratings yet
MCA Sem Java Program Solution
16 pages
JAVA UNIT-2 Notes
PDF
No ratings yet
JAVA UNIT-2 Notes
21 pages
Assignment 2
PDF
No ratings yet
Assignment 2
11 pages
Primitive Values, Wrapper Classes, Types and Casting
PDF
No ratings yet
Primitive Values, Wrapper Classes, Types and Casting
6 pages
5 6172398136460313330
PDF
No ratings yet
5 6172398136460313330
90 pages
Assignment Answers
PDF
No ratings yet
Assignment Answers
95 pages