SlideShare a Scribd company logo
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);
}
}
}

More Related Content

What's hot (20)

DOCX
Lab manual asp.net
Vivek Kumar Sinha
Ā 
PPTX
Html formatting
Webtech Learning
Ā 
PDF
The JavaScript Programming Language
guestceb98b
Ā 
PPTX
Java swing
Apurbo Datta
Ā 
PPT
C++ Function
Hajar
Ā 
ODP
Web service Introduction
Madhukar Kumar
Ā 
PPTX
Html table
JayjZens
Ā 
PDF
Exercices en turbo pascal sur la rƩcursivitƩ
salah fenni
Ā 
PPT
stack, opeartions on stack, applications of stack
Minakshee Patil
Ā 
PPT
Introduction To C#
SAMIR BHOGAYTA
Ā 
PPT
List in java
nitin kumar
Ā 
PPTX
The Complete HTML
Rohit Buddabathina
Ā 
PDF
Constants, Variables and Data Types in Java
Abhilash Nair
Ā 
PDF
Javascript essentials
Bedis ElAchĆØche
Ā 
PPT
Java Basics
Brandon Black
Ā 
PPT
What Is Php
AVC
Ā 
PPTX
Arrays in java
bhavesh prakash
Ā 
PPSX
Javascript variables and datatypes
Varun C M
Ā 
PDF
Object Oriented Solved Practice Programs C++ Exams
MuhammadTalha436
Ā 
Lab manual asp.net
Vivek Kumar Sinha
Ā 
Html formatting
Webtech Learning
Ā 
The JavaScript Programming Language
guestceb98b
Ā 
Java swing
Apurbo Datta
Ā 
C++ Function
Hajar
Ā 
Web service Introduction
Madhukar Kumar
Ā 
Html table
JayjZens
Ā 
Exercices en turbo pascal sur la rƩcursivitƩ
salah fenni
Ā 
stack, opeartions on stack, applications of stack
Minakshee Patil
Ā 
Introduction To C#
SAMIR BHOGAYTA
Ā 
List in java
nitin kumar
Ā 
The Complete HTML
Rohit Buddabathina
Ā 
Constants, Variables and Data Types in Java
Abhilash Nair
Ā 
Javascript essentials
Bedis ElAchĆØche
Ā 
Java Basics
Brandon Black
Ā 
What Is Php
AVC
Ā 
Arrays in java
bhavesh prakash
Ā 
Javascript variables and datatypes
Varun C M
Ā 
Object Oriented Solved Practice Programs C++ Exams
MuhammadTalha436
Ā 

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

PPTX
Java 102
Manuela Grindei
Ā 
PPTX
Java 102 intro to object-oriented programming in java
agorolabs
Ā 
PDF
Big Java Early Objects 5th Edition Horstmann Solutions Manual
budmarumbet
Ā 
PPTX
Stop that!
Doug Sparling
Ā 
PDF
"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu
ThinkOpen
Ā 
PPTX
Overview of ECE Engineer
piyushkumar979747
Ā 
PPTX
Joy of scala
Maxim Novak
Ā 
PPT
Inheritance & Polymorphism - 1
PRN USM
Ā 
PPT
Ch02 primitive-data-definite-loops
James Brotsos
Ā 
PDF
Core Java Programming Language (JSE) : Chapter VI - Class Design
WebStackAcademy
Ā 
PDF
SOLID Java Code
Omar Bashir
Ā 
PPTX
Object Oriented Programming Concepts
Bhushan Nagaraj
Ā 
TXT
CORE JAVA
Shohan Ahmed
Ā 
PDF
Built-in Classes in JAVA
Mahmoud Ali Ibrahim
Ā 
PDF
Built in classes in java
Mahmoud Ali
Ā 
PPTX
A Case Study on Java. Java Presentation
Ayush Gupta
Ā 
PPT
Java htp6e 09
Ayesha ch
Ā 
PDF
Howto get input with java
Syed Faizan Hassan
Ā 
PDF
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Edureka!
Ā 
PDF
Week 4
EasyStudy3
Ā 
Java 102
Manuela Grindei
Ā 
Java 102 intro to object-oriented programming in java
agorolabs
Ā 
Big Java Early Objects 5th Edition Horstmann Solutions Manual
budmarumbet
Ā 
Stop that!
Doug Sparling
Ā 
"Java 8, Lambda e la programmazione funzionale" by Theodor Dumitrescu
ThinkOpen
Ā 
Overview of ECE Engineer
piyushkumar979747
Ā 
Joy of scala
Maxim Novak
Ā 
Inheritance & Polymorphism - 1
PRN USM
Ā 
Ch02 primitive-data-definite-loops
James Brotsos
Ā 
Core Java Programming Language (JSE) : Chapter VI - Class Design
WebStackAcademy
Ā 
SOLID Java Code
Omar Bashir
Ā 
Object Oriented Programming Concepts
Bhushan Nagaraj
Ā 
CORE JAVA
Shohan Ahmed
Ā 
Built-in Classes in JAVA
Mahmoud Ali Ibrahim
Ā 
Built in classes in java
Mahmoud Ali
Ā 
A Case Study on Java. Java Presentation
Ayush Gupta
Ā 
Java htp6e 09
Ayesha ch
Ā 
Howto get input with java
Syed Faizan Hassan
Ā 
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Edureka!
Ā 
Week 4
EasyStudy3
Ā 
Ad

More from agorolabs (6)

PDF
Introduction to Agile
agorolabs
Ā 
PPTX
Computer Programming Overview
agorolabs
Ā 
PPTX
Java 101 Intro to Java Programming - Exercises
agorolabs
Ā 
PPTX
Java 201 Intro to Test Driven Development in Java
agorolabs
Ā 
PPTX
Java 103 intro to java data structures
agorolabs
Ā 
PPTX
Java 101 Intro to Java Programming
agorolabs
Ā 
Introduction to Agile
agorolabs
Ā 
Computer Programming Overview
agorolabs
Ā 
Java 101 Intro to Java Programming - Exercises
agorolabs
Ā 
Java 201 Intro to Test Driven Development in Java
agorolabs
Ā 
Java 103 intro to java data structures
agorolabs
Ā 
Java 101 Intro to Java Programming
agorolabs
Ā 
Ad

Recently uploaded (20)

PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
Ā 
PDF
ģœ ė‹ˆķ‹°ģ—ģ„œ Burst Compiler+ThreadedJobs+SIMD ģ ģš©ģ‚¬ė”€
Seongdae Kim
Ā 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
Ā 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
Ā 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
Ā 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
Ā 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
Ā 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
Ā 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
Ā 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
Ā 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
Ā 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
Ā 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
Ā 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
Ā 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
Ā 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
Ā 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
Ā 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
Ā 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
Ā 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
Ā 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
Ā 
ģœ ė‹ˆķ‹°ģ—ģ„œ Burst Compiler+ThreadedJobs+SIMD ģ ģš©ģ‚¬ė”€
Seongdae Kim
Ā 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
Ā 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
Ā 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
Ā 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
Ā 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
Ā 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
Ā 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
Ā 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
Ā 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
Ā 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
Ā 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
Ā 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
Ā 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
Ā 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
Ā 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
Ā 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
Ā 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
Ā 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
Ā 

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); } } }