CSCI 355 LAB #2 Spring 2004

Similar documents
CSCI 355 Lab #2 Spring 2007

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Introduction to Programming Using Java (98-388)

COMP 250 Winter 2011 Reading: Java background January 5, 2011

AP Computer Science Summer Work Mrs. Kaelin

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Programming with Java

JAVA MOCK TEST JAVA MOCK TEST II

Introduction to Java

1 Method Signatures and Overloading (3 minutes, 2 points)

c) And last but not least, there are javadoc comments. See Weiss.

Java and C CSE 351 Spring

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

15CS45 : OBJECT ORIENTED CONCEPTS

CS 116 Week 8 Page 1

Chapter 4 Defining Classes I

Software Practice 1 Basic Grammar

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

COP 3330 Final Exam Review

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

CS Exam 1 Review Suggestions

Points To Remember for SCJP

Java and C I. CSE 351 Spring Instructor: Ruth Anderson

CS 251 Intermediate Programming Methods and More

Computer Science II (20082) Week 1: Review and Inheritance

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

CSE 113 A. Announcements - Lab

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

13 th Windsor Regional Secondary School Computer Programming Competition

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

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

AP CS Unit 3: Control Structures Notes

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

More Java Basics. class Vector { Object[] myarray;... //insert x in the array void insert(object x) {...} Then we can use Vector to hold any objects.

CO Java SE 8: Fundamentals

Design Patterns: State, Bridge, Visitor

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CS 251 Intermediate Programming Methods and Classes

CompSci 125 Lecture 11

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

1 Shyam sir JAVA Notes

Midterm Exam CS 251, Intermediate Programming March 12, 2014

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Computer Science II (20073) Week 1: Review and Inheritance

PIC 20A The Basics of Java

Lesson 3: Accepting User Input and Using Different Methods for Output

Prelim 1, Solution. CS 2110, 13 March 2018, 7:30 PM Total Question Name Short answer

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

1 Inheritance (8 minutes, 9 points)

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

COE318 Lecture Notes Week 6 (Oct 10, 2011)

last time in cs recitations. computer commands. today s topics.

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

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

CSE351 Winter 2016, Final Examination March 16, 2016

CS-202 Introduction to Object Oriented Programming

CS 231 Data Structures and Algorithms, Fall 2016

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

CS 251 Intermediate Programming Java Basics

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

Welcome to the Using Objects lab!

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

The class Object. Lecture CS1122 Summer 2008

Java Object Oriented Design. CSC207 Fall 2014

Lecture 1: Overview & Intro to Java

2. The object-oriented paradigm

CS 211: Methods, Memory, Equality

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

Selected Java Topics

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

CS260 Intro to Java & Android 03.Java Language Basics

Program Fundamentals

About this exam review

Chapter 11: Create Your Own Objects

F I N A L E X A M I N A T I O N

CS 177 Spring 2010 Exam I

CS 113 PRACTICE FINAL

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Lecture Set 4: More About Methods and More About Operators

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

CSCI 201L Written Exam #1 Fall % of course grade

Lab5. Wooseok Kim

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

CS 1302 Chapter 9 (Review) Object & Classes

Inheritance & Polymorphism

Course Outline. Introduction to java

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Transcription:

CSCI 355 LAB #2 Spring 2004 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications that use methods and classes. Preparation: Before lab read the following chapters in Java: How to Program by Deitel and Deitel, fourth edition: Chapters 6-10 (6-11 in fifth). Bring the Java text to lab. Laboratory Assignment: The first part of the lab is to explore several Unix tools that deal with processes. The rest of the lab is a collection of small exercises that point out some novel features in Java as well as some pitfalls that some C++ programmers have in programming in Java. 1. Unix Processes: In class, we talked about the importance of the notion of process to operating systems and distributed systems. In a Unix shell window, type the ps Unix command to view the important processes you are running. To see all the processes running on your machine, type ps -ef. I suggest you pipe the output to more or less. Who else is running on your machine? Read about ps on its man page. The Unix command prstat will show all the active processes in a display that is updated automatically every few seconds. Press Control-c to exit. Read the man page on prstat. The command top displays the table of only the top 15 active processes. Read top s man page to understand the state of each process. Again, the display is updated evey few seconds and you exit by hitting Control-c. Remote login to the compute server castor using the rlogin command and try top on castor. How many CPUs are currently being used on castor? 2. Primitive Types Vs. Objects: Java has primitive types, i. e., int, boolean, byte, char, float and double which have some subtle differences from C++ (See page 183 in fourth (153 in fifth) edition of Java Text). For examples, int is always 32 bits in Java whereas in C++ it depends on the computer platform. In Java, byte is 8 bits while char is 16 bits to store international characters. The use of the primitive types are cleaner than in C++. For example, the if, and while statements require a boolean expression whereas in C++ one could use an int. Therefore, in Java you would say while(true) instead of while(1). Java makes major distinctions between primitive types and objects. Primitive types can be just declared while objects such as arrays must use new. String is an exception it is an object where you do not need to use new. In Java you use new a lot more than in C++. For example, to declare an array you must use new as follows: CSCI 355 Spring 2004 1 Lab #2

int i; int a[]; //in Java can t specify array dimension in a type expression a = new int[10]; i = 2; a[i] = 7; System.out.println( "i is " + i + " a[i] is " + a[i]); 3. Passing Parameters to a Method: Passing primitive types to a Java method (function in C++) is always done by call-by-value. There is no call-by-reference mechanism such as the & symbol in C++. Objects always pass their reference to the method (You can think of this as a pointer to the object.) Remember from last week that Java does have pointers (references) but you can t do arithmetic on references and there is no dereferencing operator (*) in Java as in C++. See page 329 fourth (293 in fifth) edition of Java text. Write a Java application that allows the user to enter up to 20 integer grades into an array from System.in. You can t use the TextReader class of last lab! (See Marvin Solomon s web pages if you need help. There is a link to them on the CS355 web pages.) Stop the loop by typing in -1. Your main method should call an Average method that returns the average of the grades. Use the DecimalFormat class (see pages 171, 381 fourth (page 142 in fifth) edition of Java Text) and the System.out.println method to print the average to 2 decimal places. Hint: To make the Average method act like a free function in C++, make it static. A static method is called by using Class-name.method-name() and not an object name. And all the calls use the same state of instance variables. Be careful with the use of static keyword. Normally we avoid its use except with main. 4. A Common Design Pattern for Java Applications: Java has no top-level or global variables or functions. A Java program is always one or more classes. A file may contain several classes but only one can be public and that class must have same name as the file with.java extension. A class without a qualifier, e.g., the keyword public, is known only to the current package. Only two things may appear before the first class construct - package and import statements. Because of this requirement that a Java program must be a set of classes, many programmers use a common design pattern for a Java application as shown below: class Lab2Ex4 // Instance objects (data members in C++) traditionally after class. // Used to communicate information across the class s methods. private int a; // Constructor Lab2Ex4 () a = 7; // Other methods CSCI 355 Spring 2004 2 Lab #2

void Print() System.out.println("a is " + a); // main method public static void main ( String args []) // Create a Lab2Ex4 object called p // which automatically calls the constructor. Lab2Ex4 p = new Lab2Ex4(); // Call other methods as needed. p.print(); The idea here is that the main method creates an object of the class which automatically calls the proper constructor then uses that object to call other methods. Notice how private instance variables are used to communciate objects across methods. To C++ programmers this structures may seem a little strange but it is very common in Java programs. You need to become familiar with it as you will use it often. Copy your Java application of Exercise 3 into a new file and rewrite it to use the above design pattern. No longer make the Average method static. 5. Exceptions: In many places, Java requires you to use exceptions such as when reading input with the method readline. Exceptions in Java are really handy and you should learn to be comfortable in using them. Copy the program in Exercise 4 to a new file and add exception handling code to catch the exception thrown by the Integer.parseInt(line) method when the user types in a non-integer like cat. Modify the code such that your program tells the user that what they typed was not legal and to retype. See Chapter 14 (Chapter 15 in fifth edition) in the Java text for information on exceptions. See especially the tables on pages 821-824 fourth (tables removed in fifth, see page 750) edition for the proper exception class to use. 6. Strings: Strings are true objects in Java. Strings are different from the string class in C++ libraries in that Java Strings are immutable, i. e., you can t modify the value of a String. (See page 429 fourth (508 in fifth) edition and Chapter 10 (Chapter 11 in fifth) in Java text.) For example, that means you can t alter the third character in a String. However, you can reassign a String object a new value such as shown below: String s1, s2; s1 = "WOW"; s2 = "BOW"; s1 = s2 + " " + s1; System.out.println(s1); CSCI 355 Spring 2004 3 Lab #2

If you want to modify a string, use the StringBuffer class (See page 559 fourth (523 in fifth) edition in Java text). The most common error with strings is when comparing them. The following is probably not what the programmer intended. if( s1 == "WOW" ) // WRONG! System.out.println(s1 + s2); This compares the two references (pointers) for equality! With String use the equals method. if( s1.equals("wow") ) System.out.println(s1 + s2); Any Java object that can be compared for equality will have an equals method. And if you write your own classes where you test for equality, you should name your method equals. Copy your program of Exercise 5 to a new file and change the program to stop the loop when the user types the word done instead of -1. 7. Using the Java Math Class Methods and the Java API: Spend some time and focus on the Math class methods on pages 249-250 fourth (219 in fifth) edition to see what is available. On page 261 fourth (230 in fifth) edition, you can learn how to use random numbers in Java. Bookmark in your browser the following URL for the Java 2, v 1.4 Application Programming Interface (API): http://java.sun.com/j2se/1.4/docs/api/index.html You should learn how to extract useful information from the API. 8. Design Your Own Class: In Java, all objects extend the class Object directly or indirectly. For example, if you define a new class Exam as follows: class Exam extends Object this is the same as leaving off extends Object. In Java s jargon, we would say Object is the superclass of Exam and Exam is the subclass of Object. By extends we mean that Exam inherits methods and data instances from Object. (See page 382 fourth (345 in fifth) edition and Chapter 9 (Chapter 10 in fifth) in Java text for more on inheritance.) One method that is part of the Object class and, therefore, inherited by all objects is tostring. See pages 384 fourth (407 in fifth) edition and 456 fourth edition. If you use an object in a System.out.print method, Java automatically calls the tostring method associated with that object. Therefore, you should override tostring when you create your own classes. CSCI 355 Spring 2004 4 Lab #2

You are to write a new Java application which allows the user to enter up to 20 student names and their exam scores. The information will be stored in an array of a user-defined class Exam. This second class will be placed in the same file after the primary class. The primary class should have a method to read in the information and a second method to print the information. Keep the Exam class as small as possible, i. e., only methods that directly operate on the two data members name and score. Your class Exam should override method tostring to allow the printing of the name and score such as the following: System.out.println(grades[i]); You will need to make your tostring method public. In contrast to the int array of Exercise 2, this exercise involves an array of objects, i. e., Exam objects. As in C++, using the new method to create an array of a class of objects only creates an array of references. You still need to use the new method repeatedly to create each element of the array. Hand in: For Exercises 3, 4, 5, 6 and 8, combine all the Java listings and outputs from runs into one handin file with a.java extension. Print using the print alias set up in Lab 1. CSCI 355 Spring 2004 5 Lab #2