Java Basics Exercises You are not turning this in, so you don’t really need to write anything down. These are the types of questions you will be asked. Work with a partner if you want. Consider this your test study guide. Note: There are some trick questions below. I don’t normally do trick questions on a test, but they illustrate common errors programmers make. 1. There are two ways to do comments. Let’s say you wanted to put your name, date, and project name at the top of your project. Write out both ways to do that using comments. 2. What will print out to the screen with the following code? System.out.print("UCLA"); System.out.print("Bruins"); System.out.print("are #1!"); 3. What will print out to the screen with the following code? System.out.print("To be or\nnot to be..."); 4. What will print out to the screen with the following code? System.out.print("The answer is: System.out.println(3/5); 5. "); What will print out to the screen with the following code? String firstName = "Joe", lastName = "Black"; System.out.print(firstName + " " + "lastName"); 6. What will print out to the screen with the following code? System.out.println("When I go Trick or Treating, I want to get"); System.out.println("Reese’s, M&Ms, and//or Snickers."); 7. What will print out to the screen with the following code? System.out.println(9.18 + 7.02 + " is the total ounces of yogurt."); System.out.println("The total comes to $" + 5.17 + 3.95 + "."); 8. What will print out to the screen with the following code? System.out.print(Math.pow(-2, 6)); Page 1 of 15 9. What will print out to the screen with the following code? System.out.print(Math.pow(Math.abs((int)-5.892), Math.abs((int)3.95))); 10. What will print out to the screen with the following code? System.out.println(9/4); 11. What will print out to the screen with the following code? System.out.println((double)(9/4)); 12. What will print out to the screen with the following code? System.out.println(9/4.0); This poem is from President George W. Bush written to Laura during his presidency while he was away. At one point during his presidency, it was posted at http://www.whitehouse.gov so presumably it is real. Write the poem with only one System.out.print statement. 13. Roses are red, Violets are blue, Oh my lump in the bed, How I’ve missed you. 14. Write the code that would produce this output to the screen: Randy said, "No!" 15. Write the code that would produce this output to the screen: The survey says... \ / \/ /\ / \ 16. For this problem, create variables that would store the information provided, and then store the information inside of the variable you created. Do each part (part a., part b., etc.) with only one line of code, i.e. it should take four lines of code to do all four parts of this question. a. 3.14159 b. Eat my shorts! c. 56 Note: Create a variable that only accepts whole numbers. d. true Note: Create a variable that only accepts true or false. Page 2 of 15 17. Vocab time! a. What is a bit? b. What is a byte? 18. Determine whether each of the following variable declarations is legal or illegal. a. int num1 = 4.2; b. int num2 = (int)3.8; c. double num3 = 5; d. double num4 = "1.18"; e. int num5 = 8.0; f. int num6 = (int)(7.9 + 3.7); g. int num7 = 9/4; h. String input = 1973; i. String answer1 = true; j. boolean answer2 = t; k. boolean answer3 = "true"; l. String doesThisWork = "\n"; m. String howAboutThis = "\"\"\"\"\"\"\"\"\"\""; 19. What will print out to the screen with the following code? System.out.println((int)Math.random()); Page 3 of 15 The next seven problems will test your ability to follow what is happening with the code. Just like every math class you have ever had, it is a good idea with these type of problems to show your work so that I can follow your thought process and give you partial credit if your final answer is wrong. I usually suggest making a column for each variable and keep track of the current value of the variable there, while also showing what the previous values were. So for a problem with 3 variables (x, y, and z) which start out with values of 4, 6, and 1 respectively, this might be a way to track how their values change during the execution of a program: __x__ __y__ __z__ 4 6 1 3 8 4 4 6 7 The final values would be 3, 7, and 6. It is easy for me (and you) to see what you did and how it all progressed, and if you make one error early on, I can follow what you did and see if you managed the rest correctly. Obviously you don’t need to do it this way. It is just a suggestion if you want possible partial credit, and usually quite helpful for students to follow these type of problems. 20. What does the following code print? int x, y = 16, z = 10; x = y % z; y /= x; x = z – y * x; System.out.println ("x is: " + x); 21. What does the following code print? double x = 4.18; int y = 2; x /= y; System.out.println ("x is: + x"); 22. What does the following code print? double z = 6; int y = 8, x = 13; x += y; y -= (int)z; z *= (x / z); System.out.println ("z is: " + z); Page 4 of 15 23. What does the following code print? int x, y = 9, z = 2; x = y / z; x += x; System.out.println ("x is: " + x); 24. What does the following code print? int x; double y = 9.0, z = 2.0; x = (int)(y / z); x += x; System.out.println ("x is: " + x); 25. What does the following code print? String x = "ABC", y = "DEF", z; z = x + y; z += x; System.out.println ("z is: " + z); 26. What does the following code print? int age = 54; int x = 7, y = 5, z; z = age – x * y; z %= x; z--; System.out.println ("z is: " + z); 27. A programmer typed in the following code expecting the output to occasionally contain decimals but there is integer division tripping him up. How could he change the last line of code only so that it will print out the full decimal answer? int input1, input2; //some code that asks the user to enter numbers for the integers. System.out.println(input1/input2); Page 5 of 15 28. Starting with this question, you should do these problems in BlueJ. Note: Your output must match exactly to my sample examples in each problem. The user input should show up on the same line, make sure you have blank lines where they are supposed to be, make sure all punctuation is there, etc. You WILL get marked off on the AP and on my test for missing any of those details. Seriously…your output needs to match EXACTLY. Most of the time, I will provide you a project to start from before each set of exercises, where a lot of the tedious class creation and setup for each problem will have been done for you (so that you can jump right into the exercises faster). However, you should be able to that, so for this first unit, you need to create your own project, as well as create a brand new class for each of the problems below, clear out the extra code, start your own public static void main, and create your own Scanners and all of that. These are skills you should have. Ask the user to enter in their age (decimals are okay). Then ask them to enter their first name. Then ask them to enter in their last name. After that output Full Name is # years old. As an example, look at the following sample run of a program below. Note: These three things in blue are the things that the user inputs (and will Please enter your age: 47.2 show up on the screen and look like Please enter your first name: Chuck this). On tests, I can’t print in color so Please enter your last name: Dawson they will just be in bold. Chuck Dawson is 47.2 years old. Get familiar with that! You need to match that output! 29. Ask the user to enter in two integers (this will need to be two separate lines). Then output the average of those two numbers just like I have done below (with the numbers they entered in as part of the output line). Be careful about integer division here. Just like the last problem, you need to get Please enter in an integer: 74 familiar with distinguishing which of the Please enter in another integer: 89 pieces at left is your output, e.g. the "Please enter in an integer: " part, and which of the pieces are things the The average of 74 and 89 is 81.5. user entered, e.g. the "74". They look exactly the same on the screen, so be careful. 30. We are going to channel your inner 3rd grader. Ask the user to enter in a dividend and a divisor (both integers), and then output the answer to the division problem like your 3rd grade teacher would have wanted. Like this: Please enter in a dividend: 27 Please enter in a divisor: 5 27 divided by 5 is 5 remainder 2. Page 6 of 15 31. Ask the user to enter in a number of degrees in Celsius. Then output the equivalent number of degrees in Fahrenheit. For those who can’t remember the conversion formula, it is: 9 = Degrees Fahrenheit ( DegreesCelsius ) + 32 5 Make sure the value they entered in is part of the output, like I have done with the 76.4 below. Please enter in a number of degrees in Celsius: 76.4 76.4 degrees Celsius is equal to 169.52 degrees Fahrenheit. 32. Ask the user to enter in name of an item. Ask the user to enter in the price of the item and use the name of the item in the prompt (see below). Provide them the $ sign, too. Ask the user to enter in the number of items purchased. Then output the subtotal. Output how much tax is due on that (calculated at 7.25%), and don’t worry about keeping it to two decimal places. Then output the final total. It should look something like: Please enter the name of the item: Botox Barbie Please enter the price of the Botox Barbie: $34.99 Please enter the number of Botox Barbie bought: 13 Subtotal: $454.87 Tax Due: $32.978075 Total Due: $487.848075 33. Ask the user to enter in 2 numbers (decimals are o.k.). The output what the sum of those numbers is, what the first number minus the second number is, what the numbers multiplied together are, and finally what the first number divided by the second number is. It should look like this: Please enter in a number (decimals are o.k.): 5.67 Please enter in a second number (decimals are o.k.): 5.67 5.67 5.67 5.67 + – * / 3.48 3.48 3.48 3.48 = = = = 3.48 9.15 2.19 19.7316 1. 6293103448275863 34. Ask the user to enter in the number of hours, the number of minutes, and the number of seconds (all integers). Then output the total number of seconds that that is. It should look just like this: Please enter in the number of hours: 7 Please enter in the number of minutes: 34 Please enter in the number of seconds: 37 7 hours, 34 minutes, and 37 seconds is equal to 27277 seconds. Page 7 of 15 35. Now create a project that works in reverse. Ask the user to enter in an integer number of seconds, and then output how many hours, minutes, and seconds that is. Hint: You will need to make use of integer division (here, it is actually useful!) for the hours and minutes, and the easiest way to deal with the seconds is to use modulus (although you can get there the long way by subtracting). Please enter in an integer number of seconds: 63745 63745 seconds is equal to 17 hours, 42 minutes, and 25 seconds. 36. You all remember your geometry, I am sure, so I shouldn’t need to give you the formula for calculating the volume and surface area of a sphere. Right? *sigh* …here are the formulas: 4 3 πr 3 Surface area = 4πr 2 Volume = Ask the user for a radius of a sphere and then output the volume and surface area of that sphere. Use 3.14159265 for the value of π, and also use the pow function of the Math class to calculate the powers (since it is such a small power, I wouldn’t normally care if you used r*r*r, but the point of this problem is to get you practice using functions from the Math class. Please enter in the radius of the sphere: 7.2 The volume of the sphere is 1563.4575645696. The surface area of the sphere is 651.4406519040001. I have told you it is important to match output exactly (on the AP test, too). Did you notice the periods finishing the sentences? Have you done that for all the problems? 37. Ask the user for an integer, then output the absolute value of that integer. A sample running of the program should look just like this: Please enter in an integer: -18 The absolute value of -18 is 18. This should be super simple at this point... Page 8 of 15 38. Ask the user for a positive integer, then output the square root of that integer. A sample running of the program should look like: Please enter in a positive integer: 23 The square root of 23 is 4.795831523312719. 39. Generate a random decimal value from -2.9 (inclusive) to 16.3 (exclusive) to be used as the base of an exponent. Then generate a random integer from 3 (inclusive) to 7 (inclusive) to be used as the power of an exponent. This will help hammer home the difference between creating random decimals vs. integers. The base from -2.9 to 16.3 that I have created is -1.8478910818030612. The power from 3 to 7 that I have created is 4. -1.8478910818030612 raised to the power of 4 is 11.660185994047753. 40. Ask the user for a decimal number. Then output the square root, third root, fourth root, and fifth root of that number. In order to do the third root, fourth root, and fifth roots, you will need to use the pow method in the Math class and raise the number the user entered to fractional powers. A sample run would look like: Please enter in a decimal value: The The The The 8.7 square root of 8.7 is 2.949576240750525. third root of 8.7 is 2.0567101162059633. fourth root of 8.7 is 1.7174330382144525. fifth root of 8.7 is 1.5413591700421996. 41. If you do the following: System.out.println(1234 * 5678 * 9012); Java prints out: -1280561616 Why? We multiply three positive 4-digit numbers together and end up with a negative number? And a big negative number at that? Why? What happened? Page 9 of 15 42. Create a program that generates a lot of different random numbers. The first random number it should generate is an integer from 1 to 6 (normal die roll). The next number should be a random integer from 14 to 39. The next number should be a random integer from -19 to 62. The next number should be a random decimal from 0.0 (inclusive) to 8.0 (exclusive). The next random number should be a decimal from -3.0 (inclusive) to 15.0 (exclusive). Run the program many many times to see if you are getting values in the right range. A sample run should look like: You should run your code many Random integer from 1 to 6: 5 times to make sure your results are Random integer from 14 to 39: 32 falling in the right range. Random integer from -19 to 62: -11 Random decimal in the interval [0.0, 8.0): 2.456727283724164 Random decimal in the interval [-3.0, 15.0): -0.6874378986939647 43. Create a program that generates four random numbers from 10 to 99, i.e. a two-digit number. Output the four numbers generated, then output the sum of those four numbers. Random Random Random Random #1 #2 #3 #4 from from from from 10 10 10 10 to to to to 99 99 99 99 is is is is 78. 11. 36. 81. The sum of those four numbers is 206. 44. For this problem, we are going to try and generate a random integer from a random range as well as a random decimal from that same random range. How will we do that? First, it might be easiest to show you what it looks like. Our random range is going to be -19 to 65. A random integer in that range is 44. A random decimal in that range is -18.245498388059104. In that first line of output, the -19 was generated from a random number from -100 to -1, both inclusive. The 65 was generated from a random number from 1 to 100, both inclusive. Page 10 of 15 45. Let’s start off easy. a. By this point in the exercises, part a. should be a snap. Write some code which parrots back what the user enters in. Like this: Please enter in some text: The text you entered was: b. Hi there! Hi there! Now, what do you think happens if the user types in "Hi there!" Instead? Do you think your code will crash? Or what if they typed in Hi\nthere!? Do you think the output line will end up being on two lines? Obviously this will be quick for you to test out, but it’s an interesting thing to ponder before you do. A few notes about the test: First, I tried to impress on you in the document that random numbers were crazy important. One of the most common problems on this first test is that students don’t really have that down yet. Random numbers come up all the time so you need to get them down. No…really. Down cold. And it won’t just be this test. Almost every test has random numbers on them. This is a vital skill – and I tell students that every year – but every year a surprising number of students just don’t really believe it until they get hammered on it a few tests in a row. So don’t do that. Get those random numbers down! Second, make sure you actually have taken the time to execute and run a lot of these word problems in BlueJ. You will get a much better sense of how things are all working by actually running them in BlueJ. Students who do that end up doing much better on the test. And it only really helps if you actually are trying to do the coding on your own. It doesn’t help as much to just look at the answer key and think, yep, I could have done that. A bunch of you will do that, too. Third, you need to get used to matching the output of the sample program runs that I give you. Put in the periods, the spaces, etc. Matching output is important on the AP test, too. It takes practice to see in the sample runs which parts are your output and which parts are the user input, but that is a key skill to get down. The test questions will look like the word problems here with sample output given. Page 11 of 15 Fourth, I give you the following chart on the test: abs pow Math Class random sqrt So you don’t need to memorize what all of these things are named – you just need to know how to use them. Also don’t forget about integer division. It is a crazy common bug on tests. People mistakenly do it all the time when they don’t intend to. But then there are those times where integer division is helpful (like Problem #35). In fact, I have a feeling there will be a problem on the test where integer division is helpful. Another common problem on the first test is that students mix math class with comp sci. For example, in Java, multiplication is a * or a *, however, when doing multiplication on comp sci tests, I will often have students try to do this: int x = (4)(8); or int x = 4 · 8; Neither one of those works. I know it works in math class, but it doesn’t work in code. So don’t do that! And lastly, you don’t yet need to know/memorize the public class, public static void main, import line, or Scanner line(s). I will give all of those lines to you on the test (that won’t always be the case, but it is for the first couple tests). For example, on the test you might see something like this where you would put your code into the blank in the middle inside of the public static void main. import java.util.Scanner; public class Problem19 { public static void main(String[] args) { Scanner userInput = new Scanner(System.in); } } Page 12 of 15 Advanced Section I am often going to include an “advanced section” on these homework sets. The problems in the advanced section are, um, well…advanced! The Advanced Section is always optional. You don’t need to do them. The problems are either harder than what will be found on the test, push concepts that are beyond the scope of the AP curriculum, are programming brain teasers, etc. These problems are here for students who think they might want to major in computer science or pursue it as a career. These are the kinds of problems that will help get you thinking as an advanced programmer. 46. This question highlights something interesting to ponder, but it clearly isn’t something you would normally do (and I wouldn’t expect you to remember it). Let’s say we have a simple, standard comment: /* * What happens if you comment out a comment? */ Simple, right? But what do you think happens if you do this? // /* * What happens if you comment out a comment? */ And now what do you think happens if you do this? /* * // What happens if you comment out a comment? */ Clearly you would never do that in practice (I hope), but it’s interesting to think about what might actually happen if you did. Page 13 of 15 47. In the Java Basics document, I briefly showed you some of the variable types which are in Java but are not covered in the class because they are not in the AP curriculum. In particular, I said that char and long were odd omissions from the AP curriculum, so this problem is a brain teaser which involves long to get you exposed to it some more. A long variable takes up 64 bits of memory and holds integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Basically, long is simply an int which takes up twice as much memory and thus can hold MUCH bigger numbers. For this problem, you need to know that a millisecond is 1/1000th of a second, and a microsecond is onemillionth of a second. Do you know how many milliseconds or microseconds are in day? Not off the top of your head, probably, but you can calculate it. Often programmers are faced with things like this, and they create variables that do the calculations on the fly rather than crunching the numbers themselves and putting that in their code. Therefore, you will often see programmers do something like this: long microsecondsPerDay = 24 * 60 * 60 * 1000 * 1000; int millisecondsPerDay = 24 * 60 * 60 * 1000; The calculation for milliseconds per day is 86,400,000. That fits into an int variable fine, so we can create that variable as an int. However, the number of microseconds per day (86,400,000,000) is over 40x bigger than will fit into an int, so we create that variable as a long instead. Pretty straightforward, right? Now it is time for the brainteaser. The calculation for microseconds per day should be 1000 times bigger than milliseconds per day. In fact, I have given you the actual numbers above, and you can see that it is. However, if I run this line of code: System.out.println(microsecondsPerDay / millisecondsPerDay); Then a 5 prints to the screen. Why? What happened? Page 14 of 15 48. This problem is going to seem weird, but that’s why it is in the advanced section. Let’s say I have the following: double x = 6.4; int y = 5; y = y + x; System.out.println(y); This generates an error: So far so good, right? That should be an error. You shouldn’t be able to put a double into an int. However, if I change the code to this: double x = 6.4; int y = 5; y += x; System.out.println(y); Now the code works. It really shouldn’t. It makes no sense. Type it in if you want to confirm for yourself, but it really does work. What do you suppose prints? Why do you think it works? Page 15 of 15