 Branching, Looping, and Creating Methods in JSP

• Print
This chapter is from the book

Workshop

This workshop tests whether you understand all the concepts you learned today. It's a good idea to master today's concepts by honing your knowledge here before starting tomorrow's material. You can find the answers to the quiz questions in Appendix A.

Quiz

1. If you wanted to match a String value against fifteen possible other strings, which would you use, an if-else ladder or a switch statement?

2. How do you make sure certain code is always run in a switch statement if no case statement is executed?

3. What are the three expressions inside the parentheses of an if statement, and what do they do?

4. What statement lets you end a loop early?

5. What's the difference between passing by value and passing by reference?

Exercises

1. One thing Java lacks is a handy method named square that returns the square of values you pass to it. Create such a method now that takes an int value and returns a long value (why should you return a long value?) holding the square of the integer. And don't forget to test it out with a few test values!

2. Factorials can get pretty big pretty fast. Modify the factorial code in today's code so it avoids trying to find a factorial that is larger than can fit into an int variable. The largest possible integer value is Integer.MAX_VALUE in Java. (Hint: In the current stage of the factorial code, check to see if you're going to exceed Integer.MAX_VALUE by using conditional statements to compare the value returned by factorial(n-1) to Integer.MAX_VALUE / n, where n is the number you're about to multiply factorial(n-1) by.)