Welcome to the Primitives and Expressions Lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 2 terms. 2. Describe declarations, variables, literals and constants for primitive numerical data types. 3. Describe String literals, concatenation and constants. 4. Evaluate a sequence of primitive data type expressions using binary operators (*, -, *,/,%, =) including conversions between numeric primitive types. 5. Use class (Math) methods in expressions. 6. Use a precedence and associativity table. 7. Write a method call and definition including parameter, and return value. Exercise A: Terms Please write out (on paper or notepad) your understanding of each of these terms (which are mostly from zybooks). As you are doing the lab, consider whether your understanding is confirmed or clarified. Review your understanding with a TA. variable, variable declaration, data type, primitive data type, byte vs int vs short vs long vs float vs double, assignment vs equality, expression evaluation, identifier, identifier naming convention, camel casing, keyword, literal, 8 vs 8.0 vs 8.0F vs 8L, implicit type conversion vs explicit type conversion, constant vs final, method call vs. method definition, argument vs parameter Exercise B: Trace and Explain For this code segment: int k = 2; k = k + 1; k = k * 2; Here are a couple of ways of drawing a picture of what is happening in memory as the code is executed. Drawings such as this can be helpful as you trace code. In the code, "k" is a variable (name for a location in memory). Variables usually change their values as the code is executed. Tracking the current values can be helpful as you are tracing the code. k 2 3 6 Or k 2 3
6 Below is a Java Operator Precedence and Associativity table. Precedence tells us that operators with higher precedence are evaluated before lower precedence operators. For example, the expression: 5 + 4 * 3 is evaluated if it were 5 + (4 * 3) because * has higher precedence than +. Associativity tells us how operators with the same precedence are grouped when parentheses are absent. For example, the expression: 4-3 - 2 is evaluated as if it were (4-3) - 2 because the operators + and - are left-to-right associative. Another example is the expression b = a = 1 is evaluated as it if were b = (a = 1) because = is right-to-left associative. Sub-expressions are evaluated left-to-right. A sub-expression may be a variable, for example, and evaluating a variable means retrieving its value. If c has value 3, then the expression c * (c = 2) would be 6 since the value of c is retrieved (3), then the assignment of 2 to c would be completed, before multiplying 2 to 3. With your partner, trace and explain each of the following (also found in traceexplain.txt ). Check your understanding using Java Visualizer. A. //Do these statements have the same result? int i; i = 4 + 3 * 2; i = 4 + (3 * 2); i = (4 + 3) * 2; B. //Will both the literal values fit in the shoesize variable? //Will shoesize store both values are just the last value? double shoesize = 9.5; shoesize = 10;
C. //Will these compile? If not, why not? int mysize = 8.5; int fraction = 4/8; D. //What exactly (integer vs floating point matters) will each result be? double fraction = 4 / 8; fraction = 4.0 / 8; fraction = (int) 4.0 / 8; fraction = 4.0 / 8; fraction = (double) (4 / 8); E. //How are the following different? double answer = 5.0 / 0.0; int answerint = 5 / 0; F. final double PI = 3.14; PI = 3.1415926; //Does this work? Why or why not? G. //What does % operator do? int num = 10 % 2; int num = 3 % 2; int num = 1397836563 % 2; H. int cents = 1097; int dollars = cents / 100; cents = cents % 100; int quarters = cents / 25; cents %= 25; I. //Is assignment left-to-right or right-to-left associative? int a = 1; int b = 2; int c = 3; int d = 4; a = b = c = d; J. //How do you know whether + means addition or concatenation? String str = "howdy"; str = str + str; String str2 = 1 + 2 + str + 3 + 4; K. //Are these the same? Why or why not? String exprstr1 = 4 + 1 + " = 4 + 1"; String exprstr2 = "4 + 1 = " + 4 + 1; String exprstr3 = "4 + 1 = " + (4 + 1);
L. int value = 36; double squareroot = Math.sqrt( value); M. //What should the data type of result be? //How can you find out? result = Math.pow( 2, 32); N. //What should the data type of lowest be? lowest = Math.min( 8, 9); lowest = Math.min( 8+2, 9); lowest = Math.min( Math.min(5,6), Math.min(19, 20)); lowest = Math.min( lowest, value); O. int result = Math.min( Math.max( 1, Math.min(3, 5)), Math.min(3, Math.min( 2, 4))); P. int x = -4; int abs = Math.abs(x); Q. //Is the value of the variable changed while evaluating the expression? int a = 1; System.out.print("a="); System.out.print( (a = 2) + a); int b = 1; System.out.print(", b="); System.out.print( b + (b = 2)); Explanation (copy into Notepad to see): Since ( ) have higher precedence than + the expression within ( ) is evaluated first. So, (a = 2) results in the value 2 is assigned to a and the resulting value of the expression is also 2. Next, the value in a is retrieved (2) and then added to the result of (a=2) resulting in a value of 4 for the entire expression. (a = 2) + a \=/ / 2 2 \ + / 4 As before ( ) have higher precedence than +. But when evaluating the expression the sub-expressions are evaluated left-to-right. Therefore the value of the first b is retrieved (1) then the (b = 2) is evaluated resulting in b changing to 2 and the result of (b = 2) being 2. Finally the 1 that was retrieved prior is added to 2 resulting in a value of 3 for the entire expression. This follows both rules of precedence and order of evaluation. b + (b = 2) 1 \=/ \ 2 \ + /
3 Exercise C: Edit-Compile-Run Cycle If you have not yet completed the Edit-Compile-Run cycle tutorial, do so now as the next exercises use the command-line tools. Before continuing, for each of the tools (editor, compiler and virtual machine) make sure you can answer: What is a summary of what each tool does in the programming process? What are the names used on the command-line for each of the tools? What are the inputs and outputs? Does the order the tools are run matter? What is the meaning of compile-time? What is the meaning of runtime? What kinds of errors can occur when using each tool? Exercise D: Change Using the command-line tools, extend Change.java to also calculate dimes, nickels and pennies. Output: Amount: 1094 Dollars: 10 Quarters: 3 Dimes: 1 Nickels: 1 Pennies: 4 Exercise E: Math documentation Where can you find the documentation for all the methods available in the java.lang.math class? Exercise F: Reorder Lines Using the command-line tools, reorder lines to fix CubeSurfaceArea.java. Example interleaved input and output: Enter length of one side of cube: 3 Cube has surface area: 54.0 Now add the following testing method, testsurfaceareaofcube(), to the CubeSurfaceArea class. Improve testsurfaceareaofcube with additional testing cases. Then call the testsurfaceareaofcube() method from the main method. public static void testsurfaceareaofcube() {
System.out.println( "surfaceareaofcube( 2) = " + surfaceareaofcube( 2) + " should equal 24.0" ); //add statements to call surfaceareaofcube with arguments of 1 and 0. Example output is: surfaceareaofcube( 2) = 24.0 should equal 24.0 surfaceareaofcube( 1) = 6.0 should equal 6.0 surfaceareaofcube( 0) = 0.0 should equal 0.0 Ask a TA to verify you have created and called the testing method correctly. Exercise G: Area of Triangle We want a program to calculate the area of a triangle. Here is a systematic, incremental approach to creating and testing a program to do this. Follow along by writing an extending this Triangle.java program using the command-line tools. 1. Find an Equation http://www.mathopenref.com/trianglearea.html 2. Convert Equation to Java We implement this equation with the following Java statements: double base; //length of base double altitude; //length of altitude double area = base * altitude / 2.0; Then, define a method for these statements: public static double areaoftriangle( double base, double altitude) { //equation from: http://www.mathopenref.com/trianglearea.html double area = base * altitude / 2.0; return area;
3. Write a Testing Method We create a testing method to call the areaoftriangle method for various cases. Add a couple of additional test cases to testareaoftriangle(). public static void testareaoftriangle() { 2) System.out.println( "areaoftriangle( 3, 2) = " + areaoftriangle( 3, + " should equal 3.0"); //create a couple of other test cases Show a TA the test cases you have created. Discuss with a TA what the terms boundary case or corner case might mean. 4. Call the Testing Method Call the testing method from the main method to verify the areaoftriangle method is working correctly: public class Triangle { public static double areaoftriangle(double base, double altitude) { // equation from: http://www.mathopenref.com/trianglearea.html double area = base * altitude / 2.0; return area; public static void testareaoftriangle() { System.out.println("areaOfTriangle( 3, 2) = " + areaoftriangle(3, 2) + " should equal 3.0"); // create a couple of other test cases... public static void main(string[] args) { testareaoftriangle(); Example output: areaoftriangle( 3, 2) = 3.0 should equal 3.0 //plus additional test cases Show a TA the testing output of your program.
5. Use the Calculation Method Once you have verified the new method, areaoftriangle, works correctly then extend your program to use the method. In our program write the code to prompt the user for values within the main method and then call the areaoftriangle method. import java.util.scanner; public class Triangle { public static double areaoftriangle(double base, double altitude) { // equation from: http://www.mathopenref.com/trianglearea.html double area = base * altitude / 2.0; return area; public static void testareaoftriangle() { System.out.println("areaOfTriangle( 3, 2) = " + areaoftriangle(3, 2) + " should equal 3.0"); // create a couple of other test cases... public static void main(string[] args) { //testareaoftriangle(); Scanner input = new Scanner(System.in); System.out.print("Enter base: "); double baselength = input.nextdouble(); System.out.print("Enter altitude: "); double altitudeheight = input.nextdouble(); double trianglearea = areaoftriangle(baselength, altitudeheight); System.out.println( "Triangle with base " + baselength + " and altitude " + altitudeheight + " has area " + trianglearea); input.close(); Example Output: Enter base: 6 Enter altitude: 4.5 Triangle with base 6.0 and altitude 4.5 has area 13.5 Show a TA the complete working program and the output. Discuss why it is better to have testing code that can rerun a set of test cases rather than prompting the user for adhoc test cases.
Exercise H: Celsius to Fahrenheit Temperature Conversion Go through the systematic, incremental process of writing a program to do Celsius to Fahrenheit Temperature conversion. Show a TA your working program including testing method. Exercise I: Fix Logic Errors Using the command-line tools, fix the logic errors in DistanceBetweenPoints.java. Creating a testing method to test the calculation may be very helpful. Example 1: This program finds the distance between 2 points (x1,y1) and (x2,y2). Enter x1: 2 Enter y1: 4 Enter x2: 4 Enter y2: 4 Distance between points (2,4) and (4,4) is 2.0 Example 2: This program finds the distance between 2 points (x1,y1) and (x2,y2). Enter x1: 1 Enter y1: 1 Enter x2: 4 Enter y2: 4 Distance between points (1,1) and (4,4) is 4.242640687119285 Exercise J: Area of Cylinder Go through the systematic, incremental process of writing a program to do Area of Cylinder calculation. Show a TA your working program including testing method. Exercise K: Pick an Equation When you have tested your methods then review with a TA. Format your programs following the course Style Guide. Exercise L: Quiz To help you assess your own mastery of the material, see if you can answer these questions without looking back. 1. What is printed out? System.out.print( 1 + 2 + "3" + 4 + 5); 2. What is the resulting data type of the following expression? 3 + Math.max( 3, 4.0) 3. What is the meaning of the symbol: % in a Java program?
4. What does the following command mean when run on the command-line? What is the input and output? java Hello 5. What is the first line of code that the JVM executes in the Java application programs that we have seen in this course? And what is the last line of code before ending? 6. What are key benefits of a systematic, incremental approach to writing programs? Additional Learning Materials When you have mastered everything in this lab and previous labs, then you are welcome to learn from additional learning resources available on the web and beyond this course: https://cs200-www.cs.wisc.edu/wp/learn-to-program-resources/ Note: Due to programs and zybooks being individual work, it is Not appropriate to work on them during the Team Lab. Contributions by Sean McClanahan, Marc Renault Lab 2018 Jim Williams