University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Mathematical Operations, Static Methods Lecture 9, Thu Feb 2.

Slides:



Advertisements
Similar presentations
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Advertisements

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Interfaces, Polymorphism II Lecture 21, Thu Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Data Types, Assignment, Casting, Constants Lecture.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Advanced Class Design Lecture 19, Thu Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design Lecture 11, Fri Jan
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Mathematical Operators, Static Methods Lecture 14,
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Mathematical Operators: working with floating point numbers and more operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Static Methods, Conditionals Lecture 15, Mon Feb 8.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
CPSC 111 Introduction to Computation October 15 th, 2009 Based on slides by Eiselt, Carter, Murphy, Pottinger.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Pemrograman Dasar - Data Types1 THINGS & STUFF Identifier, Variable, Constant, Data type, operator, expression, assignment, javadoc.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Interfaces, Polymorphism Lecture 29, Fri Mar
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design Lecture 12, Mon Feb
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design II Lecture 31, Wed Mar
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design Lecture 13, Wed Feb
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design III, Parameter/Scope Review Lecture.
Expressions, Data Conversion, and Input
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Classes CS 21a: Introduction to Computing I First Semester,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Week 5 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Mathematical Calculations in Java Mrs. G. Chapman.
Mathematical Calculations in Java Mrs. C. Furman.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
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.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Class Design II Lecture 7, Thu Jan
Expressions.
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Type Conversion, Constants, and the String Object
Type Conversion, Constants, and the String Object
Lecture 3 Expressions Richard Gesick.
Arithmetic Expressions & Data Conversions
Chapter 4 Writing Classes.
CS 200 Primitives and Expressions
Data Types and Expressions
Java Programming Language
Classes CS 21a: Introduction to Computing I
Data Types and Expressions
Arithmetic Expressions & Data Conversions
Data Types and Expressions
Presentation transcript:

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Mathematical Operations, Static Methods Lecture 9, Thu Feb based on slides by Kurt Eiselt

Reading n Re-read Chapter (today) n Next week: Chapter 6 all ( )

News n Weekly Questions due today n Midterm reminder: Tue Feb 7, 18: :00 n Geography 100 & 200 n Discovery Forum – here, right after class n Computer Science And Medicine: Where Technology Meets Biology n you can see demos of what I do when I’m not teaching!

Recap: Commenting Code n Conventions n explain what classes and methods do n plus anywhere that you've done something nonobvious n often better to say why than what n not useful int wishes = 3; // set wishes to 3 n useful int wishes = 3; // follow fairy tale convention

Recap: javadoc Comments n Specific format for method and class header comments n running javadoc program will automatically generate HTML documentation n Rules n /** to start, first sentence used for method summary tag for parameter name and explanation tag for return value explanation n n */ to end n Running % javadoc Die.java % javadoc *.java

Recap: Cleanup Pass n Would we hand in our code as it stands? n good use of whitespace? n well commented? n every class, method, parameter, return value n clear, descriptive variable naming conventions? n constants vs. variables or magic numbers? n fields initialized? n good structure? n ideal: do as you go n commenting first is a great idea! n acceptable: clean up before declaring victory

Finishing Point and PointTest

Formal vs. Actual Parameters n formal parameter: in declaration of class n actual parameter: passed in when method is called n variable names may or may not match n if parameter is primitive type n call by value: value of actual parameter copied into formal parameter when method is called n changes made to formal parameter inside method body will not be reflected in actual parameter value outside of method n if parameter is object: covered later

Scope n Fields of class are have class scope: accessible to any class member n in Die and Point class implementation, fields accessed by all class methods n Parameters of method and any variables declared within body of method have local scope: accessible only to that method n not to any other part of your code n In general, scope of a variable is block of code within which it is declared n block of code is defined by braces { }

Objectives n Understand how to use mathematical shorthand operators n Understand when values will be implicitly converted n Understand how to use static variables and methods

Increment and Decrement n Often want to increment or decrement by 1 n obvious way to increment n count = count + 1; n assignment statement breakdown n retrieve value stored with variable count n add 1 to that value n store new sum back into same variable count n obvious way to decrement n count = count - 1;

Shorthand Operators n Java shorthand n count++; // same as count = count + 1; n count--; // same as count = count - 1; n note no whitespace between variable name and operator n Similar shorthand for assignment n tigers += 5; // like tigers=tigers+5; n lions -= 3; // like lions=lions-3; n bunnies *= 2; // like bunnies=bunnies*2; n dinos /= 100; // like dinos=dinos/100;

Shorthand Assignment Operators n what value ends up assigned to total ? int total = 5; int current = 4; total *= current + 3; n remember that Java evaluates right before left of = n first right side is evaluated: result is 7 n total *= 7; n total = total * 7; n total = 5 * 7; n total = 35;

Data Conversion n Math in your head n 1/3 same as …. n Math in Java: it depends! int a = 1 / 3; double b = 1 / 3; int c = 1.0 / 3.0; double d = 1.0 / 3.0;

Data Conversion n Math in your head n 1/3 same as …. n Math in Java: it depends! int a = 1 / 3; // a is 0 double b = 1 / 3; // b is 0.0 int c = 1.0 / 3.0; // Java’s not happy double d = 1.0 / 3.0; // d is

Data Conversion n Consider each case int a = 1 / 3; // a is 0 n Literals 1 and 3 are integers n Arithmetic with integers results in integer n fractional part truncated (discarded) n So 0 is value assigned to a

Data Conversion n Consider each case double b = 1 / 3; // b is 0.0 n Literals 1 and 3 are integers n Arithmetic with integers results in integer n fractional part truncated (discarded) n So 0 is result on right side n Left side expects double n integer 0 is converted to floating point 0.0 n So 0.0 is value assigned to b

Data Conversion n Consider each case int c = 1.0 / 3.0; // Java’s not happy n Literals 1.0 and 3.0 are doubles n Arithmetic with doubles results in double n results is n Left side expects int not double n fractional part would have to be truncated n Java wants to make sure you know you’d lose fractional information n could be explicit with cast int c = (int) (1.0 / 3.0); //cast placates Java

Data Conversion n Consider each case double d = 1.0 / 3.0; // d is n Literals 1.0 and 3.0 are doubles n Arithmetic with doubles results in double n results is n Right side double can hold value n well... just approximation of repeating value! n finite number of bits to hold infinite sequence n roundoff errors can be major problem n CPSC 302, 303 cover in more detail

Data Conversion n Casting: explicit data conversion n Widening: conversion from one data type to another type with equal or greater amount of space to store value n widening conversions safer because don’t lose information (except for roundoff) n Narrowing: conversion from one type to another type with less space to store value n important information may be lost n avoid narrowing conversions!

Data Conversion n Which of these is n not a conversion? n widening conversion? n narrowing conversion? int a = 1 / 3; // a is 0 double b = 1 / 3; // b is 0.0 int c = 1.0 / 3.0; // Java’s not happy double d = 1.0 / 3.0; // d is

Assignment Conversion n Assignment conversion: value of one type assigned to variable of other type, so must be converted to new type n implicit, happens automatically n Java allows widening but not narrowing through assignment

Promotion n Second kind of data conversion n happens when expression contains mixed data types n example: int hours_worked = 40; double pay_rate = 5.25; double total_pay = hours_worked * pay_rate; n To perform multiplication, Java promotes value assigned to hours_worked to floating point value n produces floating point result n implicit, widening

Data Conversion n No such thing as automatic demoting n would be narrowing! int hours_worked = 40; double pay_rate = 5.25; int total_pay = hours_worked * pay_rate; // error n can use casting to explicitly narrow int total_pay = hours_worked * (int) pay_rate;

Modulus Operator n computes remainder when second operand divided into first n sign of result is sign of numerator n if both operands integer, returns integer n if both operands floating point, returns floating point n operator is % int num1 = 8, num2 = 13; double num3 = 3.7; System.out.println( num1 % 3 ); System.out.println( num2 % -13 ); System.out.println( num3 % 3.2 ); System.out.println( -num3 % 3 );

Questions?

Static Variables public class Giraffe { private double neckLength; public Giraffe(double neckLength) { this.necklength = necklength; } public void sayHowTall() { System.out.println(“Neck is “ + neckLength); }

Static Variables public class Giraffe { private double neckLength; public Giraffe(double neckLength) { this.necklength = necklength; } public void sayHowTall() { System.out.println(“Neck is “ + neckLength); } n how would we keep track of how many giraffes we’ve made? n need a way to declare variable that "belongs" to class definition itself n as opposed to variable included with every instance (object) of the class

Static Variables public class Giraffe { private static int numGiraffes; private double neckLength; public Giraffe(double neckLength) { this.necklength = necklength; } public void sayHowTall() { System.out.println(“Neck is “ + neckLength); } n static variable: variable shared among all instances of class n aka class variable n use "static" as modifier in variable declaration

Static Variables public class Giraffe { private static int numGiraffes; private double neckLength; public Giraffe(double neckLength) { this.necklength = necklength; numGiraffes++; } public void sayHowTall() { System.out.println(“Neck is “ + neckLength); } n updating static variable is straightforward n increment in constructor

Static Variables n Static variable shared among all instances of class n Only one copy of static variable for all objects of class n Thus changing value of static variable in one object changes it for all others objects too! n Memory space for a static variable established first time containing class is referenced in program

Static Methods n Static method "belongs" to the class itself n not to objects that are instances of class n aka class method n Do not have to instantiate object of class in order to invoke static method of that class n Can use class name instead of object name to invoke static method

Static Methods public class Giraffe { private static int numGiraffes; private double neckLength; public Giraffe(double neckLength) { this.necklength = necklength; numGiraffes++; } public void sayHowTall() { System.out.println("Neck is " + neckLength); } public static int getGiraffeCount() { return numGiraffes; } n static method example

Calling Static Method Example public class UseGiraffes { public static void main (String[] args) { System.out.println("Total Giraffes: " + Giraffe.getGiraffeCount()); Giraffe fred = new Giraffe(200); Giraffe bobby = new Giraffe(220); Giraffe ethel = new Giraffe(190); Giraffe hortense = new Giraffe(250); System.out.println("Total Giraffes: " + Giraffe.getGiraffeCount()); } n Note that Giraffe is class name, not object name! n at first line haven’t created any Giraffe objects yet

Static Methods n Static methods do not operate in context of particular object n cannot reference instance variables because they exist only in an instance of a class n compiler will give error if static method attempts to use nonstatic variable n Static method can reference static variables n because static variables exist independent of specific objects n Therefore, the main method can access only static or local variables.

Static Methods public class UseGiraffes { public static void main (String[] args) { System.out.println("Total Giraffes: " + Giraffe.getGiraffeCount()); Giraffe fred = new Giraffe(200); Giraffe bobby = new Giraffe(220); Giraffe ethel = new Giraffe(190); Giraffe hortense = new Giraffe(250); System.out.println("Total Giraffes: " + Giraffe.getGiraffeCount()); } n Now you know what all these words mean n main method can access only static or local variables

Static Methods in java.Math n Java provides you with many pre-existing static methods n Package java.lang.Math is part of basic Java environment n you can use static methods provided by Math class n examples: > Math.sqrt(36) 6.0 > Math.sin(90) > Math.sin(Math.toRadians(90)) 1.0 > Math.max(54,70) 70 > Math.round( ) 3 > Math.random() > Math.random() > Math.pow(2,3) 8.0 > Math.pow(3,2) 9.0 > Math.log(1000) > Math.log10(1000) 3.0