Welcome to the Primitives and Expressions Lab!

Similar documents
Welcome to the Using Objects lab!

Welcome to the Using Objects lab!

CS Week 2. Jim Williams, PhD

CEN 414 Java Programming

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Chapter 2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Full file at

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

JAVA Programming Concepts

Program Fundamentals

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

CS Programming I: Primitives and Expressions

CS111: PROGRAMMING LANGUAGE II

Programming with Java

AP Computer Science Unit 1. Programs

Chapter 2: Data and Expressions

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Introduction to Computer Science Unit 2. Notes

Getting started with Java

Introduction to Java Applications

Java Classes: Math, Integer A C S L E C T U R E 8

Algorithms and Programming I. Lecture#12 Spring 2015

Chapter 2 Primitive Data Types and Operations. Objectives

Basics of Java Programming

Chapter 2 Elementary Programming

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

Fundamentals of Programming Data Types & Methods

Basic Programming Elements

Chapter 2: Basic Elements of Java

Lecture 2: Operations and Data Types

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

double float char In a method: final typename variablename = expression ;

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Chapter 2 Elementary Programming

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Chapter 2: Data and Expressions

CIS133J. Working with Numbers in Java

Chapter 2 Elementary Programming

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Chapter 2 ELEMENTARY PROGRAMMING

Anatomy of a Java Program: Comments

AP Computer Science Unit 1. Writing Programs Using BlueJ

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Tutorial 03. Exercise 1: CSC111 Computer Programming I

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

CS 302: Introduction to Programming

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Section 2.2 Your First Program in Java: Printing a Line of Text

Introduction to Computer Science Unit 2. Notes

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Introduction to Computer Science and Object-Oriented Programming

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COMP 110 Project 1 Programming Project Warm-Up Exercise

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

Computational Expression

Introduction to Java Unit 1. Using BlueJ to Write Programs

AP CS Unit 3: Control Structures Notes

Introduction to Software Development (ISD) David Weston and Igor Razgon

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

3. Java - Language Constructs I

1.1 Your First Program

Java Programming Language. 0 A history

CS 200 Using Objects. Jim Williams, PhD

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

CS Week 5. Jim Williams, PhD

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Important Java terminology

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Week 3: Objects, Input and Processing

Programming Language Basics

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

MODULE 02: BASIC COMPUTATION IN JAVA

Introduction to Programming Using Java (98-388)

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Chapter 3: Operators, Expressions and Type Conversion

JAVA Ch. 4. Variables and Constants Lawrenceville Press

1 Short Answer (5 Points Each)

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Computer Components. Software{ User Programs. Operating System. Hardware

CSE 1223: Introduction to Computer Programming in Java Chapter 1 Computer Basics

Transcription:

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