Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Similar documents
Using Classes and Objects. Chapter

Packages & Random and Math Classes

Using Classes and Objects

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Formatting Output & Enumerated Types & Wrapper Classes

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

Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

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

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Chap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,

ECE 122 Engineering Problem Solving with Java

Data Conversion & Scanner Class

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

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

Introduction to Computer Science Unit 2. Notes

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

Using Classes and Objects

Objects and Classes -- Introduction

Introduction to Computer Science Unit 2. Notes

Java Basic Introduction, Classes and Objects SEEM

AP CS Unit 3: Control Structures Notes

Data Representation Classes, and the Java API

Chapter. Let's explore some other fundamental programming concepts

Computational Expression

More Programming Constructs -- Introduction

Introduction to Programming Using Java (98-388)

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Join the course group CS230-S18! Post questions, answer them if you know the answer!

Object-Based Programming. Programming with Objects

Java Basic Introduction, Classes and Objects SEEM

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

Full file at

Using Classes and Objects

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

CS111: PROGRAMMING LANGUAGE II

Chapter 2. Elementary Programming

Chapter 3 Using Classes and Objects

1 Shyam sir JAVA Notes

CIS133J. Working with Numbers in Java

Important Java terminology

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

Introduction to Java (All the Basic Stuff)

Chapter 2: Data and Expressions

Chapter 2: Basic Elements of Java

CS 112 Introduction to Programming

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

Chapter 2: Data and Expressions

CMPT 125: Lecture 3 Data and Expressions

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

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

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Introduction to Computer Science and Object-Oriented Programming

Overview. Software Code is Everywhere. Software Crisis. Software crisis Development approaches Reusability Java packages API Sample classes:

Introduction to Computer Science I

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

Classes and Objects Part 1

Programming with Java

ECE 122. Engineering Problem Solving with Java

Practice Midterm 1 Answer Key

1.1 Your First Program

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

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

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Class Libraries and Packages

Operators and Expressions

CS110: PROGRAMMING LANGUAGE I

CS 200 Using Objects. Jim Williams, PhD

CS 335 Lecture 02 Java Programming

Lecture Set 4: More About Methods and More About Operators

PROGRAMMING FUNDAMENTALS

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

COMP-202 Unit 8: Basics of Using Objects

4. Java Project Design, Input Methods

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

What did we talk about last time? Examples switch statements

! This week: Chapter 6 all ( ) ! Formal parameter: in declaration of class. ! Actual parameter: passed in when method is called

Declaration and Memory

Chapter 3: Using Classes and Objects

Computational Expression

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Chapter 4 Classes in the Java Class Libraries

CEN 414 Java Programming

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

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Practice Midterm 1. Problem Points Score TOTAL 50

Java Primer 1: Types, Classes and Operators

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

CS 302: Introduction to Programming

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Example: Tax year 2000

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

Midterms Save the Dates!

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Peer Instruction 1. Elementary Programming

Chapter 2: Data and Expressions

CS260 Intro to Java & Android 03.Java Language Basics

Transcription:

http://cs.wellesley.edu/~cs230 Objectives of CS 230 Teach main ideas of programming Data abstraction Modularity Performance analysis Basic abstract data types (ADTs) Make you a more competent programmer designer, tester, analyzer, debugger team member Help you develop a project worth showing off Have fun in the process 1 Why ADTs? Java portability Allow you to write complex programs easier To keep mental track of complex data interaction To reuse code (yes!) To improve code performance Allows modularity of large projects Easier to understand large chunks of code Easier to collaborate with large teams To combat Sergeant Spaghetti Code Some basic ADTs: Collections Linked list Stack Queue Table Priority queue Not so basic: Tree Set Graph C source code Java source code Compiler Unix Compiler Mac OS Compiler Windows Compiler Java Compiler Byte Code Binary code Unix Mac OS Windows Java Virtual Machine (Interpreter) 1

1.5 Object-Oriented Programming 1.5 Classes define Objects Java is an object-oriented programming language An object is a fundamental entity in a Java program Objects can be used to represent real-world entities For instance, a Photo Object might represent a particular photo in a photo management program (e.g., iphoto) Each Photo Object handles the data (pixel files) processing methods (e.g., red eye reduction) and data management (e.g., copy photo) related to that photograph A class is the blueprint of an object The class uses methods to define the behaviors of the object The class that contains the main method of a Java program represents the entire program A class represents a concept, and an object represents the embodiment of that concept Multiple objects can be created from the same class 5 6 1.5 Objects and Classes 1.5 Inheritance A class (the concept) An object (the realization) One class can be used to derive another via inheritance Classes can be organized into hierarchies Bank John s Bank Balance: $5,257 Multiple objects from the same class Jason s Bank Balance: $1,245,069 Mary s Bank Balance: $16,833 Charge Savings Bank Checking 7 8 2

USING JAVA OBJECTS 3.1 Objects Objects and References The String Class Using Packages The Random Class The Math Class Comparing Floats, Strings, Objects Wrapper Classes Generally, we use the new operator to create an object name1 = new String ("Steve Jobs"); This calls the String constructor, which is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class name1 "Steve Jobs" CS230 - Reading LDC Ch. 3 9 10 3.1 Understanding the Assignment Before: Execute: num1 38 num2 96 For primitive types, assignment takes a copy of a value and stores it in a variable After: num2 = num1; num1 38 num2 38 name1 name2 name1 name2 name2 = name1; "Steve Jobs" " For object references, assignment copies the address "Steve Wozniak" "Steve Jobs" "Steve Wozniak" 3.2 StringChange.java //**************************************************************** // StringChange.java // Demonstrates the use of the String class and its methods. //**************************************************************** public class StringChange public static void main (String[] args) String phrase = "Hi, I love you not ; String m1 = phrase.concat (,..."); String m2 = m1.touppercase(); String m3 = m2.replace ( I', U'); String m4 = m3.substring (6, 10); System.out.println (m4 + " is the answer"); System.out.println ( Changed length: " + m4.length()); " Two or more references that refer to the same object are called aliases " Aliases can be useful, but dangerous: should be managed carefully " Changing an object through one reference changes it for all of its aliases, because there is really only one object (but this cannot happen on immutable Strings) 11 12 3

3.3 Class Libraries 3.3 Packages A class library is a collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment: http://docs.oracle.com/javase/6/docs/api/ Its classes are not part of the Java language per se, but we rely on them heavily Various classes we've already seen (System, Scanner, String) are part of the Java standard class library Other class libraries can be obtained through third party vendors, or you can create your own! The classes of the Java standard class library are organized into packages Some of the packages in the standard class library are Package java.lang java.applet java.awt javax.swing java.net java.util Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities 13 14 3.3 The import Declaration 3.4 Very useful: The Random Class To use a class from a package, you could use its fully qualified name java.util.scanner scan = new java.util.scanner (System.in); Or you can import the class, import java.util.scanner; and then use just the class name: Scanner scan = new Scanner (System.in); To import all classes in a package, you can use the * wildcard character import java.util.*; No need to import java.lang (it is imported automatically into all programs) The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values Useful also in testing main() programs by creating random input That's why we don t have to import the System or String classes explicitly The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported 15 16 4

3.4 RandomNumbers.java import java.util.random; // Class RandomNumbers generates random numbers in various ranges. public class RandomNumbers public static void main (String[] args) Random generator = new Random(); int num1; float num2; System.out.println ("A random integer: " + generator.nextint()); System.out.println ("From 0 to 9: " + generator.nextint(10)); System.out.println ("From -10 to 9: " + generator.nextint(20) - 10); num2 = generator.nextfloat(); System.out.println ("A random float (between 0-1): " + num2); num2 = generator.nextfloat() * 6; // 0.0 to 5.999999 num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); 3.5 Very useful: The Math Class The Math class is part of the java.lang package Math functions include absolute value: Math.abs() square root: Math.sqrt() Exponentiation: Math.pow() Math.exp() trigonometric functions: Math.sin(), Math.tan() The methods of the Math class are static methods (aka class methods) Static methods can be invoked through the class name no new object of the Math class is needed discriminant = Math.pow(b, 2) - (4 * a * c); root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); root2 = ((-1 Write * code b) that - Math.sqrt(discriminant)) computes the roots of a quadratic equation / (2 * a); 17 18 How do you program this? 4.2 Java s Conditional Operator Your change is 1 Dollar, 5 Dimes Your change is 3 Dollars, 1 Dime System.out.println ("Your change is " + count + ((count == 1)? "Dime" : "Dimes")); Its syntax is condition? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression 1-20 5

What happened to Comair Computers? 2.3 Primitive Data There are eight primitive data types in Java Four of them represent integers byte, short, int, long Two of them represent floating point numbers float, double One of them represents characters char And one of them represents logical values boolean 34 35 2.3 Numeric Primitive Data The difference between the various numeric primitive types is their size, and therefore the values they can store: Type Storage Min Value Max Value 2.5 Assignment Conversion What happens when you mix different primitive types in a calculation? Assignment conversion occurs when a value of one type is assigned to a variable of another float money; int dollars; byte short int long 8 bits 16 bits 32 bits 64 bits -128-32,768-2,147,483,648 < -9 x 10 18 127 32,767 2,147,483,647 > 9 x 10 18 The following converts the value in dollars to a float money = dollars; Note that the value or type of dollars did not change float double 32 bits 64 bits +/- 3.4 x 10 38 with 7 significant digits +/- 1.7 x 10 308 with 15 significant digits Only widening conversions can happen via assignment x dollars = money; What happens when you mix different primitive types in a calculation? 36 In this case you cast: dollars = (int)money; 37 6

2.5 Casting 2.5 Promotion Casting is the most powerful (and dangerous), technique for conversion Both widening and narrowing conversions can be accomplished by casting a value To cast, put type in parentheses in front of the value being converted For example, if total and count are integers, but we want a floating point result when multiply them, we can cast result = (float) total * count; Promotion happens automatically when operators in expressions convert their operands float total; int count; The value of count is converted to a floating point value to perform the following calculation result = total / count; 38 39 7