FAQ: Conditionals and Control Flow - Switch Statement

This community-built FAQ covers the “Switch Statement” exercise from the lesson “Conditionals and Control Flow”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Java

FAQs on the exercise Switch Statement

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

I am troubled by this exercise pls somebody help me.
https://www.codecademy.com/courses/learn-java/lessons/java-conditionals-and-control-flow/exercises/switch?action=resume_content_item

Hey @yokel2473029837, welcome to the forums!

Would you please look at this topic and add a little bit more to your question?

  
  public double calculateShipping() {
    double shippingCost;
	 	// declare switch statement here
    switch (shipping) {
      case "Regular":
        shippingCost = 0;
        break;
      case "Express":
        shippingCost = 1.75;
        break;
      default:
        shippingCost = 0.50;
    }
    
    return shippingCost;
 }
  

My solution for the exercise 5/6
The reason I used the “shipping” variable inside the paranthesis of the switch block is because…

when we create/instantiate the objects “book” and “chemistrySet” in the main() method…
the shipping preferences “Regular” and “Express” are stored in the “shipping” variable
( you can see this in the constructor method).

8 Likes

Why do we need the break in this case? Can someone explain more about break? Why don’t the switch just stop by itself? Thanks!

Essentially, a switch will match an expression’s value to a case clause, and return the associated statement.

switch (expression) {
  case 1:
    // statement to be executed
  case 2: 
    // statement to be executed
  default:
    // default statement to be executed
}

When it finds what it’s looking for, it gives you back the information that you need.

But what if you had hundreds of cases? You’d have to go through all of them, every time.

Let’s say that you have 500 cases in your switch. And case 1 matches the given expression.

Well you’d still have to go through all other 499 cases. Just to return the statement of case 1.

That’s not efficient at all.

So we add break statements to break out of the switch and return the information we were looking for.

switch (expression) {
  case 1:
    // statement to be executed
    break;
  case 2: 
    // statement to be executed
    break;
  ...
  case 500:
    // statement to be executed
    break;
  default:
    // default statement to be executed
}

If case 1 matches the expression’s value, it will break and return the associated statement, without going through all the other cases. 499 of them in this example.

Much more efficient.

By default the switch won’t just stop by itself. It’s not that smart, you have to tell the program what to do in each situation. It doesn’t think, it executes commands.

Hope this answers your question :wink:

2 Likes

Thanks! That’s really easy to understand. I have one more question: is there any case that the dev get creative and doesn’t use break? Maybe to return more than one statement?

Hi All,

I am looking for the cheatsheet for ‘Conditionals and Control Flow’. The link says it is not ready yet but I am not sure if this is correct. The link is as follows:
https://www.codecademy.com/learn/learn-java/modules/learn-java-conditionals-control-flow-u/cheatsheet

Thanks,
Igneos

In the conditional lesson :

The following code snippet is a constructor method inside the class Order :


public Order(boolean filled, double cost, String shippingMethod) {

    if (cost > 24.00) {

      System.out.println("High value item!");

    }

    isFilled = filled;

    billAmount = cost;

    shipping = shippingMethod;

  }

In the main method when we create the object out of the class —> Order
we use the following line of code -----

public static void main(String[] args) {

    // do not alter the main method!

    Order book = new Order(true, 9.99, "Express");

    Order chemistrySet = new Order(false, 72.50, "Regular");

    

    book.ship();

    chemistrySet.ship();

  }

The following is the output ------------>>

High value item!
Shipping
Shipping cost: 1.75
Order not ready

I am confused because in the constructor method -----> the conditional says if the cost of the item is greater than 24.0 then only print "High value item"

public Order(boolean filled, double cost, String shippingMethod) {

    **if (cost > 24.00) {**

**      System.out.println("High value item!");**

**    }**

    isFilled = filled;

    billAmount = cost;

    shipping = shippingMethod;

  }

When we created our Book object we gave it the following parameters —>

Order book = new Order(true, **9.99**, "Express");

Since 9.99 is lesson than 24.00 therefore the statement "High value item " should not be printed.

Any help will be highly appreciated :slight_smile:

2 Likes

I am also confused by this. Any help?

You should be able to return the same outcome for multiple cases like this:

public int someMethod(param) {
    switch (param) {
      case "a":
      case "b":
         someVariable = 1;    //do this when param == "a" or param == "b"
         break;
      case "d":
         someVariable = 2;    // do something else when param == "d"
         break;
      default:
         someVariable = 0;   // do this if param == "e" or "d" or...
    }
    System.out.println("Done!");  // this code will run after the switch is finished
    return someVariable * 2;      // this will return a value and exit the parent method
}

‘break’ is just telling Java to exit the switch. It helps save time. Otherwise Java will go through all remaining cases. Whether you use ‘break’ or not, when your switch is finished Java will move on to the next line of code in your method (see above).
If you want your switch to return a value you can skip ‘break’, as ‘return’ will also exit the switch. Keep in mind though that ‘return’ will also exit the parent method that contains your switch, and so the code following your switch will not run (see below).

public int someMethod(param) {
    switch (param) {
      case "a":
      case "b":
         return x;    //do this when param == "a" or param == "b"
      case "d":
         return y;    // do something else when param == "d"
      default:
         return 0;   // do this if param == "e" or "d" or...
    }
    System.out.println("Done!");    // This will not run, as 'return' will exit both the switch and the function it's in.  
}

1 Like

Here, if param == "d", the default block will not run. Only the code under case "d": will, since you would have broken out of the switch case.


It’s important to note that, not only does break save time, it can also ensure that the desired code is being executed. Here’s an example of a switch block without break statements.

switch (1) {
  case 0:
    System.out.println("A");
  case 1:
    System.out.println("B");
  case 2:
    System.out.println("C");
  case 3:
    System.out.println("D");
  default:
    System.out.println("N/A");
}

Can you guess what will happen? B, C, D, and N/A will all be printed. That’s why it’s important to use break statements in a way that ensures the correct code is executed.

Here’s the code after adding in break statements.

switch (1) {
  case 0:
    System.out.println("A");
    break;
  case 1:
    System.out.println("B");
    break;
  case 2:
    System.out.println("C");
    break;
  case 3:
    System.out.println("D");
    break;
  default:
    System.out.println("N/A");
    break;  // break isn't required here since default is the last case
}

Now, what will happen? Only B will be printed. That’s our desired result.

1 Like

Well spotted, victoria_dr. It’s a typo on my part. In both snippets of code it should be “f” not “d” in the “default” line comment. Like so:

case "d":
         someVariable = 2;    // do something else when param == "d"
         break;
      default:
         someVariable = 0;   // do this if param == "e" or "f" or...

As for this…

It’s important to note that, not only does break save time, it can also ensure that the desired code is being executed.

Also a good point! Without either ‘break’ or ‘return’ all following cases will also be executed.

1 Like

Even though I think you have moved on already with the course I think answering to your question might be useful to others as well, since similar question has been posted several times.

I think the cause for the “High value item!” is not the cost of the book, but the cost of the chemistySet.
Try to comment out the book and then the chemistrySet and you’ll figure it out.
See for yourself:


and

Got it?
In the main method the ship() method will be called for both of them (the book and the chemistrySet) and different messages will be printed out for the book and the chemistrySet, but since in both cases something will be printed out, it is easy to forget the other item.

If you are still looking for an answer, see the reply here.

Thank you :smiling_face_with_three_hearts:

Greetings,
The Order Method essentially reads that, "If at any point cost exceeds 24.00, print “High value item!”. This line is printed because at some point in the entire class, cost exceeded 24.00 and it was not necessarily because of the book.

So why do we declare the double shippingCost variable in the first place?