Common Mistakes To Avoid

Understand the common mistakes and errors in order to avoid them.

❌ Common errors

Some common errors with methods that return values are:

  • Forgetting to write a return type before the method name
  • Forgetting to use the return keyword to return a value at the end of the method
  • Forgetting to store or print the return value after returning from a method
  • Adding a return type before the constructor name (like void)

🚨 An important alert

Look at the code below.

Press + to interact
ShoppingCart.java
Item.java
public class ShoppingCart
{
// Instance variable
private Item product;
// Constructor
public ShoppingCart(Item item)
{
product = item;
}
public void print()
{
product.print();
}
// Entry point: main menthod for testing purposes
public static void main (String args[])
{
Item i = new Item("Pringles", 100);
ShoppingCart cart= new ShoppingCart(i);
cart.print();
System.out.println("\n");
i.updatePrice(200); // Updating the price
ShoppingCart newCart= new ShoppingCart(i);
newCart.print();
System.out.println("\n");
cart.print(); // Here's the problem!
}
}

The code is a bit tricky. Don’t panic. Let’s go through it.

Open the Item.java file. We make an Item class. It has two variables: name and price. Next, we make its constructor to set the initial values. At line 12, we make a print() function that prints the name and price of an Item object.

In a supermarket, the prices of items change over time, so we make a void method, updatePrice(), at line 18 that takes an int type value and updates the price of the item. Up until now, everything is pretty straightforward.

Now open the ShoppingCart.java file. We make a ShoppingCart class. It has one instance variable: a variable of Item type (a class we recently created). Item is just like a data type, and ...