Introduction to Computer Science and Object-Oriented Programming

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Types and Arithmetic Operators
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Datalogi A 3: 26/9. Java Concepts chapter 4 Fundamental Data Types int (long and short) double (and float) boolean char String.
Pemrograman Dasar - Data Types1 THINGS & STUFF Identifier, Variable, Constant, Data type, operator, expression, assignment, javadoc.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
What is a variable?  A variable holds data in memory so the program may use that data, or store results.  Variables have a data type. int, boolean, char,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
1 Number Types  Every value in Java is either: 1.a reference to an object or 2.one of the eight primitive types  eight primitive types: a.four integer.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Week 5 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. int: integers, no fractional part: 1, -4, 0 double : floating-point.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
COMP Primitive and Class Types Yi Hong May 14, 2015.
Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo.
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Chapter 3 Implementing Classes
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Review by Mr. Maasz, Summary of Chapter 2: Starting Out with Java.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 2 Variables.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 2 Basic Computation
Introduction to Computer Science / Procedural – 67130
Basic Elements of C++.
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Primitive Data, Variables, Loops (Maybe)
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
Basic Elements of C++ Chapter 2.
OPERATORS (2) CSC 111.
Type Conversion, Constants, and the String Object
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
Chapter 2 Edited by JJ Shepherd
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
Fundamentals 2.
CS 200 Primitives and Expressions
Expressions and Assignment
elementary programming
CS2011 Introduction to Programming I Elementary Programming
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Classes CS 21a: Introduction to Computing I
In this class, we will cover:
Primitive Types and Expressions
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Variables.
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Introduction to Computer Science and Object-Oriented Programming Week 5

Tonight Fundamental Data Types (Ch. 4) Implementing Methods (Ch. 3) Class Types Preparing for the Test Launching Lab 2 Week 5 2

Warm Up What are the classes, objects, and methods? Client client1 = new Client("Pat",20); Client client2 = new Client(”Sal",55); System.out.println( client1.getName() + ", at your age of " + client1.getAge() + ", you E-Quotient is " + Math.round(client1.getQuotient() ); int age2 = client2.getAge(); client2.setAge(age2 + 5); Week 5 3

Values Judgment Week 5

Programs Manipulate Values Inputs them Stores them Calculates new values from existing ones Outputs them Week 5

Types of Values In Java Primitive types References to objects Week 5

Primitive Types Java has eight primitive types For each you need to know: Possible values Defined operations How to declare Form of constants Week 5

Integer Types byte short int long Type Range -128 . . . 127 Memory Units byte -128 . . . 127 1 byte short -32768 . . . 32767 2 bytes int 2,147,483,648 . . . 2,147,483,647 4 bytes long -9,223,372,036,854,775,808 . . . -9,223,372,036,854,775,807 8 bytes Use when in doubt! Week 5

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 Week 5

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 ±1038 and about 7 significant decimal digits f4 bytes double a range of about ±10308 and about 15 significant decimal digits 8 bytes Use when in doubt! Week 5

Floating Point Operations The expected: +, -, *, / Week 5

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 Week 5

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 Week 5

byte -> short -> int -> long -> float ->double 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; Week 5

byte -> short -> int -> long -> float ->double 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 Week 5

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 Week 5

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 Week 5

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; Week 5

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 Must be a decimal point No commas 0.0 .234 -78439.42243 Week 5

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; Week 5

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; Week 5

You Try Create a class constant for converting Celsius to Fahrenheit Show how you would use the constant in a conversion method Week 5

Assignment Operator Form variable = expression; Examples: 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(): Week 5

Expressions Ways to specify a value Includes Examples 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() ); Week 5 24

Precedence see Appenix E Big Java Always do subexpressions within parentheses first Week 5 25

Resolve this Java expression Show your work - including each step You Try It Resolve this Java expression Show your work - including each step 8 + 2 * (12 - 5) / 2 + 9 Week 5 26

Resolve this Java expression Show your work - including each step You Try It Resolve this Java expression Show your work - including each step 6 + 17 / 4 - 21 / 5 + 5 % 3 Week 5 27

Mathematical Functions Provided by methods of the class Math Type Returns Math.sqrt(x) Square root of x Math.pow(x,y) x to the y power Math.round(x) Closest integer to x Math.ceil(x) Smallest integer greater than or equal to x Math.floor(x) Largest integer less than or equal to x Math.abs() Absolute value of x Math.max(x,y) The larger of x and y Math.min(x,y) The smaller of x and y Week 5

Calling Static Methods The Math class methods are static methods A static method call uses the class name rather than an object name className.methodName(parameters) Classes like Math class are not used to create objects. think of as general purpose utility classes.

Examples 5 to the 3rd power can be expressed as: int x = Math.pow(5, 3); // x equals 125 The square root of 25 can be expressed as: double x = Math.sqrt(25); // x equals 5.0 Week 5

variable = expression; 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 Week 5 31

The Curious Assignment Beware items = items + 1; Is legal! Is common! Is not equality!! use value replace value Week 5

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 use value replace value Week 5

Variations -- is the increment operator -- is the decrement operator ++myVar; is a pre-increment myVar++; is a post-increment -- is the decrement operator --myVar; is a pre-decrement myVar--; is a post-decrement Week 5

The changing of value is called a side effect The ++ Side Effect! Expressions with variables Use the value of variables But do not change them But in 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 Week 5

Side Effect Example Two int variables About to execute amount = 3 * cost++; 4 cost amount Start evaluation of right side 3 *  Get the value of cost 3 * 4 Increment value of cost (side effect!) Evaluate right side 12 Assign value to left 4 cost amount 5 cost amount 5 cost amount 12

Side Effect Example Two int variables About to execute amount = 3 * ++cost; 4 cost amount Start evaluation of right side 3 *  Increment value of cost (side effect!) Get the value of cost 3 * 5 Evaluate right side 15 Assign value to left 4 cost amount 5 cost amount 5 cost amount 5 cost amount 15

What is Output? int myVar; myVar = 10; System.out.println(myVar++); 10 Week 5

What is Output? int myVar; myVar = 10; System.out.println(myVar--); 10 Week 5 39

What is Output? int myVar; myVar = 10; int myNewVar = myVar--; System.out.println(myVar + “ “ + myNewVar); Output is 9 10 Week 5

Boolean Type Type specifier: boolean Two values: true or false Literals are: true false What’s returned from assertEquals Week 5

char Type Type specifier: char Two values: single characters Literals are: `a` `4` `!` Note `a` is not the same as `A` `a` is not the same as “a” (ones a char, ones a String) Week 5

String type String in not a primitive type As a class type, it has a special status it has a form for literal values it can be initialized without a new it has a special operator The positions in a string start leftmost at 0 go to the length of the string minus 1 It has many useful methods Week 5

String methods Suppose word is a variable of type String word.length() is the number of characters in word word.toUpperCase() is the word with all characters capitalized Week 5

Categories of Variables Instance fields Local variables Parameter variables Notes All hold values. Difference is lifetime. Week 5

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 Week 5 46

Example public class BankAccount { private double balance; public void deposit(double amount) double newBalance = this.balance + amount; this.balance = newBalance; } . . . Example: harrysChecking.deposit(500); Method is called amount is created and set to 500 newBalance is created and set to balance + amount balance is set to newBalance. After method call, amount and newBalance dies, balance still lives. balance is instance field amount: parameter variable newBalance: local variable Week 5

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) Week 5

Commenting the Public Interface Use documentation comments to describe the classes and public methods Use the standard documentation notation so program called javadoc can automatically generate a set of HTML pages

Commenting the Public Interface Provide documentation comments for every class every method every parameter every return value Javadoc comment are within /** and */ Best to write the method comments first, before writing code in the body

Example /** Withdraws money from the bank account. @param amount the amount to withdraw */ public void withdraw(double amount) { // implementation filled in later }

Example /** Gets the current balance of the bank account. @return double the current balance */ public double getBalance() { // implementation filled in later }

Generated by Javadoc