Path Menu Get Unstuck Tools: My Home

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

My Home

Path Menu
Connected to Codecademy
Get Unstuck
Tools

Learn Java: Methods: Adding Parameters

Narrative and Instructions

Learn
LEARN JAVA: METHODS
Adding Parameters
We saw how a method’s scope prevents us from using variables declared in one method in
another method. What if we had some information in one method that we needed to pass into
another method?

Similar to how we added parameters to constructors, we can customize all other methods to
accept parameters. For example, in the following code, we create a startRadio() method that
accepts a Double parameter, stationNum, and a String parameter called stationName:

class Car {

  String color;

  public Car(String carColor) {


    color = carColor;         
  }

  public void startRadio(double stationNum, String stationName) {


    System.out.println("Turning on the radio to " + stationNum + ", "
+ stationName + "!");
    System.out.println("Enjoy!");
  }

  public static void main(String[] args){


    Car myCar = new Car("red");
    myCar.startRadio(103.7, "Meditation Station");
  }
}
Adding parameter values impacts our method’s signature. Like constructor signatures, the
method signature includes the method name as well as the parameter types of the method. The
signature of the above method is startRadio(double, String).

In the main() method, we call the startRadio() method on the myCar object and provide


a double argument of 103.7 and String argument of "Meditation Station", resulting in the
following output:

Turning on the radio to 103.7, Meditation Station!


Enjoy!
Note that when we call on a method with multiple parameters, the arguments given in the call
must be placed in the same order as the parameters appear in the signature. If the argument types
do not match the parameter types, we’ll receive an error.

Keep Reading: AP Computer Science A Students

Through method overloading, our Java programs can contain multiple methods with the same
name as long as each method’s parameter list is unique. For example, we can recreate our above
program to contain two startRadio() methods:

// Method 1
public void startRadio(double stationNum, String stationName) {
  System.out.println("Turning on the radio to " + stationNum + ", "
+ station + "!");
  System.out.println("Enjoy!");
}

// Method 2
public void startRadio(double stationNum) {
  System.out.println("Turning on the radio to " + stationNum + "!");
}

public static void main(String[] args){


  Car myCar = new Car("red");
  // Calls the first startRadio() method
  myCar.startRadio(103.7, "Meditation Station");

  // Calls the second startRadio() method


  myCar.startRadio(98.2);
}

Instructions

1.
Add a method to the Store class called greetCustomer(). It should be accessible by other classes,
and return no output. For now, have it take no parameters and leave the body of the method
empty.
Checkpoint 2 Passed

Hint
If we wanted to write a method called bark() that is accessible by other classes and produces no
output, we would use syntax like:

public void bark(){

}
2.
Modify the greetCustomer() method so that it accepts a String parameter called customer.
Checkpoint 3 Passed

Hint
To add a parameter to a method signature, you put it in the parentheses:

public void methodWithIntParam(int myIntParam){

}
3.
Inside of the greetCustomer() method, add a print statement to print:

"Welcome to the store, " + customer + "!"


Checkpoint 4 Passed

4.
Inside the main() method, call the greetCustomer() method on the lemonadeStand object. Pass in
a String argument of your choice!
Checkpoint 5 Passed

Hint
If I were calling this method to greet myself, I would use the line:

lemonadeStand.greetCustomer("Laura");

store.java

public class Store {

// instance fields

String productType;

// constructor method

public Store(String product) {

productType = product;
}

// advertise method

public void advertise() {

String message = "Selling " + productType + "!";

System.out.println(message);

public void greetCustomer(String customer){

System.out.println("Welcome to the store, " + customer + "!");

// main method

public static void main(String[] args) {

Store lemonadeStand = new Store("Lemonade");

lemonadeStand.greetCustomer("Laura");

}
My Home
Path Menu
Workspace restored.
Get Unstuck
Tools

Learn Java: Methods: Reassigning Instance Fields

Narrative and Instructions

Learn
LEARN JAVA: METHODS
Reassigning Instance Fields
Earlier, we thought about a Savings Account as a type of object we could represent in Java.

Two of the methods we need are depositing and withdrawing:

public SavingsAccount{
  double balance;
  public SavingsAccount(double startingBalance){
    balance = startingBalance;
  }

  public void deposit(double amountToDeposit){


     //Add amountToDeposit to the balance
  }

  public void withdraw(double amountToWithdraw){


     //Subtract amountToWithdraw from the balance
  }

  public static void main(String[] args){

  }
}
These methods would change the value of the variable balance. We can reassign balance to be a
new value by using our assignment operator, =, again.

public void deposit(double amountToDeposit){


  double updatedBalance = balance + amountToDeposit;
  balance = updatedBalance;
}
Now, when we call deposit(), it should change the value of the instance field balance:

public static void main(String[] args){


  SavingsAccount myAccount = new SavingsAccount(2000);
  System.out.println(myAccount.balance);
  myAccount.deposit(100);
  System.out.println(myAccount.balance);
}
This code first prints 2000, the initial value of myAccount.balance, and then prints 2100, which is
the value of myAccount.balance after the deposit() method has run.

Changing instance fields is how we change the state of an object and make our objects more
flexible and realistic.

Instructions

1.
We have added a price instance field to the Store class.

However, to combat inflation costs, we’ve found ourselves increasing the price of our product
over and over. We’ve added an empty increasePrice() method to the Store class. It takes
a double parameter priceToAdd.

Inside of the increasePrice() method, create a variable called newPrice. Declare it to be a double,


and set it equal to the price plus the priceToAdd.
Checkpoint 2 Passed

2.
Inside of increasePrice(), set the instance field price to be newPrice!
Checkpoint 3 Passed

3.
In the main() method, increase the price at the lemonade stand by 1.5. Then, print
the lemonadeStand.price to see how it has changed!
Checkpoint 4 Passed

Store.java

public class Store {

// instance fields

String productType;

double price;

// constructor method

public Store(String product, double initialPrice) {

productType = product;

price = initialPrice;

// increase price method

public void increasePrice(double priceToAdd){

double newPrice = price + priceToAdd;

price = newPrice;

// main method

public static void main(String[] args) {

Store lemonadeStand = new Store("Lemonade", 3.75);

lemonadeStand.increasePrice(1.5);

System.out.println(lemonadeStand.price);

}
}

My Home
Path Menu
Connected to Codecademy
Get Unstuck
Tools

Learn Java: Methods: Returns

Narrative and Instructions

Learn
LEARN JAVA: METHODS
Returns
Remember, variables can only exist in the scope that they were declared in. We can use a value
outside of the method it was created in if we return it from the method.

We return a value by using the keyword return:

public int numberOfTires() {


   int tires = 4;
   // return statement
   return tires;
}
This method, called numberOfTires(), returns 4. Once the return statement is executed, the
compiler exits the function. Any code that exists after the return statement in a function is
ignored.

In past exercises, when creating new methods, we used the keyword void. Here, we are
replacing void with int, to signify that the return type is an int.

The void keyword (which means “completely empty”) indicates that no value is returned after
calling that method.

A non-void method, like numberOfTires() returns a value when it is called. We can use datatype


keywords (such as int, char, etc.) to specify the type of value the method should return. The
return value’s type must match the return type of the method. If the return expression is
compatible with the return type, a copy of that value gets returned in a process known as return
by value.
Unlike void methods, non-void methods can be used as either a variable value or as part of an
expression like so:

public static void main(String[] args){


    Car myCar = new Car("red");
    int numTires = myCar.numberOfTires();
}
Within main(), we called the numberOfTires() method on myCar. Since the method returns
an int value of 4, we store the value in an integer variable called numTires. If we
printed numTires, we would see 4.

Keep Reading: AP Computer Science A Students

We learned how to return primitive values from a method, but what if we wanted our method to
return an object? Returning an object works a little differently than returning a primitive value.
When we return a primitive value, a copy of the value is returned; however, when we return an
object, we return a reference to the object instead of a copy of it.

Let’s create a second class, carLot, that takes in a Car as a parameter and contains a method
which returns a Car object.

class CarLot {
    Car carInLot;
    public CarLot(Car givenCar) {
        carInLot = givenCar;
    }

    public Car returnACar() {


        // return Car object
        return carInLot;
    }

    public static void main(String[] args) {


        Car myCar = new Car("red", 70);
        System.out.println(myCar);
        CarLot myCarLot = new CarLot(myCar);
        System.out.println(myCarLot.returnACar());
    }
}
This code outputs the same memory address because myCar and carInLot have the same reference
value:

Car@2f333739
Car@2f333739

Instructions
1.
We want to have a method that returns the price plus tax.

Define a method called getPriceWithTax() that is intended to return the price plus the tax. It
should take in no parameters and return a double.

You can leave the body of the method empty for now. Note: the code will have an error until we
return the correct type from the method, which we will do in the next step.
Hint
To create a method called getNumBarks() that returns an int, we would use the syntax:

public int getNumBarks(){


}
2.
Inside the getPriceWithTax() method, create a double variable totalPrice that is equal to price +
price * 0.08. 0.08 is the tax applied to the price.

Then, return totalPrice.
Hint
You can also accomplish this by defining a variable called tax, and then multiplying
by tax instead:

double tax = 0.08;


double totalPrice = price + price*tax;
Make sure to return totalPrice at the end!
3.
Inside of main(), set a double variable lemonadePrice to the value returned
by lemonadeStand.getPriceWithTax().
4.
Now, print out lemonadePrice.

public class Store {

// instance fields

String productType;

double price;

// constructor method

public Store(String product, double initialPrice) {

productType = product;
price = initialPrice;

// increase price method

public void increasePrice(double priceToAdd){

double newPrice = price + priceToAdd;

price = newPrice;

// get price with tax method

public double getPriceWithTax(){

double tax = 0.08;

double totalPrice = price + price*tax;

return totalPrice;

// main method

public static void main(String[] args) {

Store lemonadeStand = new Store("Lemonade", 3.75);

double lemonadePrice = lemonadeStand.getPriceWithTax();

System.out.println(lemonadePrice);

}
My Home
Path Menu
Connected to Codecademy
Get Unstuck
Tools

Learn Java: Methods: The toString() Method

Narrative and Instructions

Learn
LEARN JAVA: METHODS
The toString() Method
When we print out Objects, we often see a String that is not very helpful in determining what the
Object represents. In the last lesson, we saw that when we printed our Store objects, we would
see output like:

Store@6bc7c054
where Store is the name of the object and 6bc7c054 is its position in memory.

This doesn’t tell us anything about what the Store sells, the price, or the other instance fields
we’ve defined. We can add a method to our classes that makes this printout more descriptive.

When we define a toString() method for a class, we can return a String that will print when we
print the object:

class Car {

    String color;

    public Car(String carColor) {


        color = carColor;
    }

    public static void main(String[] args){


        Car myCar = new Car("red");
        System.out.println(myCar);
    }

   public String toString(){


       return "This is a " + color + " car!";
   }
}
When this runs, the command System.out.println(myCar) will print This is a red car!, which
tells us about the Object myCar.

Instructions

1.
In the main() method, print the Objects lemonadeStand and cookieShop. Are these printouts helpful
in understanding these Objects?
2.
Create a toString() method for the Store class. The method signature should say that it is public,
and that it returns a String. It shouldn’t take in any parameters. For now, have it return
the String "Store".
3.
"Store" isn’t very helpful! What kind of Store is it?

Change the toString() to return a String that describes this Store object.

Your String should look like:

This store sells productType at a price of price.


where productType and price are the values in those instance fields. For example, if it was a hat
store where hats cost 8, the String would say:

This store sells hats at a price of 8.


4.
Look at the printouts again. Are they more helpful now?
public class Store {

// instance fields

String productType;

double price;

// constructor method

public Store(String product, double initialPrice) {

productType = product;

price = initialPrice;

// increase price method

public void increasePrice(double priceToAdd){

double newPrice = price + priceToAdd;

price = newPrice;

// get price with tax method

public double getPriceWithTax(){

double tax = 0.08;

double totalPrice = price + price*tax;

return totalPrice;

// main method
public static void main(String[] args) {

Store lemonadeStand = new Store("Lemonade", 3.75);

Store cookieShop = new Store("Cookies", 5);

}
My Home
Path Menu
Workspace restored.
Get Unstuck
Tools

Learn Java: Methods: The toString() Method

Narrative and Instructions

Learn
LEARN JAVA: METHODS
The toString() Method
When we print out Objects, we often see a String that is not very helpful in determining what the
Object represents. In the last lesson, we saw that when we printed our Store objects, we would
see output like:

Store@6bc7c054
where Store is the name of the object and 6bc7c054 is its position in memory.

This doesn’t tell us anything about what the Store sells, the price, or the other instance fields
we’ve defined. We can add a method to our classes that makes this printout more descriptive.

When we define a toString() method for a class, we can return a String that will print when we
print the object:

class Car {

    String color;

    public Car(String carColor) {


        color = carColor;
    }

    public static void main(String[] args){


        Car myCar = new Car("red");
        System.out.println(myCar);
    }

   public String toString(){


       return "This is a " + color + " car!";
   }
}
When this runs, the command System.out.println(myCar) will print This is a red car!, which
tells us about the Object myCar.

Instructions

1.
In the main() method, print the Objects lemonadeStand and cookieShop. Are these printouts helpful
in understanding these Objects?
Checkpoint 2 Passed

2.
Create a toString() method for the Store class. The method signature should say that it is public,
and that it returns a String. It shouldn’t take in any parameters. For now, have it return
the String "Store".
Checkpoint 3 Passed

3.
"Store" isn’t very helpful! What kind of Store is it?

Change the toString() to return a String that describes this Store object.

Your String should look like:

This store sells productType at a price of price.


where productType and price are the values in those instance fields. For example, if it was a hat
store where hats cost 8, the String would say:

This store sells hats at a price of 8.


Checkpoint 4 Passed

4.
Look at the printouts again. Are they more helpful now?
My Home
Path Menu
Workspace restored.
Get Unstuck
Tools

Learn Java: Methods: Review

Narrative and Instructions

Learn
LEARN JAVA: METHODS
Review
Great work! Methods are a powerful way to abstract tasks away and make them repeatable. They
allow us to define behavior for classes, so that the Objects we create can do the things we expect
them to. Let’s review everything we have learned about methods so far.

 Defining a method : Methods have a method signature that declares their return type,
name, and parameters
 Calling a method : Methods are invoked with a . and ()
 Parameters : Inputs to the method and their types are declared in parentheses in the
method signature
 Changing Instance Fields : Methods can be used to change the value of an instance field
 Scope : Variables only exist within the domain that they are created in
 Return : The type of the variables that are output are declared in the method signature

As you move through more Java material, it will be helpful to frame the tasks you create in terms
of methods. This will help you think about what inputs you might need and what output you
expect.

Instructions

1.
Now that we’ve learned about behavior, we can apply behavior to our SavingsAccount class using
methods!

We’ve added the functionality for each method inside main() now, but you will be rebuilding
each above main(). Note that your methods can directly access the balance field.

First, write a method called checkBalance() that prints:


Hello!
Your balance is
with the balance of the account displayed.

It should take in no parameters and return nothing.


Checkpoint 2 Passed

Hint
A checkPrice() method for our Store class would have looked like:

public void checkPrice(){


  System.out.println("Welcome!");
  System.out.println("The price is "+ price);
}
How would you do this for checkBalance()?

Don’t forget to call


2.
Now, write a method called deposit() that takes in an int parameter amountToDeposit and adds it
to the balance. It should return nothing.

If you want, you can also have the method print:

You just deposited amountToDeposit


with the value of amountToDeposit displayed.
Checkpoint 3 Passed

Hint
An addInventory() method for our Store class would have looked something like:

public void addInventory(int inventoryToAdd){


  int newInventory = inventory + inventoryToAdd;
  inventory = newInventory;
}
You can do something similar for deposit()!
3.
Now, write a method called withdraw() that takes in an int parameter amountToWithdraw and
subtracts it from the balance. It should return the amountToWithdraw.

If you want, you can also have the method print:

You just withdrew amountToWithdraw


with the value of amountToWithdraw displayed.
Checkpoint 4 Passed

Stuck? Get a hint


4.
Test out your methods by trying to replace some of the code in the main() method with the
equivalent methods!

Make sure to use checkBalance(), deposit(), and withdraw() at least once each.


Checkpoint 5 Passed

5.
Congratulations! You’ve made a basic SavingsAccount.

If you want, you can add more functionality to this! What other instance fields might you want to
keep track of? What might a toString() look like for this class?

public class SavingsAccount {

int balance;

public SavingsAccount(int initialBalance){

balance = initialBalance;

public void checkBalance(){

System.out.println("Hello!");

System.out.println("Your balance is "+balance);

public void deposit(int amountToDeposit){

balance = amountToDeposit + balance;

System.out.println("You just deposited " + amountToDeposit);

public int withdraw(int amountToWithdraw){

balance = balance - amountToWithdraw;

System.out.println("You just withdrew " + amountToWithdraw);

return amountToWithdraw;
}

public String toString(){

return "This is a savings account with " + balance + " saved.";

public static void main(String[] args){

SavingsAccount savings = new SavingsAccount(2000);

//Check balance:

savings.checkBalance();

//Withdrawing:

savings.withdraw(300);

//Check balance:

savings.checkBalance();

//Deposit:

savings.deposit(600);

//Check balance:

savings.checkBalance();

//Deposit:
savings.deposit(600);

//Check balance:

savings.checkBalance();

System.out.println(savings);

https://discuss.codecademy.com/t/build-a-droid-help/512527

You might also like