CSCI 355 Lab #2 Spring 2007

Similar documents
CSCI 355 LAB #2 Spring 2004

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

Introduction to Programming Using Java (98-388)

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

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

Lecture 7: Classes and Objects CS2301

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

15CS45 : OBJECT ORIENTED CONCEPTS

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

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson


AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Introduction to Java

AP Computer Science Summer Work Mrs. Kaelin

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

Object Oriented Programming. Java-Lecture 1

COP 3330 Final Exam Review

CS Exam 1 Review Suggestions

Chapter 4 Defining Classes I

AP CS Unit 3: Control Structures Notes

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

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

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

CO Java SE 8: Fundamentals

Software Practice 1 Basic Grammar

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

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

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

Full file at

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

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

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

CS 251 Intermediate Programming Methods and More

Java Object Oriented Design. CSC207 Fall 2014

Points To Remember for SCJP

CS 116 Week 8 Page 1

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

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

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

Introduction to Classes and Objects

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

WA1278 Introduction to Java Using Eclipse

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

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

1 Shyam sir JAVA Notes

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

Course Outline. Introduction to java

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

CompuScholar, Inc. 9th - 12th grades

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

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

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

CompSci 125 Lecture 11

13 th Windsor Regional Secondary School Computer Programming Competition

PIC 20A The Basics of Java

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

CS 211: Methods, Memory, Equality

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Java and C CSE 351 Spring

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

CS260 Intro to Java & Android 03.Java Language Basics

Design Patterns: State, Bridge, Visitor

Computational Expression

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Assignment 2.4: Loops

TeenCoder : Java Programming (ISBN )

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

H212 Introduction to Software Systems Honors

Introduction to Java Applications

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

CS 251 Intermediate Programming Methods and Classes

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

CSE 113 A. Announcements - Lab

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

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

Final CSE 131B Spring 2004

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

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

The class Object. Lecture CS1122 Summer 2008

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

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

CS-202 Introduction to Object Oriented Programming

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Chapter 6 Introduction to Defining Classes

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Chapter 11: Create Your Own Objects

Exam Duration: 2hrs and 30min Software Design

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

1 Inheritance (8 minutes, 9 points)

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics

Transcription:

CSCI 355 Lab #2 Spring 2007 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. Reference: Java: How to Program by Deitel and Deitel, sixth edition. Preparation: Before lab read the following chapters in Deitel s Java text: Chapters 6 Methods; 7 Arrays; 8 Classes; 9 Inheritance; 10 Polymorphism; and 29 Strings. 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 Linux 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 -Af. I suggest you pipe the output to more or less. Try piping ps -Af to grep logon-name. Who else is running on your machine? Read about ps on its man page. Make your Unix shell window as tall as possible and run the command top. top displays a table of the top active processes ranked by CPU activity. Read top s man page to understand the state of each process. The table is updated evey few seconds and you exit by pressing Control-c. Remote login to the compute server linuxcomp3 using the rlogin command and try top on linuxcomp3. How many CPUs are currently being used on linuxcomp3? 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 Appendix D of Deitel s Java Text for list of primitive types). 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) CSCI 355 Spring 2007 1 Lab #2

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: 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 indirect operator (*) in Java as in C++. See page 306 in Deitel s Java text for discussion on passing arguments. Write a Java application that allows the user to enter up to 20 integer grades into an array from System.in. (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 to print the average to 2 decimal places. (For another way, see the new Java 1.5 feature System.out.printf() that is similar to C s printf.) 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 Lab2Part4 // Instance objects (data members in C++) traditionally after class. // Used to communicate information across the class s methods. private int a; // Constructor CSCI 355 Spring 2007 2 Lab #2

Lab2Part4 () a = 7; // Other methods void Print() System.out.println("a is " + a); // main method public static void main ( String args []) // Create a Lab2Part4 object called p // which automatically calls the constructor. Lab2Part4 p = new Lab2Part4(); // 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 the 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. Use the Scanner class method nextline(). Modify the code such that your program tells the user that what they typed was not legal and to retype. See Chapter 13 of the Deitel s Java text for information on exceptions. See especially the table on page 649 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 Chapter 29 of Deitel s 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; CSCI 355 Spring 2007 3 Lab #2

s1 = "WOW"; s2 = "BOW"; s1 = s2 + " " + s1; System.out.println(s1); If you want to modify a string, use the StringBuffer class (See page 1364 of Deitel s Java text). The most common error with strings is when comparing them. The following is probably not what the programmer intended. String s1; if( s1 == "WOW" ) // WRONG! System.out.println(s1 + s2); This compares the two references (pointers) for equality! With String use the equals method. String s1; 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 page 235 to see what is available. On page 249 in Deitel s Java text, you can learn how to use randum numbers in Java. Bookmark in your browser the following URL for the Java 2, v 1.5 Application Programming Interface (API): http://java.sun.com/j2se/1.5/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 CSCI 355 Spring 2007 4 Lab #2

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 421 and Chapter 9 of Deitel s Java text for more on inheritance.) One method that is part of the Object class and, therefore, inherited by all objects is tostring. (See page 424). 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. 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 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 with 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 a2ps command. CSCI 355 Spring 2007 5 Lab #2