Welcome to the Using Objects lab!

Similar documents
Welcome to the Using Objects lab!

Welcome to the Primitives and Expressions Lab!

AP Computer Science Unit 1. Programs

CS 200 Using Objects. Jim Williams, PhD

CS Week 5. Jim Williams, PhD

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

Elementary Programming

CS Programming I: Using Objects

Introduction to Java Unit 1. Using BlueJ to Write Programs

AP Computer Science Unit 1. Writing Programs Using BlueJ

CS Programming I: Using Objects

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

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

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

Introduction to Java Applications

AP Computer Science Unit 1. Writing Programs Using BlueJ

Assignment 2.4: Loops

Full file at

CS 302: Introduction to Programming

CS Week 2. Jim Williams, PhD

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Using Classes and Objects

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

Fall 2017 CISC124 9/16/2017

Computational Expression

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

Introduction to Java & Fundamental Data Types

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

What did we talk about last time? Examples switch statements

Java Foundations: Unit 3. Parts of a Java Program

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

CS Week 2. Jim Williams

Mr. Monroe s Guide to Mastering Java Syntax

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Software Practice 1 Basic Grammar

Introduction to Computer Science Unit 2. Notes

CS 211: Existing Classes in the Java Library

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

Java API: Math, Wrapper Classes, StringBuffer Random Data Quiz2

Getting started with Java

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

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

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

AP Computer Science A Unit 2. Exercises

Encapsulation in Java

Introduction to Computer Science Unit 2. Notes

Final Exam Practice. Partial credit will be awarded.

Lecture Set 2: Starting Java

CEN 414 Java Programming

Chapter 2: Basic Elements of Java

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

Chapter 2 Elementary Programming

CS 200 Arrays, Loops and Methods Jim Williams, PhD

Lecture Set 2: Starting Java

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

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

Building Java Programs

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

Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 2 ELEMENTARY PROGRAMMING

Name: Checked: Access the Java API at the link above. Why is it abbreviated to Java SE (what does the SE stand for)?

String. Other languages that implement strings as character arrays

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

Building Java Programs

Reading Input from Text File

Topic 4 Expressions and variables

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

Lab 6. Name: Checked:

Building Java Programs

Chapter 2: Data and Expressions

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

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

Chapter 2: Data and Expressions

CS 200 Objects and ArrayList Jim Williams, PhD

CS 180. Recitation 8 / {30, 31} / 2007

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

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

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

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

BM214E Object Oriented Programming Lecture 8

CSCI 355 Lab #2 Spring 2007

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

Building Java Programs

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

CSCI 355 LAB #2 Spring 2004

Arrays OBJECTIVES. In this chapter you will learn:

H212 Introduction to Software Systems Honors

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

Object-oriented programming in...

Java Fall 2018 Margaret Reid-Miller

Object Oriented Programming. Java-Lecture 1

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

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

Introduction to Software Development (ISD) Week 3

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

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

Introduction to Programming Using Java (98-388)

Chapter 4: Conditionals and Recursion

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

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 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. object vs instance vs class, binary, decimal, char, char literal, ASCII, escape sequence (\n, \t, \\, \"), primitive type vs. reference type, a string vs String class, reference, System.in, Integer, Double, wrapper class, Random, Scanner, static method call, non-static 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 actual number, 132 in this case, could change every time the program is run we typically draw the reference as an arrow showing the location in memory the reference refers to. Draw reference variables with the 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. A. 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. B. 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 (select, copy and paste into notepad to read): 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. C. 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?

D. String abc = " a b c "; System.out.println( abc.trim()); //If you don't know what trim() does, where can you find the description the method (or any method)? //What are 3 other String methods? E. String str = " r g h "; String.trim(); //what is wrong with this and how do you fix? //once this is fixed and the string is trimmed, what happens to the trimmed string? F. int length = " strange looking".length(); //why does this work? System.out.println( length); G. 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? H. String str = "he" + (9+2) + 'o'; String str2 = str.touppercase(); System.out.println( str2); I. 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? J. 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. H. char ch = Character.toUpperCase('a'); System.out.println( ch); I. Character ch = new Character('A'); System.out.println( ch.islowercase()); J. int num = '1'; //will this data type conversion work? System.out.println( num); K. 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? L. Random numgenerator = new Random(); System.out.println( "number: " + Random.nextInt()); //What is wrong and how do you fix? M. Random numgenerator = new 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? N. 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/ O. java.util.scanner stdin = new java.util.scanner( System.in); String str = stdin.nextline(); //what does this do, precisely? P. //to use just the class name Scanner within your program, remember to import java.util.scanner //will this work? why or why not? Scanner stdin = new Scanner( System.in); int num = stdin.nextdouble(); Q. //Exactly what is printed out? Scanner input = new Scanner("This is the input."); String str = input.next(); str = input.next(); System.out.println( str); R. Scanner input = new Scanner("one 1 2.0"); System.out.println( input.nextdouble()); //how would this code need to change so that 2.0 is print out? S. Scanner input = new Scanner("one 1 2.0");

String str = input.next(); System.out.println( input.nextdouble()); T. 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? U. Scanner input = new Scanner("1 2 3\n 4 5 6"); String str = input.nextline(); //str refers to what sequence of characters? V. Scanner input = new Scanner("1 2 3\n 4 5 6"); System.out.println( input.next()); String str = input.nextline(); System.out.println( "#" + str + "#"); //str refers to what sequence of characters? why? W. Scanner input = new Scanner("1 2 3\n 4 5 6"); System.out.println( input.nextline()); input.next(); X. //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)); Exercise C: 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 D: 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 E: 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 F: 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 G: Quiz To help you assess your own mastery of the material, see if you can answer these questions without looking back and without using a tool such as Java Visualizer. Use a tool to check your answers. 1. Draw a picture of memory as you trace the following code: Integer i = new Integer(3); Integer j = i; i = 4; int k = 5; k = j; 2. Use Random to generate an integer in the range -3 to 3, inclusive of both bounds. 3. What is printed out? String str = " This is a puzzle. \n"; str.substring( str.indexof( 'a'), 13).toUpperCase().trim(); System.out.println( str); 4. What is printed out? Scanner input = new Scanner("This\nhas\n4\nlines\n"); input.next(); System.out.println( "%"+ input.nextline() + "%"); input.nextline(); System.out.println("#"+ input.nextline() + "#"); System.out.println("*"+ input.nextline() + "*"); 5. 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(); 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