SlideShare uma empresa Scribd logo
1 de 19
Java 102: Intro to Object-oriented
Programming in Java
Hands-on Exercises
Hands-on Exercise
Creating Objects
Exercise: Creating Objects
• Create a new Java project named Java102
• Create a new package named exercise.carfactory
• Create a class named Car in the exercise.carfactory
package
• Add color, make and model properties to the Car class
• Create a java program named CarFactory (in same
package) that creates two instances of the class Car,
changes their colors to Blue and Pink and prints a message
to the console
• Run the class CarFactory and observe the message in the
Console.
Solution: Creating Objects
package exercise.creatingobjects;
public class Car {
String make;
String model;
String color;
}
package exercise.creatingobjects;
public class CarFactory {
public static void main(String[] args) {
Car firstCar = new Car();
Car secondCar = new Car();
firstCar.color = "Blue";
secondCar.color = "Pink";
System.out.println("Just finished painting new cars");
}
}
Car.java
CarFactory.java
Hands-on Exercise
Working with Methods
Exercise: Working with Methods
• What happens when you compile and run the
following code?
public class Cubes {
static int cube (int i){
int j = i * i * i;
return j;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i=0 ;i<= N; i++) {
System.out.println(i + " " + cube(i));
}
}
}
Solution: Working with Methods
public class Cubes {
static int cube (int i){
int j = i * i * i;
return j;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i=0 ;i<= N; i++) {
System.out.println(i + " " + cube(i));
}
}
}
% java Cubes 6
0 0
1 1
2 8
3 27
4 64
5 125
6 216
Hands-on Exercise
Method Overloading
Exercise : Method Overloading
• Create a new package named exercise.methodoverloading
• Create a BasicRateTax class with a method calcTax() that returns 20% of a fixed
base income of £1000
• Create a java program named TaxCollector that creates a new BasicRateTax object,
calls the calcTax() method and prints the output to the console
• Run the TaxCollector program and ensure it always prints 200.00 as calculated tax
• Add new calcTax() method to BasicRateTax class that takes a double grossIncome
parameter and calculates the tax as 20% of the grossIncome if it’s greater than the
base income of £1000
• Change the TaxCollector program to call the new calcTax(double grossIncome)
method and passing the gross Income value from the command line
• Run the TaxCollector program and see if the tax is correctly calculated.
• Re-run the program with different Gross Income values and check the output
Solution: Method Overloading
package exercise.methodoverloading;
public class BasicRateTax {
private static final double BASE_INCOME = 1000.00;
private static final double BASIC_TAX_RATE = 0.20;
public double calcTax (){
return BASE_INCOME * BASIC_TAX_RATE;
}
public double calcTax(double grossIncome){
if (grossIncome < BASE_INCOME){
return calcTax();
}
return grossIncome * BASIC_TAX_RATE;
}
}
Solution: Method Overloading
package exercise.methodoverloading;
public class TaxCollector {
public static void main(String[] args) {
double grossIncome = Double.parseDouble(args[0]);
BasicRateTax taxCalculator = new BasicRateTax();
double tax = taxCalculator.calcTax(grossIncome);
System.out.println("Tax due is " + tax);
}
}
% java TaxCollector 2000
Tax due is 400.0
% java TaxCollector 10000
Tax due is 2000.0
Hands-on Exercise
Inheritance
Exercise: Inheritance
• Create a new package named exercise.inheritance
• Create a class named HigherRateTax in the exercise.inheritance package that
extends BasicRateTax and add an empty calcTax(double grossIncome) method
• Add the code to HigherRateTax.calcTax(double grossIncome) method to calculate
the tax as follows:
– 20% of grossIncome if up to £34,000 (hint: reuse the BasicRateTax.calcTax(double
grossIncom) method)
– 40% of grossIncome if above £34,000 but less than £150,000
– 50% of grossIncome if £150,000 or above
• Run the existing TaxCollector program with some large gross income amounts and
observe that your changes didn’t have any effect on the calculate tax. Why?
• Change the code of the TaxCollector to instantiate HigherRateTax instead of
BasicRateTax
• Run the TaxCollector program again and observe that now the new percentage is
properly applied. You are now using the overridden version of the method
calcTax().
Solution: Inheritance
package exercise.inheritance;
import exercise.methodoverloading.BasicRateTax;
public class HigherRateTax extends BasicRateTax {
public double calcTax(double grossIncome){
double tax = 0.0;
if (grossIncome <=34000.00){
tax = super.calcTax(grossIncome);
}else if (grossIncome > 34000 && grossIncome <=150000) {
tax = grossIncome * 0.40;
}else if (grossIncome > 150000){
tax = grossIncome * 0.50;
}
return tax;
}
}
Solution: Inheritance
package exercise.methodoverloading;
import exercise.inheritance.HigherRateTax;
public class TaxCollector {
public static void main(String[] args) {
double grossIncome = Double.parseDouble(args[0]);
BasicRateTax taxCalculator = new HigherRateTax ();
double tax = taxCalculator.calcTax(grossIncome);
System.out.println("Tax due is " + tax);
}
}
% java TaxCollector 51000
Tax due is 20400.0
% java TaxCollector 32000
Tax due is 6400.0
% java TaxCollector 155000
Tax due is 77500.0
Hands-on Exercise
Using a Java Library
Exercise: Using Libraries
• Create a new package named exercise.libraryclient
• Create a class named CardDealer with an empty
deal() method that takes no arguments and returns
a String
• Implement the card dealer to use the StdRandom
library to deal playing cards ramdomly from an
infinite deck of cards
• Create a CardDealerTest program to test the
CardDealer class
Exercise: Using the StdRandom Library
public class CardDealer {
private static final String[] SUITES = { "D", "H", "C", "S"
};
private static final int TOTAL_CARDS_PER_SUITE = 13;
public String deal() {
// select a random suite
String suite = SUITES[StdRandom.uniform(SUITES.length)];
// select a random rank
int rank = StdRandom.uniform (TOTAL_CARDS_PER_SUITE ) +
1;
String card = rank + suite;
// return the dealt card
return card;
}
}
Testing the CardDealer Program
public class CardDealerTest {
public static void main(String[] args) {
CardDealer dealer = new CardDealer();
for (int i=0;i<5;i++){
String card = dealer.deal();
System.out.println( “ Card “ + i + “ is “ + card);
}
}
}

Mais conteúdo relacionado

Mais procurados (20)

Decision Making and Looping
Decision Making and LoopingDecision Making and Looping
Decision Making and Looping
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
2D Array
2D Array2D Array
2D Array
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
CPU INPUT OUTPUT
CPU INPUT OUTPUT CPU INPUT OUTPUT
CPU INPUT OUTPUT
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Managing I/O operations In C- Language
Managing I/O operations In C- LanguageManaging I/O operations In C- Language
Managing I/O operations In C- Language
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Nested loops
Nested loopsNested loops
Nested loops
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-Sharp
 
C# loops
C# loopsC# loops
C# loops
 
Visual Basic(Vb) practical
Visual Basic(Vb) practicalVisual Basic(Vb) practical
Visual Basic(Vb) practical
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Strings in C
Strings in CStrings in C
Strings in C
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++
 
Introduction to Input/Output Functions in C
Introduction to Input/Output Functions in CIntroduction to Input/Output Functions in C
Introduction to Input/Output Functions in C
 

Semelhante a Java 102 intro to object-oriented programming in java - exercises

PT1420 Modules in Flowchart and Visual Basic .docx
PT1420 Modules in Flowchart and Visual Basic             .docxPT1420 Modules in Flowchart and Visual Basic             .docx
PT1420 Modules in Flowchart and Visual Basic .docxamrit47
 
Informatics Practice Practical for 12th class
Informatics Practice Practical for 12th classInformatics Practice Practical for 12th class
Informatics Practice Practical for 12th classphultoosks876
 
exercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdfexercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdfenodani2008
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design ExamplesTareq Hasan
 
Asp netmvc e03
Asp netmvc e03Asp netmvc e03
Asp netmvc e03Yu GUAN
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with codekamal kotecha
 
C# Advanced L02-Operator Overloading+Indexers+UD Conversion
C# Advanced L02-Operator Overloading+Indexers+UD ConversionC# Advanced L02-Operator Overloading+Indexers+UD Conversion
C# Advanced L02-Operator Overloading+Indexers+UD ConversionMohammad Shaker
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptsbhargavi804095
 
Battle of React State Managers in frontend applications
Battle of React State Managers in frontend applicationsBattle of React State Managers in frontend applications
Battle of React State Managers in frontend applicationsEvangelia Mitsopoulou
 
Procedure to create_the_calculator_application java
Procedure to create_the_calculator_application javaProcedure to create_the_calculator_application java
Procedure to create_the_calculator_application javagthe
 
This is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdfThis is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdfindiaartz
 
C# Programming. Using methods to call results to display. The code i.pdf
C# Programming. Using methods to call results to display. The code i.pdfC# Programming. Using methods to call results to display. The code i.pdf
C# Programming. Using methods to call results to display. The code i.pdffatoryoutlets
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAlfa Gama Omega
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdfssusera587d2
 
Apollo. The client we deserve
Apollo. The client we deserveApollo. The client we deserve
Apollo. The client we deserveYuri Nezdemkovski
 

Semelhante a Java 102 intro to object-oriented programming in java - exercises (20)

Java 102
Java 102Java 102
Java 102
 
PT1420 Modules in Flowchart and Visual Basic .docx
PT1420 Modules in Flowchart and Visual Basic             .docxPT1420 Modules in Flowchart and Visual Basic             .docx
PT1420 Modules in Flowchart and Visual Basic .docx
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Informatics Practice Practical for 12th class
Informatics Practice Practical for 12th classInformatics Practice Practical for 12th class
Informatics Practice Practical for 12th class
 
exercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdfexercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdf
 
IT104 Week 4 - Module/Function
IT104 Week 4 - Module/FunctionIT104 Week 4 - Module/Function
IT104 Week 4 - Module/Function
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design Examples
 
Asp netmvc e03
Asp netmvc e03Asp netmvc e03
Asp netmvc e03
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
C# Advanced L02-Operator Overloading+Indexers+UD Conversion
C# Advanced L02-Operator Overloading+Indexers+UD ConversionC# Advanced L02-Operator Overloading+Indexers+UD Conversion
C# Advanced L02-Operator Overloading+Indexers+UD Conversion
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
 
Battle of React State Managers in frontend applications
Battle of React State Managers in frontend applicationsBattle of React State Managers in frontend applications
Battle of React State Managers in frontend applications
 
Procedure to create_the_calculator_application java
Procedure to create_the_calculator_application javaProcedure to create_the_calculator_application java
Procedure to create_the_calculator_application java
 
This is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdfThis is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdf
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
C# Programming. Using methods to call results to display. The code i.pdf
C# Programming. Using methods to call results to display. The code i.pdfC# Programming. Using methods to call results to display. The code i.pdf
C# Programming. Using methods to call results to display. The code i.pdf
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf
 
Apollo. The client we deserve
Apollo. The client we deserveApollo. The client we deserve
Apollo. The client we deserve
 

Mais de agorolabs

Introduction to Agile
Introduction to AgileIntroduction to Agile
Introduction to Agileagorolabs
 
Computer Programming Overview
Computer Programming OverviewComputer Programming Overview
Computer Programming Overviewagorolabs
 
Java 101 Intro to Java Programming - Exercises
Java 101   Intro to Java Programming - ExercisesJava 101   Intro to Java Programming - Exercises
Java 101 Intro to Java Programming - Exercisesagorolabs
 
Java 201 Intro to Test Driven Development in Java
Java 201   Intro to Test Driven Development in JavaJava 201   Intro to Test Driven Development in Java
Java 201 Intro to Test Driven Development in Javaagorolabs
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programmingagorolabs
 

Mais de agorolabs (7)

Introduction to Agile
Introduction to AgileIntroduction to Agile
Introduction to Agile
 
Computer Programming Overview
Computer Programming OverviewComputer Programming Overview
Computer Programming Overview
 
Java 101 Intro to Java Programming - Exercises
Java 101   Intro to Java Programming - ExercisesJava 101   Intro to Java Programming - Exercises
Java 101 Intro to Java Programming - Exercises
 
Java 201 Intro to Test Driven Development in Java
Java 201   Intro to Test Driven Development in JavaJava 201   Intro to Test Driven Development in Java
Java 201 Intro to Test Driven Development in Java
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
 

Último

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Último (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Java 102 intro to object-oriented programming in java - exercises

  • 1. Java 102: Intro to Object-oriented Programming in Java Hands-on Exercises
  • 3. Exercise: Creating Objects • Create a new Java project named Java102 • Create a new package named exercise.carfactory • Create a class named Car in the exercise.carfactory package • Add color, make and model properties to the Car class • Create a java program named CarFactory (in same package) that creates two instances of the class Car, changes their colors to Blue and Pink and prints a message to the console • Run the class CarFactory and observe the message in the Console.
  • 4. Solution: Creating Objects package exercise.creatingobjects; public class Car { String make; String model; String color; } package exercise.creatingobjects; public class CarFactory { public static void main(String[] args) { Car firstCar = new Car(); Car secondCar = new Car(); firstCar.color = "Blue"; secondCar.color = "Pink"; System.out.println("Just finished painting new cars"); } } Car.java CarFactory.java
  • 6. Exercise: Working with Methods • What happens when you compile and run the following code? public class Cubes { static int cube (int i){ int j = i * i * i; return j; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i=0 ;i<= N; i++) { System.out.println(i + " " + cube(i)); } } }
  • 7. Solution: Working with Methods public class Cubes { static int cube (int i){ int j = i * i * i; return j; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i=0 ;i<= N; i++) { System.out.println(i + " " + cube(i)); } } } % java Cubes 6 0 0 1 1 2 8 3 27 4 64 5 125 6 216
  • 9. Exercise : Method Overloading • Create a new package named exercise.methodoverloading • Create a BasicRateTax class with a method calcTax() that returns 20% of a fixed base income of £1000 • Create a java program named TaxCollector that creates a new BasicRateTax object, calls the calcTax() method and prints the output to the console • Run the TaxCollector program and ensure it always prints 200.00 as calculated tax • Add new calcTax() method to BasicRateTax class that takes a double grossIncome parameter and calculates the tax as 20% of the grossIncome if it’s greater than the base income of £1000 • Change the TaxCollector program to call the new calcTax(double grossIncome) method and passing the gross Income value from the command line • Run the TaxCollector program and see if the tax is correctly calculated. • Re-run the program with different Gross Income values and check the output
  • 10. Solution: Method Overloading package exercise.methodoverloading; public class BasicRateTax { private static final double BASE_INCOME = 1000.00; private static final double BASIC_TAX_RATE = 0.20; public double calcTax (){ return BASE_INCOME * BASIC_TAX_RATE; } public double calcTax(double grossIncome){ if (grossIncome < BASE_INCOME){ return calcTax(); } return grossIncome * BASIC_TAX_RATE; } }
  • 11. Solution: Method Overloading package exercise.methodoverloading; public class TaxCollector { public static void main(String[] args) { double grossIncome = Double.parseDouble(args[0]); BasicRateTax taxCalculator = new BasicRateTax(); double tax = taxCalculator.calcTax(grossIncome); System.out.println("Tax due is " + tax); } } % java TaxCollector 2000 Tax due is 400.0 % java TaxCollector 10000 Tax due is 2000.0
  • 13. Exercise: Inheritance • Create a new package named exercise.inheritance • Create a class named HigherRateTax in the exercise.inheritance package that extends BasicRateTax and add an empty calcTax(double grossIncome) method • Add the code to HigherRateTax.calcTax(double grossIncome) method to calculate the tax as follows: – 20% of grossIncome if up to £34,000 (hint: reuse the BasicRateTax.calcTax(double grossIncom) method) – 40% of grossIncome if above £34,000 but less than £150,000 – 50% of grossIncome if £150,000 or above • Run the existing TaxCollector program with some large gross income amounts and observe that your changes didn’t have any effect on the calculate tax. Why? • Change the code of the TaxCollector to instantiate HigherRateTax instead of BasicRateTax • Run the TaxCollector program again and observe that now the new percentage is properly applied. You are now using the overridden version of the method calcTax().
  • 14. Solution: Inheritance package exercise.inheritance; import exercise.methodoverloading.BasicRateTax; public class HigherRateTax extends BasicRateTax { public double calcTax(double grossIncome){ double tax = 0.0; if (grossIncome <=34000.00){ tax = super.calcTax(grossIncome); }else if (grossIncome > 34000 && grossIncome <=150000) { tax = grossIncome * 0.40; }else if (grossIncome > 150000){ tax = grossIncome * 0.50; } return tax; } }
  • 15. Solution: Inheritance package exercise.methodoverloading; import exercise.inheritance.HigherRateTax; public class TaxCollector { public static void main(String[] args) { double grossIncome = Double.parseDouble(args[0]); BasicRateTax taxCalculator = new HigherRateTax (); double tax = taxCalculator.calcTax(grossIncome); System.out.println("Tax due is " + tax); } } % java TaxCollector 51000 Tax due is 20400.0 % java TaxCollector 32000 Tax due is 6400.0 % java TaxCollector 155000 Tax due is 77500.0
  • 17. Exercise: Using Libraries • Create a new package named exercise.libraryclient • Create a class named CardDealer with an empty deal() method that takes no arguments and returns a String • Implement the card dealer to use the StdRandom library to deal playing cards ramdomly from an infinite deck of cards • Create a CardDealerTest program to test the CardDealer class
  • 18. Exercise: Using the StdRandom Library public class CardDealer { private static final String[] SUITES = { "D", "H", "C", "S" }; private static final int TOTAL_CARDS_PER_SUITE = 13; public String deal() { // select a random suite String suite = SUITES[StdRandom.uniform(SUITES.length)]; // select a random rank int rank = StdRandom.uniform (TOTAL_CARDS_PER_SUITE ) + 1; String card = rank + suite; // return the dealt card return card; } }
  • 19. Testing the CardDealer Program public class CardDealerTest { public static void main(String[] args) { CardDealer dealer = new CardDealer(); for (int i=0;i<5;i++){ String card = dealer.deal(); System.out.println( “ Card “ + i + “ is “ + card); } } }