Introduction to Computer Science and Object-Oriented Programming

Similar documents
CIS133J. Working with Numbers in Java

Full file at

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Basics of Java Programming

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

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

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

COMP Primitive and Class Types. Yi Hong May 14, 2015

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

3. Java - Language Constructs I

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

CEN 414 Java Programming

C++ Programming: From Problem Analysis to Program Design, Third Edition

CS313D: ADVANCED PROGRAMMING LANGUAGE

LECTURE 3 C++ Basics Part 2

Number Representation & Conversion

Zheng-Liang Lu Java Programming 45 / 79

Full file at

COMP 110 Introduction to Programming. What did we discuss?

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

double float char In a method: final typename variablename = expression ;

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

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.

Chapter 2. Elementary Programming

ECE 122 Engineering Problem Solving with Java

CS Programming I: Primitives and Expressions

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2: Using Data

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

CS 302: Introduction to Programming

DATA TYPES AND EXPRESSIONS

Reserved Words and Identifiers

CIS 110: Introduction to Computer Programming

StudyHub+ 1. StudyHub: AP Java. Semester One Final Review

Computer System and programming in C

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

VARIABLES AND TYPES CITS1001

Values, Variables, Types & Arithmetic Expressions. Agenda

Arithmetic and IO. 25 August 2017

MODULE 02: BASIC COMPUTATION IN JAVA

These are reserved words of the C language. For example int, float, if, else, for, while etc.

PROGRAMMING FUNDAMENTALS

Chapter 6 Primitive types

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

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

The Math Class. Using various math class methods. Formatting the values.

Fall 2017 CISC124 9/16/2017

Program Fundamentals

Computational Expression

CSI33 Data Structures

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Objectives. In this chapter, you will:

1/11/2010 Topic 2: Introduction to Programming 1 1

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

Chapter 2: Data and Expressions

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Exercise: Using Numbers

Outline. Data and Operations. Data Types. Integral Types

HUDSONVILLE HIGH SCHOOL COURSE FRAMEWORK

Visual C# Instructor s Manual Table of Contents

Introduction to Programming Using Java (98-388)

Chapter 2: Using Data

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

AP Computer Science A. Return values

Operators. Lecture 3 COP 3014 Spring January 16, 2018

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Java Primer 1: Types, Classes and Operators

Methods CSC 121 Fall 2014 Howard Rosenthal

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

Important Java terminology

Methods CSC 121 Spring 2017 Howard Rosenthal

Operators. Java operators are classified into three categories:

Elementary Programming

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Topic 2: Introduction to Programming

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

CS112 Lecture: Primitive Types, Operators, Strings

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

Methods CSC 121 Fall 2016 Howard Rosenthal

JAVA OPERATORS GENERAL

egrapher Language Reference Manual

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

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

Declaration and Memory

Welcome to the Primitives and Expressions Lab!

Chapter 2: Using Data

Chapter 2: Basic Elements of Java

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

Data Types, Literals, Operators

Implementing Classes

UNIT- 3 Introduction to C++

Implementing Classes (P1 2006/2007)

Types and Expressions. Chapter 3

FUNDAMENTAL DATA TYPES

More Programming Constructs -- Introduction

CS 112 Introduction to Programming

Transcription:

COMP 111 Introduction to Computer Science and Object-Oriented Programming Values Judgment

Programs Manipulate Values Inputs them Stores them Calculates new values from existing ones Outputs them In Java Primitive types Types of Values References to objects reference primitive

Primitive Types Java has eight primitive types For each you need to know: Possible values Defined operations How to declare Form of constants Integer Types Type Range Memory Units byte -128... 127 1 byte short -32768... 32767 int 2,147,483,648... 2,147,483,647 2 bytes 4 bytes Use when in doubt! long -9,223,372,036,854,775,808... -9,223,372,036,854,775,807 8 bytes

Integer Operations The expected: +, -, * The unexpected: ++ and -- (later) The unexpected: / and % / is integer division results in integer (remainder discarded) % computes remainder after integer division 7 / 3 results in 2 7 % 3 results in 1 Floating Point Type Have fractional part Two types - float and double - differ in Min and max Significant digits Type Range Memory Units float a range of about ±10 38 and about 7 significant decimal digits 4 bytes double a range of about ±10 308 and about 15 significant decimal digits 8 bytes Use when in doubt!

Floating Point Operations The expected: +, -, *, / Number Gotchas Integer overflow A value not in range for the type May not be warned Example int n = 1000000; System.out.println( n*n); REMEDY: use a different type

Number Gotchas Floating point rounding errors Due to differences number systems Decimal (the one we are used to) Binary (used to represent numbers in a computer) May not be warned Example double f = 4.35; System.out.println(100 * f); ( will print 434.99999 ) REMEDY: be aware, round, use special class type Number Gotchas Conversion between types byte -> short -> int -> long -> float ->double value of a type can be converted to any type to its right No loss of precision No syntax error Example int dollars = 100; double balance = dollars;

Number Gotchas Conversion between types byte -> short -> int -> long -> float ->double value of a type cannot be converted to a type to its left Potential information loss! A syntax error! Example error! double balance = 13.75; int dollars = balance; REMEDY: cast or round Cast Programmer agrees to possible loss of info Use (type) before a value Only needed when otherwise a syntax error double balance = 13.75; int dollars = (int) balance; In this case, 13 is assigned! Fractional part is truncated

Round Programmer controls conversion Use Math.round(value) round is a method of the Math class double balance = 13.75; int dollars = Math.round(balance); In this case, 14 is assigned! Using normal mathematical rounding Constants Variable allow programs to be general Different values input, processed, output Each time run Some values are the same Each time the program is run For example Int heightininches = 12 * feet + inches;

Literal Constants Ways of writing values of a certain type Literally within program statements Form differs by type Integers Sequence of digits Preceded by + or - No commas 430 0-99833786 Floating point numbers Sequence of digits Must be a decimal point Preceded by + or - No commas 0.0.234-78439.42243 Symbolic Constants Ways of writing values of a certain type These are self-documenting Ease program maintenance Requires an initializing declaration (like a variable) Requires use of special keywords One form for all types In a method final typename variablename = expression; In a class static final typename variablename = expression;

Symbolic Constants final denotes a variable that once given a value, cannot change value static means the constant belongs to the class (not part of each instance) public is fine since value cannot be changed Style convention: make a constant all caps Example of a method constant final double QUARTER_VALUE = 0.25; Example of a class constant: public static final double QUARTER_VALUE = 0.25; You Try Create a class constant for converting Celsius to Fahrenheit Show how you would use the constant in a conversion method

Assignment Operator Form variable = expression; Replace the value of the variable on left Expression on right calculates the value Examples: ticketcount = 0; int heightininches = 12 * feet + inches; wordsize = word.length(): Expressions Ways to specify a value Directly By calculation Includes Literal constant - use literal value Variable of symbolic constant - use current value Call on a method - use the return value Combine the above with operators (+, -, /, *, %, etc.) Examples ticketcount = 0; int heightininches = 12 * feet + inches; System.out.println( word.length() );

Assignment Operator variable = expression; Notes on references to variables On the left Replace the value of the variable On the right Use the current value of the variable Beware The Curious Assignment Is legal! Is common! Is not equality!! items = items + 1; replace value use value

The Increment Operator Another way to increment by 1 items++; Is legal! No assignment operator is necessary The above is a valid statement on its own replace value use value Variations -- is the increment operator ++myvar; myvar++; is a pre-increment is a post-increment -- is the decrement operator --myvar; myvar--; is a pre-decrement is a post-decrement

The ++ Side Effect! Expressions with variables Use the value of variables But do not change them In an expressions the ++ and -- operations Apply to single variable Provide a value to use (in an expression) Change the value of the variable The changing of value is called a side effect Side Effect Example Two int variables cost 4 amount 12 About to execute amount = 3 * cost++; 1. Start evaluation of right side 3 * cost 4 amount 12 2. Get the value of cost 3 * 4 3. Increment value of cost (side effect!) cost 5 amount 12 4. Evaluate right side 12 5. Assign value to left cost 5 amount 12

Side Effect Example Two int variables cost 4 amount 12 About to execute amount = 3 * ++cost; 1. Start evaluation of right side 3 * 2. Increment value of cost (side effect!) 3. Get the value of cost 3 * 5 cost 4 amount 12 cost 5 amount 12 cost 5 amount 12 4. Evaluate right side 15 5. Assign value to left cost 5 amount 15 What is Output? int myvar; myvar = 10; System.out.println(myVar++); 10 System.out.println(myVar); 11 myvar = 10; System.out.println(++myVar); 11 System.out.println(myVar); 11

What is Output? int myvar; myvar = 10; System.out.println(myVar--); 10 System.out.println(myVar); 9 myvar = 10; System.out.println(--myVar); 9 System.out.println(myVar); 9 int myvar; What is Output? myvar = 10; int mynewvar = myvar--; System.out.println(myVar + + mynewvar); Output is 9 10

Boolean Type Type specifier: boolean Two values: true or false Literals are: true false What s returned from assertequals Type specifier: Two values: Literals are: Note char Type char `a` is not the same as `A` `a` is not the same as a (ones a char, ones a String) single characters `a` `4` `!`

Categories of Variables Instance fields Local variables Parameter variables Notes All hold values. Difference is lifetime. Lifetime of Variables Instance field as long as there is a reference to object it belongs to. Parameter and local variables come to life when method is called die after call

public class BankAccount { private double balance; Example public void deposit(double amount) { double newbalance = balance + amount; balance = newbalance; }... Example: harryschecking.deposit(500); 1. Method is called 2. amount is created and set to 500 3. newbalance is created and set to balance + amount 4. balance is set to newbalance. 5. After method call, amount and newbalance dies, balance still lives. Balance is instance field amount: parameter variable newbalance: local variable Implicit and Explicit Parameters public class BankAccount { private double balance; public void deposit(double amount) { double newbalance = this.balance + amount; this.balance = newbalance; }... harryschecking.deposit(500); The amount parameter is an explicit parameter. An instance field in a class method can be denoted as this.instancefieldname. this.balance is equivalent for this example to harryschecking.balance, This refers to the implicit object parameter (harryschecking object).

Mathematical Functions Provided by methods of the class Math Type Math.sqrt(x) Math.pow(x,y) Math.round(x) Math.ceil(x) Math.floor(x) Math.abs() Square root of x x to the y power Returns Closest integer to x Smallest integer greater than or equal to x Largest integer less than or equal to x Absolute value of x Math.max(x,y) Math.min(x,y) The larger of x and y The smaller of x and y Examples 5 to the 3 rd power can be expressed in Java as: int x = Math.pow(5, 3); // x equals 125 The square root of 25 can be expressed in Java as: double x = Math.sqrt(25); // x equals 5