Dave Malcolm

Greenhorn
+ Follow
since Nov 12, 2023
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
In last 30 days
0
Forums and Threads

Recent posts by Dave Malcolm

Thanks for clearing that all up everyone - much appreciated. I have one more question.

In the code I originally posted PrintSeason (which I now know to be a switch statement ) doesn't require a default branch whereas PrintSeason2 (the switch expression) does. Why?

I can even write PrintSeason(13) and the compiler doesn't complain and it runs fine but doesn't produce any output! That seems very wrong!!!
Well this bloody book is very badly written then - totally confusing. Take a look at the relevant section on P117 and tell me it's not confusing?

It specifically says - and i quote directly...

"Let's rewrite our printSeason() method from earlier using a switch expression:
   public  void printSeason(int month) {
       switch(month) {
           case 1, 2, 3 -> System.out.println("Winter");
           case 4, 5, 6 -> System.out.println("Spring");
           case 7, 8, 9 -> System.out.println("Summer");
           case 10, 11, 12 -> System.out.println("Fall");
       }
"

that's a direct quote from the book. I repeat that if what you're both saying is true then the book is awful because this is supposed to prepare people for the exam.
I'm only relating what it says in the (very confusing then) book on P117 in the section on switch expressions.

So the -> can be used in ordinary switch statements then can it?
A previous errata correction states that a semicolon must be placed at the end of the code in Figure 3.4 (which shows the structure of a switch expression).
This is only true if the Optional assignment (int result =) is coded.
Without the Optional assignment, code compiles and works fine without the semicolon at the end of the curly brace - at least it does so under java 17 for me.
Note also that the default branch is required only for the switch statement that includes the Optional assignment when all cases are covered.
On P435 of the 2022 edition of the OCP Guide the authors (who often confuse me) make the following statement (without supplying an example of what they mean)
"Before you ask, most of the time we don't assign the implementation of the interface to a variable. The interface name is implied, and it is passed directly to the method that needs it"
Here's some code they provide. Can someone please provide substitute code that doesn't assign the implementation to a variable.


Are they talking about the assignment of s1 or d1? Please show me in code? Or have I completely missed the point?
If s1 then the last line would have to be

which hardly seems worth the effort.
1 year ago