Types and Expressions Chapter 3. Chapter Contents 3.1 Introductory Example: Einstein's Equation 3.2 Primitive Types and Reference Types 3.3 Numeric Types.

Slides:



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

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.
Chapter 2: Using Data.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Some Java Fundamentals Chapter 2. Chapter Contents Chapter Objectives 2.1 Example: A Payroll Program 2.2 Types, Variables, and Constants Part of the Picture:
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
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.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Basic Elements of C++ Chapter 2.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Expressions, Data Conversion, and Input
Objectives You should be able to describe: Data Types
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java Types and Expressions. 3.2 Primitive and Reference Types Each data value has a type The type must be declared for all variables & constants The compiler.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
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.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 2: Using Data.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Operations Lecture 9.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 Operations Making Things Happen (Chap. 3) Expressions.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
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.
Copyright Curt Hill Variables What are they? Why do we need them?
COMP Primitive and Class Types Yi Hong May 14, 2015.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Java-02 Basic Concepts Review concepts and examine how java handles them.
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.
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.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
CompSci 230 S Programming Techniques
Chapter Topics The Basics of a C++ Program Data Types
Chapter 6 JavaScript: Introduction to Scripting
Chapter 2 Basic Computation
Chapter 3 Assignment and Interactive Input.
Java Primer 1: Types, Classes and Operators
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
2.5 Another Java Application: Adding Integers
Basic Elements of C++.
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
Chapter 2 Basic Computation
Basic Elements of C++ Chapter 2.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 2 Edited by JJ Shepherd
A First Book of ANSI C Fourth Edition
Expressions and Assignment
Primitive Types and Expressions
Presentation transcript:

Types and Expressions Chapter 3

Chapter Contents 3.1 Introductory Example: Einstein's Equation 3.2 Primitive Types and Reference Types 3.3 Numeric Types and Expressions 3.4 Assignment Expressions 3.5 Java's boolean Type and Expressions 3.6 Java's Character-Related Types and Expressions 3.7. Graphical/Internet Java: Einstein's Calculator

Chapter Objectives Study another example of software development using OCD Review primitive vs. reference types View numeric types, operations, methods Study assignment, increment, decrement operators Examine boolean data type & operators Study character-related types Note internal representation of primitive types Study another example of GUI application & Applet

3.1 Introductory Example: Einstein's Equation Need a program to do calculations concerning amount of energy released by a quantity of matter for a mass given in a physics problem Object Centered Design –Behavior –Objects –Operations –Algorithm

Behavior Program should do the following –Display prompt for quantity of matter (mass) –Allow user to enter nonnegative real via keyboard –Use entered value and Einstein's equation to do calculation for energy –Display results with descriptive label

Objects Description of Object TypeKindName screen Screen varying theScreen prompt String constantnone qty of matter double varying mass keyboard Keyboard varying theKeyboard qty of energy double varying energy descriptive label String constantnone

Operations Based on our behavioral description: Display a string (prompt) on screen Read non negative number ( mass ) from keyboard Compute energy from mass –Equation needed: e = m * c 2 Display number ( energy ) & string on screen

Refinement of Objects Description of Object TypeKindName screen Screen varying theScreen prompt String constantnone qty of matter double varying mass keyboard Keyboard varying theKeyboard qty of energy double varying energy descriptive label String constantnone c double constant SPEED_OF_LIGHT 2 int constantnone

Algorithm 1. Ask theScreen to display prompt for mass to be converted into energy 2. Ask theKeyboard to read a number, store it in mass 3. Compute energy = mass * SPEED_OF_LIGHT 2 4. Ask theScreen to display energy and descriptive label

Coding, Execution, Testing Note source code, Figure 3.1 in text Note sample runs –Check to see if all behaviors are accomplished –Check for accuracy of calculations

3.2 Primitive and Reference Types Each data value has a type The type must be declared for all variables & constants The compiler needs this information –to allocate memory for the variable or constant –to verify that the variable/constant is being used correctly

Primitive Types Also known as "simple types" –int, byte, short, and long for integer values –float and double for real/fractional values –char for letters, digits, symbols, punctuation –boolean for true and false Literals: –values of one of these types –'A', -7, 3.5, true

Reference Types Needed to represent windows, buttons, inventory, students, etc. –objects more complicated than can be represented with simple types Create a class and you have created a new type whose name is the name of the class Types created from classes are called reference types

Java Provided Reference Types Over 1600 classes already available in Java Examples: –String – for constant sequences of characters –StringBuffer – for variable sequences of characters –BigInteger – for integers of "unlimited" size –BigDecimal – for fractional numbers of "unlimited" size

Creating Reference Type Values: Constructors Primitive types use literals for their values –Meanings of literals built into compiler Reference types have no pre-existent values –Values must be created with the new operator –Example: Integer integerValue = new Integer(321); type identifier name new operator call to initializing constructor

Default Value: null Default value for reference types Screen theScreen = null; //or Screen theScreen; –value used if none is specified in declaration –indicates variable does not yet refer to a value of that type –can later be assigned values created with new

Constructing an Object Use of new to create a reference type Class provides one or more methods –called constructors Syntax: new ClassName (arguments, …) –ClassName is name of a reference type –arguments is a sequence of values separated by commas –types of arguments match those permitted by ClassName

3.3 Numeric Types and Expressions Types for real or fractional numbers –float : use 32 bits (4 bytes) –double : use 64 bits (8 bytes) Types used for integers –byte : uses 8 bits –short : uses 16 bits (2 bytes) –int : uses 32 bits –long : uses 64 bits –char : uses 16 bits (can be either numeric or represent Unicode characters)

Other Numeric Types "Wrapper classes" for the primitive types BigInteger and BigDecimal for processing larger values –found in java.math package Although many possible numeric types are provided, int and double are the most often used

Numeric Literals Positive and negative whole numbers treated by default as type int Appending the letter L to a literal tells compiler to treat it as a long 678L -45L 0L –Note use of uppercase L to avoid confusion of l with 1 Also possible to specify octal or hexadecimal –precede the literal with 0 or 0x, respectively

Real Literals Fixed point representation –Form is m.n –m is the integer part, n is decimal part –either m or n must be present with the decimal point Floating point representation –Form is xEn or xen 4.5E6 or 6e-12 –x is an integer or fixed point real, n is an integer exponent (+ or -)

Default Values for Real Literals By default, real literals are considered to be of type double If value computed using real literals and assigned to a float variable, compiler generates an error –float not large enough to hold 64 bit computed value Appending an F to a real literal tells compiler to treat it as a float F 4E6F

Numeric Expressions Primitive Expression –sequence of one or more operands (values) –combined with zero or more operators –result is a value –the type of the value produced is the type of the expression ( int, double, etc.) Example 2 + x * (3 + y)

Numeric Operators Add Subtract Multiply Divide Mod + - * / % Operands may be of any primitive or real type Watch out! 3 / 4 is integer division, result is integer NOT the same as … 3.0 / 4 which is real division and gives real result

Bitwise Operators Can be applied to integer data at individual bit level -- the 0s and 1s in the bits –Negation ~ swaps 0 for 1 or 1 for 0 –AND & a & b is 1 if both a and b are 1, else 0 –OR | a | b is 1 if either or both are 1, else 0 –Exclusive OR ^

Bitwise Operators

Operator Precedence and Associativity One expression may have several different operators –compiler will perform some before others Numeric operator precedence is pretty much same as learned in math classes * and / and % first, left to right + and - next, left to right inside parentheses first Check precedence chart for other operators Associativity

Unary Operators Parentheses The + and - operators can be applied to a single operand - 5 * Parentheses can be used to supersede the order of operations -- force a lower precedence operations to happen first 3 * (6 + 5)

Instance Methods Think of sending a message to an object –same as invoking a method Example: double mass = theKeyboard.readDouble() –theKeyboard is the object –readDouble() is the method We send the message to the object of which method to execute

Static or Class Method Example: –method to square SPEED_OF_LIGHT energy = mass * Math.pow (SPEED_OF_LIGHT, 2.0); –pow( ) is the method –Math is the class We are sending a message to a class The keyword static is used inside the class definition –thus we need not declare a M ath object to which a message is sent

The Math Class Contains static constants PI = … E = … Contains static Methods (examples) abs(x) pow(x,y) sqrt(x) exp(x) log(x)

Wrapper Classes Primitive types do not provide all operations required Wrapper classes (similar to primitive types) contain additional capabilities ByteShortInteger LongFloatDouble BooleanCharacter Each of these extends the capabilities of the corresponding primitive type –wrapping it with useful constants and methods

Integer Wrapper Class Constants Integer.MAX_VALUE Integer.MIN_VALUE Methods int int_val; String digits; int_val = Integer.parsInt(digits); digits = Integer.toString( int_val) –convert between String and int Note Table 3.4 for additional Integer methods.

BigInteger and BigDecimal Classes For situations where numbers are too large for int, long, or double BigInteger an BigDecimal types are reference types –values must be constructed using new and the constructor methods Examples: –BigDecimal has a constructor to create a value from a double and another to create one from a string BigDecimal bd_value = new BigDecimal("12.345"); Note Table 3.5 for BigInteger methods

Implicit Type Conversion Promotion –When types are mixed in an expression (say int and double) –The smaller (lesser) type is "widened" to temporarily be the larger type –Note the diagram which shows the promotions possible –The compatibility is one way => only byte short int long float double char

Explicit Type Conversion Use Method Within Wrapper Class Wrapper classes provide type-conversion Example – round a double value to an int Double roundedDoubleVal = new Double(doubleVal + 0.5); int intVal = roundedDoubleVal.intValue(); Wrapper class has no static method to do this –must create a Double value, use intValue() method

Explicit Type Conversion Casting Use the name of the type to "cast" the desired type value int intValue = (int) (doubleVal + 0.5); Fractional part of doubleVal is truncated Syntax: (type) expression

3.4 Assignment Expressions Assignment expression uses assignment operator = to change the value of a variable Syntax variable = expression –variable is a valid Java identifier, declared as a variable –expression whose type is compatible with the variable

Assignment Example Given the declarations: double xValue, yValue; Initial values are default zero: Consider the following statements and watch the results xValue 0 yValue 0

Assignment Example double xValue, yValue; xValue = xValue yValue 0

Assignment Example double xValue, yValue; xValue = 25.00; yValue = Math.sqrt(xValue); xValue yValue 5.0

Assignment Example double xValue, yValue; xValue = 25.00; yValue = Math.sqrt(xValue); xValue = 16.00; xValue 16.0 yValue 5.0 Note that yValue does not automatically change to the square root of 16.0

Assignment Example double xValue, yValue; xValue = 25.00; yValue = Math.sqrt(xValue); xValue = 16.00; double hold = xValue; xValue 16.0 yValue 5.0 hold 16.0

Assignment Example double xValue, yValue; xValue = 25.00; yValue = Math.sqrt(xValue); xValue = 16.00; double hold = xValue; xValue = yValue; xValue 5.0 yValue 5.0 hold 16.0

Assignment Example double xValue, yValue; xValue = 25.00; yValue = Math.sqrt(xValue); xValue = 16.00; double hold = xValue; xValue = yValue; yValue = hold; xValue 5.0 yValue 16.0 hold 16.0 Note that we have effectively swapped the values held by xValue and yValue. Why was it necessary to use the hold variable?

Assignment as an Operation Three actions take place when variable = expression; takes place: –expression is evaluated, producing a value –the value of variable is changed to that value –the operator = produces the value Think of operators producing values produces the value of 8 An additional by product of the assignment operator is that it stores a value in the variable

Chaining Assignment Operators We have just stated that = is a value producing operator Thus x = y = 3.4; is equivalent to two statements y = 3.4; x = y;

Increment and Decrement Operations Consider count = count + 1; –Note that as an algebra equation it has no solution –However, it is an assignment statement The expression is evaluated The resulting value is stored in count Java also provides a unary increment operator to accomplish the same thing counter++;

Increment and Decrement Operations The increment and decrement operators can be placed either before or after the variable If placed afterit is called "postfix" –use the variable, then increment (decrement) x = counter++; If placed before, it is called "prefix" –increment (decrement) firs then use the result x = -- counter;

Other Assignment Shortcuts Adding a value to an accumulating variable sum = sum + amount; Java provides the shortcut sum += amount; This can also be done with numeric operators -= *= /= %= as well as with the bitwise operators

3.5 Java's Boolean Type and Expressions Has two possible values –literal values true and false boolean values produced by relational operators = == != Warning for comparing for equality –Do not use = (single equal sign) –An assignment results (and is evaluated)

Compound Boolean Expressions In mathematics we use relationships such as 0 < x < 7 This is actually two relationships and in Java we must state them so and combine them with the && (logical AND) (0 < x) && (x < 7) Similar compound relationships must be done with the logical OR ||

Short Circuit Evaluation Consider the logical or boolean expression p && q Both p and q must be true for the expression to be true Thus, if p evaluates as false, there is no need to check q –Java does not do so –This is called "short circuit evaluation" of a boolean expression Benefits –can guard against the q expression causing a program crash (division by zero, square root of a negative, etc.) –speeds up program performance

Operator Precedence Note the boolean expression x = z We need to know which operators have priority Note table in text: –Math operators have higher priority than … –Comparison operators which are higher than … –Logical AND and OR –Inside parentheses forces higher precedence

3.6 Character-Related Types and Expressions Four character- related types –char : primitive type for single characters –Character : a class for single characters –String : a class for constant sequences of characters –StringBuffer : class for variable sequences of characters

The char Primitive Type Includes … –alphabetical characters - upper and lower case –Variety of punctuation characters –Numerals '0' through '9' Apostrophe (single quote) is used to delimit (surround and distinguish) character literals 'a' 'Z' '?' To delimit the apostrophe, itself, use escape sequence -- use the back slash followed by a character to be represented '\'' '\n' '\t' –See table 3.6 in text

char Expressions char objects can be defined and initialized char Y_or_N = 'N'; Characters are used in comparisons 'a' < 'b' ('A' <= letter) && (letter <= 'Z')

Character Reference Type Character wrapper class Example methods digit(chi,b) getNumericValue(ch) isLetter(ch) isUpperCase(ch) See table 3.7 in text for more complete listing

String Reference Type String literals "" // empty string "345" "\n\tEnter the value -> " Java distinctives for String and StringBuffer –there is built in support for String literals –String variables can be initialized in the same way as literals (use of new command not required) –Support for the + operator on String values

String Operations Concatenation "Hi " + "Mom" results in "Hi Mom " –use the plus + operator Access of individual characters within the string String name = "Snidly"; – name.charAt(3) results in 'd' Note String Static Methods, Table 3.8 in text Snidly\ name

3.7 Graphical/Internet Java: Einstein's Equation Object-Centered Design : GUI Version –Similar to that derived in Section 3.1Section 3.1 –Here we use dialog widgets for I/O –They require String objects – must convert between String and double Program behavior –Display input box with prompt –User enters value (as a string) –Program converts to number, computes energy –Program builds a string to display results

Objects TypeKindName the program? input dialog?none dialog widget titles String constant TITLE prompt String constantnone dialog box's text fieldnone qty as a String String varying massString real number double varying mass qty of energy double varying energy descriptive label String constantnone energy & label as String String varying energyString message dialognone OK and Cancel buttonsnone

Operations 1. Display an input box 2. Read a String ( massString ) from the input box 3. Convert a String ( massString ) to a double ( mass ) 4. Compute energy from mass 5. Convert a double ( energy ) to a String ( energyString ) 6. Display a message box showing energyString 7. Terminate the program when the user presses its OK button

Coding, Execution, Testing Note Figure 3.2 with source code of GUI Mass-to-energy conversion program Note sample run Note Applet version, Figure 3.3 –Contrast to application (stand alone program) –Applet can be loaded as part of web page, executed by a browser

Contrast Application with Applet ApplicationApplet Object class extended Class not declared public Has a main() static keyword used Uses System.exit(1) JApplet class extended class declared to be public init() instead of main() init() not declared with static keyword Note Warning: …