Welcome to the Using Objects lab!

Similar documents
Welcome to the Using Objects lab!

Welcome to the Primitives and Expressions Lab!

CS 200 Using Objects. Jim Williams, PhD

AP Computer Science Unit 1. Programs

CS Week 5. Jim Williams, PhD

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

Midterm Exam 2 Thursday, November 15th, points (15% of final grade) Instructors: Jim Williams and Marc Renault

CS Programming I: Using Objects

Reading Input from Text File

Full file at

CS Programming I: Using Objects

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

Elementary Programming

What did we talk about last time? Examples switch statements

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Introduction to Java Applications

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

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

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

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

Introduction to Java & Fundamental Data Types

Using Java Classes Fall 2018 Margaret Reid-Miller

AP Computer Science A

Computational Expression

"Hello" " This " + "is String " + "concatenation"

Assignment 2.4: Loops

Chapter 2: Basic Elements of Java

Object Oriented Programming. Java-Lecture 1

Getting started with Java

A variable is a name for a location in memory A variable must be declared

Chapter 2 ELEMENTARY PROGRAMMING

Program Fundamentals

AP Computer Science Unit 1. Writing Programs Using BlueJ

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Introduction to Java Unit 1. Using BlueJ to Write Programs

Strings, Strings and characters, String class methods. JAVA Standard Edition

Lecture Set 2: Starting Java

H212 Introduction to Software Systems Honors

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Lecture Set 2: Starting Java

Chapter 2: Data and Expressions

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

Chapter 2 Elementary Programming

Basic Computation. Chapter 2

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

Chapter 2: Data and Expressions

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Java Foundations: Unit 3. Parts of a Java Program

Mr. Monroe s Guide to Mastering Java Syntax

String. Other languages that implement strings as character arrays

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

Fall 2017 CISC124 9/16/2017

Basic Computation. Chapter 2

Programming with Java

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

First Java Program - Output to the Screen

CEN 414 Java Programming

CSCI 355 LAB #2 Spring 2004

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

Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

Software Practice 1 Basic Grammar

CS Week 2. Jim Williams

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

CSCI 355 Lab #2 Spring 2007

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

AP Computer Science A Unit 2. Exercises

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

Fundamentals of Programming Data Types & Methods

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Building Java Programs

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

CS 302: Introduction to Programming

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

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

Chapter 2 Primitive Data Types and Operations. Objectives

Introduction to Java Applications; Input/Output and Operators

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

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

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

CS Week 2. Jim Williams, PhD

AP Computer Science Unit 1. Writing Programs Using BlueJ

Chapter 2: Using Data

Final Exam Practice. Partial credit will be awarded.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Eng. Mohammed Abdualal

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

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

Chapter 02: Using Data

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Java characters Lecture 8

We now start exploring some key elements of the Java programming language and ways of performing I/O

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

Java Programming Language. 0 A history

Lec 3. Compilers, Debugging, Hello World, and Variables

Supplementary Test 1

Question: Total Points: Score:

CSE1710. Big Picture. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

Transcription:

Welcome to the Using Objects lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 3 terms. 2. Describe reference variables and compare with primitive data type variables. 3. Draw memory model diagrams contrasting primitive with reference types. Include int, Integer, String, Scanner, etc. 4. Describe char and Character. 5. Describe how calling an instance (non-static) method is different from calling a class (static) method. 6. Use API to lookup Scanner, String, Random, Integer, and Double methods. 7. Trace multiple instance methods calls for Scanner and String. 8. Trace multiple method calls. 9. Describe String concatenation and immutability. Exercise A: Terms Discuss these terms with your lab partner and write out (on paper or notepad) your understanding. If this takes more than about 10 minutes, move on to other lab exercises and come back to this later. As you are doing the lab, consider whether your understanding is confirmed or clarified. Review your understanding with a TA. object vs instance vs class, binary, decimal, char, char literal, ASCII, escape sequence (\n, \t, \\, \"), primitive type vs. reference type, reference, int vs Integer, double vs Double, wrapper class, Random, Scanner, static (class) method call, non-static (instance) method call, API, immutable, package, import, debugging Exercise B: Trace and Explain Week 2 we saw primitive data type variables simply hold a value in memory. Declaring a variable m is giving that name to a location in memory. int m = 9; Can be drawn as: m 9 Or m 9 Week 3 we saw that reference variables contain the reference (location or address) of where to find the value in memory. Technically, references contain the information needed for the JVM to find the value. For simplicity, we can think of a reference as an address.

Integer p = new Integer(7); The value (e.g., 132) in the memory location we have named p is the reference (address) to go to find the actual value 7, in this case. Since p is a reference variable (declared as Integer class) we know the value 132 is another location in memory. Going to that location (location 132) we then find the value 7. When we follow the reference we "dereference" the variable. Since the location, 132 in this case, could be a different place in memory every time the program is run we typically draw the reference as an arrow pointing to referred to location. Draw the contents of reference variables with an arrow. Sometimes references are referred to as pointers. With your partner, trace and explain each of the following (also found in traceexplain.txt ). Check your understanding using Java Visualizer. 1. double num1 = 9.0; Double num2 = 9.0; When tracing these, draw a picture of each. Check your picture by viewing in Java Visualizer. In Java Visualizer, remember to check: options > Show String/Integer/etc objects, not just values. When explaining, describe where the compiler will do an implicit type conversion. 2. int numa; numa = 3; Integer numb; numb = new Integer(3); //Can you draw a diagram and then describe in detail what is happening here? //Sample Answer: numa is a primitive variable declared with data type int. The statement numa = 3; puts the int literal 3 into the variable numa. The statement Integer numb; declares numb to be a reference variable intended to hold a reference to an instance of Integer. The expression new Integer(3) instantiates/creates an instance/object of class Integer with the initial value of 3. The result of the expression is a reference/address/pointer to the location in memory of the newly created instance. The assignment statement puts the reference into the variable numb. 3. String str; str = "Your Name"; //Is String a class or primitive data type? //Are the characters "Your Name" stored in the memory location referred to by str? //What is stored in str? 4. String abc = " a b c ";

System.out.println( abc.trim().charat(0)); //Look in the String class API, find the trim() description and 3 more methods. 5. String str = "HELLO"; str.tolowercase(); System.out.println( str); //Is the string printed out in all uppercase letters? Why/Why not? What does immutable mean? 6. String str = "Read " + " Java carefully."; System.out.println( str.substring(10,15)); //What exactly will be print out? //What is the meaning of each of the parameters to the substring method? 7. char ch = Character.toUpperCase('a'); System.out.println( ch); 8. Random numgenerator = new Random(); //remember to import java.util.random int num1 = numgenerator.nextint(10); int num2 = numgenerator.nextint(10); int num3 = numgenerator.nextint(10); //Does the value returned from nextint method call change each time? //What are the possible values returned? //If you re-run this same code are the results the same? 9. Random rand = new Random(); rand.setseed( 365); int num1 = rand.nextint(6); int num2 = rand.nextint(6); int num3 = rand.nextint(6); //How does setting a seed affect the results? //What would you change to get the values 1-6, such as for simulating a dice roll? To learn more about Scanner see https://cs200-www.cs.wisc.edu/wp/resources/learn-to-use-scanner/ 10. //Exactly what is printed out? Remember to import java.util.scanner Scanner input = new Scanner("This is the input."); String str = input.next(); str = input.next(); System.out.println( str); 11. Scanner input = new Scanner("one 1 2.0"); System.out.println( input.nextdouble()); //Change this code to read each token using the appropriate method and print each out. 12. Scanner input = new Scanner("1 2 3\n 4 5 6"); System.out.println( input.nextint());

System.out.println( input.nextint()); System.out.println( input.next()); String str = input.nextline(); System.out.println( "#" + str + "#"); System.out.println( input.nextint()); //str refers to what sequence of characters? why? 13. //What is printed out? public class M { public static int methoda(int a) { return a + 2; public static void main(string []args) { double c = 5.2; System.out.println( methodb( c)); public static int methodb(double b) { return methoda((int) (b + 1.0)); 14. //If you have difficulty, review Precedence, Associativity and Order of Evaluation tutorial. int a = 40; System.out.println((a /= 10) + "" + (a /= 2)); //for questions on /=, see "compound operators" in zybooks Exercise C: String Documentation Review the following screenshot of String API and answer the following questions. 1. Which modifier indicates that this is a class method that you call with the class name? 2. What is the data type returned by the method call and that we should use to declare the variable? result = String.valueOf( true);

3. How can you tell that you must have a reference to an instance to call the method? 4. Is this touppercase call correct? String result = String.toUpperCase(); 5. Will this print out HELLO? String shout = "hello"; shout = shout.touppercase(); System.out.println( shout); 6. Write a statement using the trim() method to remove the leading and trailing whitespace from the string " happy ". 7. There is also a tolowercase() method in the String class. Will the following print out the lowercase letters? String str = "IS THIS LOWER CASE?"; str.tolowercase(); System.out.println( str); Exercise D: Matching (Scanner) Match each of these explanations with the corresponding code, term or exception. A. a sequence of non-whitespace characters B. space, tab and newline characters C. Reads the next token and returns the first character of the token and saves the character in a variable. D. Read the next token and return as an int value. Skip any leading whitespace and stop at whitespace following token. Will throw an InputMismatchException if the token is not an integer. E. Assign the reference to a new instance of Scanner to the scnr variable. F. Declare reference variable named scnr of class Scanner. G. Declares a variable. Reads and returns the next token as a double saving value in the variable. Will throw an InputMismatchException if the token is not a floating point number. H. Read all characters (including whitespace) up to and including the next newline character. Return a reference to a string containing all the characters except for the newline. Save the string reference in a variable. I. A statement to read in the next token as a String and save the reference into the name variable. J. Closes the instance of the Scanner, typically called when the programmer is done reading from it. K. In Scanner methods, if there is not any more input then this exception is thrown. L. In Scanner methods, if the scanner has already been closed then this exception is thrown. M. In Scanner methods, if the token read doesn't match the expected data type then this exception is thrown. 1. whitespace 2. token 3. Scanner scnr; 4. scnr = new Scanner(System.in); 5. scnr.nextint()

6. name = scnr.next(); 7. char choice = scnr.next().charat(0); 8. double price = scnr.nextdouble(); 9. String line = scnr.nextline(); 10. scnr.close(); 11. InputMismatchException 12. NoSuchElementException 13. IllegalStateException Exercise E: Binary, Hexadecimal and Unicode If necessary, review zybooks section 3.1 and 3.2 1. What is binary 0111 in hexadecimal and decimal? 2. What is hexadecimal 0045 in binary and decimal and what character is it using the unicode table? 3. What is 75 (decimal) in binary and hexadecimal? Note: If necessary on an exam, a unicode table will be provided, it does not need to be memorized. Exercise TA: Demonstration and Discussion This exercise is utilized to determine 3 points of the lab grade. We suggest reviewing these before you discuss these with your TA. 1. References & Wrapper classes: a. Draw pictures and explain what is happening in memory: float salary = 1.5F; Float salary2 = 1.5F; b. Draw pictures and explain what is happening in memory: Integer numa = new Integer(3); int numb = numa; Integer numc = 3; c. Which wrapper class would you look in for a method to see if a single character is a digit? 2. Method calls a. What is printed out? String str = " This is a puzzle. \n"; str.substring( str.indexof( 'a'), 13); System.out.println( str); b. What is printed out? public class Color { public static void red() {

System.out.print("RED "); public static void blue() { red(); System.out.print("BLUE "); public static void main(string []args) { blue(); green(); red(); public static void green() { blue(); System.out.print("GREEN "); blue(); c. In the following code: Random rand = new Random(); rand.setseed( 23); int num1 = rand.nextint(10) + 2; System.out.println( num1); i. Will the number printed out be between 2 and 12 inclusive of both? ii. If this code is run 10 times, will it print out the same number each time or different numbers each time? 3. Scanner a. What will be printed out? Scanner input = new Scanner("This\nhas\n4\nlines\n"); input.next(); System.out.println( "%"+ input.nextline() + "%"); input.nextline(); System.out.println( input.nextint()); System.out.println("#"+ input.nextline() + "#"); System.out.println("*"+ input.nextline() + "*"); Exercise F: Fix Order and Indenting of Lines Using the command-line tools, reorder lines to fix Scanner2.java Output:

Job:43125 name: Sara fee: 39.95 Exercise G: Body Mass Index Body Mass Index (BMI) is used to estimate the amount of muscle, fat and bone in an individual. The BMI is defined as the body mass (kilograms) divided by the square of the body height (meters). Extend BMI.java to calculate a BMI based on height in meters and weight in kilograms. Height (meters): 1.6 Weight (kilograms): 65 BMI: 25.390624999999996 Adapt to take input in inches and pounds. Find the appropriate formulas and constants on the web. There are calculators on the web that you may use to compare results. Express any constant values, such as meters in an inch, as a constant: final double METERS_IN_INCH = 0.0254; Height (inches): 63 1.6001999999999998(meters) Weight (pounds): 143 64.86370891143507(kilograms) BMI: 25.331053134448013 Adapt further to take input in feet, inches and pounds. Height (feet): 5 Height (inches): 3 1.6001999999999998(meters) Weight (pounds): 143 64.86370891143507(kilograms) BMI: 25.331053134448013 Exercise H: Hello World Run this HelloWorld.java program and see if you can figure out how it works. 1. What does the seed for Random do? 2. What does += mean for Strings? 3. What does the following do? (char)(rand.nextint(27) + '`') 4. Why was '`' chosen? 5. Why was 27 chosen? 6. Why were those specific seeds chosen? Exercise I: Write Program Write a program to use a Scanner to read the string, reading each number, " ControlType: 1\nFIRE @ 541.0 387.0\nHERO @ 397.0 287.0\nBUILDING @ 522.0 174.0" and print out as: building (522.0, 174.0)

hero (397.0, 287.0) fire (541.0, 387.0) using control type: 1 Exercise J: More Trace and Explain With your partner, trace and explain each of the following (also found in traceexplain2.txt ). Check your understanding using Java Visualizer. 15. String str = " r g h "; String.trim(); //Will this compile? str.trim(); //Will this remove leading and trailing whitespace from the string? //Is the trimmed string changed in place or returned? 16. int length = " strange looking".length(); //why does this work? System.out.println( length); 17. String str2 = "Careful reading will save " + " lots of time debugging."; System.out.println( str2.substring( str2.indexof('e') + 1, str2.indexof('o')).trim()); //What will be print out? Describe in your own words what the substring, indexof and trim methods do. 18. String str = "he" + (9+2) + 'o'; String str2 = str.touppercase(); System.out.println( str2); 19. int num = '1'; //will this data type conversion work? System.out.println( num); 20. Character ch = new Character('A'); System.out.println( ch.islowercase()); 21. Random numgenerator = new Random(); System.out.println( "number: " + Random.nextInt()); //What is wrong and how do you fix? 22. Random rand = new Random(); //remember to import java.util.random int num1 = rand.nextint(); int num2 = rand.nextint(); int num3 = rand.nextint(); //Will the nextint() method return the same value each time? //What is the range of possible values returned? //Each time you run this will the values returned be the same or different?

23. java.util.scanner stdin = new java.util.scanner( System.in); String str = stdin.nextline(); //what does this do, precisely? 24. //Will this compile? Scanner stdin = new Scanner( System.in); // remember to import java.util.scanner int num = stdin.nextdouble(); 25. Scanner input = new Scanner("one 1 2.0"); String str = input.next(); System.out.println( input.nextdouble()); 26. Scanner input = new Scanner("1 2 3\n 4 5 6"); String str = input.next(); System.out.println( input.next()); //str refers to what sequence of characters? 27. Scanner input = new Scanner("1 2 3\n 4 5 6"); String str = input.nextline(); System.out.println( input.nextint()); //str refers to what sequence of characters? 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 Marc Renault, Yien Xu Lab 2018 Jim Williams