CS162: Introduction to Computer Science II. Primitive Types. Primitive types. Operations on primitive types. Limitations

Similar documents
CS162: Introduction to Computer Science II

Introduction to Programming Using Java (98-388)

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Chapter 4 Defining Classes I

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

CS121/IS223. Object Reference Variables. Dr Olly Gotel

ECE 122. Engineering Problem Solving with Java

CSC Java Programming, Fall Java Data Types and Control Constructs

JAVA GUI PROGRAMMING REVISION TOUR III

CHAPTER 7 OBJECTS AND CLASSES

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

VARIABLES AND TYPES CITS1001

CHAPTER 7 OBJECTS AND CLASSES

More About Objects and Methods

More About Objects and Methods. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

JAVA WRAPPER CLASSES

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

BM214E Object Oriented Programming Lecture 8

Chapter 6 Introduction to Defining Classes

Java Primer 1: Types, Classes and Operators

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Short Notes of CS201

CST141 Thinking in Objects Page 1

CS201 - Introduction to Programming Glossary By

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

Binghamton University. CS-140 Fall Data Types in Java

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Class object initialization block destructor Class object

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

CS1004: Intro to CS in Java, Spring 2005

CMSC131. Library Classes

Object-Oriented Programming Concepts

Operators and Expressions

PIC 20A Number, Autoboxing, and Unboxing

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

More About Objects and Methods

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

Variables and Primitive Types

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Programming II (CS300)

Java Fundamentals (II)

Chapter 4. Defining Classes I

ECE 122. Engineering Problem Solving with Java

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

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

CSCI 355 LAB #2 Spring 2004

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

ISA 563 : Fundamentals of Systems Programming

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Chapter 2: Using Data

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

Chapter 1 Getting Started

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

ESc101 : Fundamental of Computing

Defining Classes and Methods

Chapter 5 Names, Bindings, Type Checking, and Scopes

Defining Classes and Methods

UNIT V Sub u P b ro r g o r g a r m a s

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Introduction to C++ with content from

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

CS260 Intro to Java & Android 03.Java Language Basics

Lab5. Wooseok Kim

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

From C++ to Java. Duke CPS

Goals of this Lecture

More About Objects and Methods

Primitive Data and Objects

Lecture Set 4: More About Methods and More About Operators

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

Another IS-A Relationship

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

Chapter 2. Procedural Programming

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

This exam is open book. Each question is worth 3 points.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Java+- Language Reference Manual

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CS-211 Fall 2017 Test 1 Version A Oct. 2, Name:

Final CSE 131B Spring 2004

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

Transcription:

CS162: Introduction to Computer Science II Primitive Types Java Fundamentals 1 2 Primitive types The eight primitive types in Java Primitive types: byte, short, int, long, float, double, char, boolean int size = 42; size is a primitive variable, i.e., a variable that contains a data value of the declared type. 3 4 Limitations All primitive types have limited ranges Exceeding the range will cause inaccurate results float and double are typically approximations don't use == to compare real types Use Math.abs(x-y) <= EPSILON where EPSILON is some small number Operations on primitive types Variable holds value Assignment statements assign values E.G., int n = 10; Operations are defined as language primitives E.G., n += 5; Relational operators, etc., are defined as language primitives E.G., if (n <= 15)... 5 6 1

Result of logical operators AND OR NOT DeMorgan s Laws!(x && y) ==!x!y!(x y) ==!x &&!y 7 Short-circuit evaluation int x = 3; int y = 5; if ((x == y) && (y > 0))... if ((x < y) (y < 0))... 8 Short-circuit evaluation int x = 3; int y = 5; int z = x / y; if ((z!= 0) && ((y / z) < 5)) // OK if (((y / z) < 5) && (z!= 0)) // crash if DivideByZeroException Reference types All types that are not primitive are reference or class types String greeting = "Howdy"; greeting is a reference variable, i.e., a variable that contain a reference to (address of) the memory location of the data. // is not handled 9 10 Objects Reference Types An objectis a program entity that contains data performs certain actions The actions are called methods The actions of various objects interact to form a solution for a given problem 11 12 2

Classes A class defines the characteristics for all objects of its type A class gives a general description of what an object of the type is (instance data) what an object of the type can do (methods) Objects / Classes An object is an instance of a class. A program may have many instances (objects) of one class. All instances of the same class have The same kinds of data The same methods 13 14 An Example of a Class Three instances of the Automobile class etc. 15 16 Instantiation Invoke a constructor Automobile = new Automobile(,,,, ); Keyword new invokes a constructor for the Automobile class. Note: this example uses an overloaded constructor. The default constructor does not accept any parameters. Object variables An object variable is used to store the address of (reference to) an object When a class is instantiated, the system creates an object variable, and stores the address of the new object therein. E.G., (previous slide) is an object variable. 17 18 3

Instantiation Aliases It is possible for two variables to reference the same object. They are aliases Automobile mycar = ; A memory cell that contains the memory address of the data for mycar 19 If an object has two (or more) aliases, the object may be referenced and/or modified through any of those aliases. 20 Invoking methods in a program Instead of calling a function to do something to an object (imperative programming), tell the object to perform one of its actions (objectbased programming). Examples:.accelerate(5); int currentspeed =.getspeed(); if (.getfuellevel() < 0.1).decelerate(10); 21 Invoking methods in a program Valued methods return a single value, and should be used in an expression. Return type of method must be assignmentcompatible in the context of the call void methods do not return a value, and should be used as a single statement. Examples:.accelerate(5); int currentspeed =.getspeed(); if (.getfuellevel() < 0.1).decelerate(10); 22 Arguments and Parameters Invocation of a method must have same number of arguments as formal parameters in the declaration of the method. Arguments are associated in order with formal parameters Argument types must be assignmentcompatible with the associated formal parameter types 23 Arguments and Parameters The formal parameter in the method becomes an alias for the argument passed to it, and is treated as a local variable. The formal parameter is discarded when the method terminates. Suppose that a matchspeed method is defined as follows: public void matchspeed(automobile ) { int diff = getspeed() -.getspeed(); if(diff > 0).accelerate(diff); else.decelerate(-diff); } 24 4

Before calling matchspeed Call matchspeed.matchspeed(); is associated with is an alias of. 25 26 After executing.accelerate(diff); After matchspeed terminates.speed is changed no longer exists 27 28 Passing Arguments Pass by value For primitive type, parameter initialized to value of argument in call Pass by reference For a class type, formal parameter is initialized to the address of the object in the call An argument cannot be changed by being passed to a method! An object referenced by an argument can be changed by a method. 29 Alternate implementation of matchspeed * public void matchspeed(automobile ) { Car = new Automobile(.getModel(),.getYear(),.getFuelLevel(), getspeed(),.getmileage()); } * WRONG! 30 5

Before calling matchspeed * Call matchspeed *.matchspeed(); is associated with is a parameter, an alias of Car is a local variable with the same instance values as 31 32 After executing the statement = new Automobile( ); othe refers to a new memory location After matchspeed * terminates no longer exists Car and the object it referenced no longer exist.speed is unchanged Memory allocated by new is garbage Car 33 Car 34 Wrapper Classes Wrapper Classes Sometimes, you need to treat primitive types like objects For example, you might want to turn the integer 42 into the string 42 To do this, you need to: Create a Wrapper class for the integer Call the tostring() method for that wrapper class 36 6

Wrapper Classes Wrapper Class Example To treat primitive types as objects, you must use wrapper classes Primitive Class byte boolean char double float int long short Wrapper Class Byte Boolean Character Double Float Integer Long Short 37 int size = 42; Integer sizewrapper = new Integer(size); String sizestring = sizewrapper.tostring(); size = 42 Integer value = 42 38 Wrapper Class Functions Auto-boxing There are lots of functions you can call on a wrapper class: doublevalue() returns the value as a double intvalue() returns the value as an integer To see the complete list, check out the Java 5.0 API In Java 5.0, conversion between primitive types and the corresponding wrapper classes is automatic This is called auto-boxing Integer i = 42; // auto-boxing // same as Integer i = new Integer(42) int x = i; // auto-unboxing // same as int x = i.intvalue(); 39 40 Fancy Auto-boxing You can even make auto-boxing work inside arithmetic expressions eg. Double e = d + 1; // d is a Double Let s look at the steps that this involves: 1. Auto-unbox d into a double 2. Add 1 3. Auto-box the result into a new Double 4. Store a reference to the newly created wrapper object in e A Note About Wrappers Storing wrapper numbers is quite inefficient This is because you often only want to store the raw value but the wrapper class stores stuff in addition to the value If you care about efficiency, use the primitive type where possible 41 42 7