Programming Process Programming in Java is an exercise in using pre-defined classes and writing new classes to fill in the gaps A procedure for determining.

Slides:



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

Types and Arithmetic Operators
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
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.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
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.
Introduction to Primitives. Overview Today we will discuss: –The eight primitive types, especially int and double –Declaring the types of variables –Operations.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
22-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
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.
Chapter 2 Data Types, Declarations, and Displays
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
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,
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Expressions, Data Conversion, and Input
Objectives You should be able to describe: Data Types
***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Integer numerical data types. The integer data types The integer data types use the binary number system as encoding method There are a number of different.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 2 Variables.
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.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 3 Numerical Data. Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
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.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
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.
Chapter 2 Variables.
Lecture 3 Java Operators.
Java Primer 1: Types, Classes and Operators
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Numerical Data Types.
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
Data Types and Expressions
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Primitive Types and Expressions
Chapter 2 Variables.
Data Types and Expressions
Data Types and Expressions
Presentation transcript:

Programming Process Programming in Java is an exercise in using pre-defined classes and writing new classes to fill in the gaps A procedure for determining the relevant objects for design and application: 1. Determine primary objects by examining the nouns of the problem statement 2. Decide upon the primary behavior of the classes corresponding to these objects 3. Define the interface 4. Introduce instance variables to maintain state 5. Implement the method bodies

Designing Classes: an overview Statement of problem – Describes the object or system to be modeled – Sketch a sample scenario illustrating the solution Find the primary objects – Key elements of the model – Collect all the nouns in the problem statement Demonstrate the desired behavior of the objects – Produce basic set of required methods – Multiple objects, work one object at a time Determine the interface – Prototype each method; arguments and return types – Write sample code to see how methods are invoked Define necessary instance variables Implement the methods

Numeric processing(page 64-70) Method implementation requires a wide variety of tools, including the ability to process numbers Java defines primitive data types including numeric types – Integer and floating point types int, short, byte, long, float, double – Not classes or objects, utilize underlying hardware Cannot receive messages; have no associated methods There are associated classes with these types, to be looked at later – Form expressions as operands of operators Static methods – Written to supplement the basic arithmetic operations – Can accept primitive data type as an argument and return value

The int data type Built-in data type – Models the behavior of integers (whole numbers) Data type provides basic arithmetic operations – + (addition), - (subtraction), * (multiplication), / (division) – Used to construct standard arithmetic expressions x + y * z – Integers can be printed by the overloaded print and println methods of the PrintStream class System.out.println(total / count);

Working with int Declarations are like reference variables int count; int number, size ; Have no methods or instance variables – An integer value is the only thing that can be associated with a variable of type int – The value may be assigned when the variable is declared int count = 0 ; – Or through an assignment statement total = cost * count; No constructors, and no new instruction

Basic arithmetic OperationOperatorExampleResult Addition Subtraction - 7 – 52 Multiplication * 7 * 535 Division / 7 / 51 Remainder % 7 % 52 Integer division results in integer results - the results are whole numbers

Constants & literals Constants – There are some values that will not change over the life of the program, they have a constant value – Constants are declared using the form static final type identifier = value – Example: static final int numStudents = 20; final : constants value is final, it will never change static : constant belongs to the class, not an instance of the class Literals – In the expression int total = 2 * cost; – The 2 is a literal because it is a literal representation of its value, (which can never be changed)

Precedence What is the result of this expression? / 8 – 1 – 2 An ambiguous expression, unless precedence rules are available to resolve ambiguities – Multiplication and division have higher precedence than addition subtraction – If more than one operator of the same precedence, the expression is evaluated from the left to the right – Parentheses can be used to clarify ambiguity or to overwrite precedence rules

Compound Assignment Operators What does the following mean? Is it nonsense? total = total * 2// doubling total count = count + 1// incrementing count These kind of operations happen so often that there are special operator shorthand for them OperationStandardShortcut Addition total = total + 2total += 2 Subtraction total = total – 2total -= 2 Multiplication total = total * 2total *= 2 Division total = total / 2total /= 2 Remainder total = total % 2total %= 2 Increment count = count + 1count++ or ++count Decrement count = count - 1count-- or --count

String objects and the + operator String concatenation is a common operation in Java Therefore the + operator is overloaded for concatenating string objects string1 + string2; is Java shorthand for string1.concat(string2)

int input To read an int value into an int variable (from keyboard or file) – Read the line from the data file into a String object, using readLine() – Convert the String value into the int value using the static parseInt() method of the predefined class Integer – Example String s = br.readLine(); int num = Integer.parseInt(s); – Or int num = Integer.parseInt(br.readLine());

Other integer types long – The int type models a range of integers from –2 billion to 2 billion – When we need a larger range of values we use the long type, which models a range of integers from –8 quintillion to 8 quintillion – long is identical to ints in terms of values, operators, and behaviors – However long literals have an L appended to them long num = L; Should all integers be long ? – ints require 32 bits of memory, longs 64 bits – Most computers today are 32 bit computers, and they cannot carry out 64 bit arithmetic as efficiently

Mixed type arithmetic int values may be assigned to long variables – No chance of information being lost However, if we want to assign a long value to an int, even if it is a legitimate int value (range), we must cast the value as an int long bigNum = ; int s =(int)bigNum;

Other integer types Represent smaller range of integers, require less memory – short to (16 bits) – Byte -128 to 127 (8 bits) Mixed arithmetic rules follow the same pattern set by long and int – If information might be lost as a result of an assignment, an explicit cast is required

Numbers of Measurement: Floating Point numbers Numbers with fractional parts; precision is always an issue Two types that model floating point behavior – float Models floating point numbers with approximately 7 digits of precision – double Models floating point numbers with approximately 15 digits of precision

Using floating point numbers Print() and println() are overloaded as with ints – Format for printing floats and doubles borrows from scientific notation X  E38 Literals can be written using the scientific notation style – The decimal point, the fraction, the exponent may all be omitted – To distinguish float from double, float literals must have a trailing f f – To distinguish double literals that look like int literals, they must have a trailing d 98d

Using floating point numbers (2) Declaring doubles and floats is similar to declaring ints double area, perimiter; static final double pi = ; double price = 1.99; Operators for addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ) works with floting point numbers – You cannot find the remainder ( % ) of floating point division, however Shortcut assignment operators ( +=, -+, *=, /= ) work – Increment does not

Reading float and double The book says there is no parseDouble() in the Double class, and no parseFloat() in the Float class – However the API shows them both, and I believe that they are now implemented – Reading a double or float value should be like reading an int – Example String s = br.readLine(); double value = Double.parseDouble(s); – Or double num = Double.parseDouble(br.readLine()); – If this doesn’t work we will use the style showed in the text double num = Double.valueOf(br.readLine()).doubleValue();

Mixed type arithmetic double to float follow the same pattern set by long and int – If information might be lost as a result of an assignment, an explicit cast is required Mixing integer types and floating point types – Integers may be assigned to floating points – Floating point to integers requires a cast – Assigning a long to a float or double may result in loss of precision

Mixed type expressions What is the result of this expression? int count = 4; int total = 25; double answer = total / count; – 6 – 6.25 Analysis – num / x; is an integer expression with an integer result – The integer result (6) of the integer expression is assigned to a double – Cast one of the int variables to get the result you want double answer = (double) total / count;

Designing a class: Collecting tolls Problem statement A county is installing a toll collecting system.Trucks pulling up to a tollbooth are required to pay a toll of $5 per axle plus $10 per half-ton of the truck’s total weight. A display in the booth shows the toll receipts and the number of truck arrivals since the last collection. Primary objects – Trucks Axle, weight – Tollbooth Receipts, display, toll, number

Designing a class: Truck Behavior – Construct a Truck object with weight and number of axles – Get the weight – Get the number of axles Interface public Truck(int weight, int numAxles); public int getWeight(); // could be double public int getAxles(); Instance Variables private int myWeight; // could be double private int myNumAxles;

Designing a class: Tollbooth Behavior – Construct a Toolbooth object – Calculate the toll – Display the data – Receipt collection Interface public Toolbooth(); public void calculateToll(Truck tr); public void receiptCollection(); public void displayData(); Instance Variables private int totalReceipts; // could be double private int numTrucks;

Designing a class: Implementation Download Tollbooth.zip demoTollbooth.zip