Data Types and Operations On Data Objective To understand what data types are The need to study data types To differentiate between primitive types and.

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
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.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
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”
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.
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
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.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
Arithmetic Operations. Review function statement input/output comment #include data type variable identifier constant declaration.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
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.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Data Types and Operations On Data Objective To understand what data types are The need to study data types To differentiate between primitive types and.
1 CS 007: Introduction to Computer Programming Ihsan Ayyub Qazi.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
COMP Primitive and Class Types Yi Hong May 14, 2015.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
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 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Fundamentals 2 1. Programs and Data Most programs require the temporary storage of data. The data to be processed is stored in a temporary storage in.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
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.
Relational Operator and Operations
BASIC ELEMENTS OF A COMPUTER PROGRAM
Building Java Programs
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Object Oriented Programming
Multiple variables can be created in one declaration
Type Conversion, Constants, and the String Object
Escape Sequences What if we wanted to print the quote character?
Building Java Programs
Fundamentals 2.
Chapter 2: Java Fundamentals
Building Java Programs Chapter 2
Building Java Programs
Building Java Programs Chapter 2
Presentation transcript:

Data Types and Operations On Data Objective To understand what data types are The need to study data types To differentiate between primitive types and reference types To know the data range and storage requirements for each type To know the conditions for data conversion To know the permissible operations that can be performed on data To be able to evaluate expressions

Data Types and Operations On Data Introduction Data Types Primitive Type Integral Type Floating Point Type Character Type Boolean Type Type Compatibility Reference Type Arithmetic Operator and Operations Arithmetic Expressions Relational Operator and Operations Relational Expressions Logical Operator and Operations Input and Output Operations

Data Types - Introduction The concept of data type is like what the bolts and nuts are to a piece of machinery. It is impossible to write meaningful program, without understanding: Data types, data values The amount of memory required for each type of data, and The permissible operations that can be performed on data

Data Types - Introduction Like anything else, conservation of the use of memory is important. Some former languages did not consider conserving memory. Most of them had only two ways to store numeric values: int, for integers, and float, for floating point values. Hence wasting memory, especially when storing small values ; The amount of memory for each value, large or small, is the same.

Introduction – Data Types In the first section we: a)Study the fundamental data types in Java, and b)how they relate to programming. c)Focus on the operations that can be performed on each type. The second section introduces the reference type. This includes some of the fundamental Java classes, such as: a)The String class b)The Math class c)The wrapper classes

The Fundamental Types We had established that data is vital to a program. It must be stored in primary memory for the processor to handle it. The Java specifies two broad categories of data types: a)Primitive, and b)Reference type Primitive types are atomic They cannot be decomposed into simpler types Reference types are constructed from: a)Primitive types, b)As well as from other reference types

Data Types Data types Primitive types Reference types Integral types Floating Point boolean Integers byteshort int longfloatdouble User defined classes Java classes char Boolean types Character

Primitive Types Primitive types are atomic There are three types – integral, floating point, and boolean Integral – they can be represented by an integer value There are two groups – integer and character Integer – byte, short, int, long

Integer Type Data typesStorage RequiredRange of Values byte8 bits (byte)-128 to +127 Short16 bits (2 bytes)-32,768 to +32,767 int32 bits (4 bytes02,147,483,648 to +2,147,483,647 long64 bits (8bytes)-9223,372,036,854,775,808 to +9223,372,036,854,775,807

Floating Point Type Data TypeStorage requiredRange of Values float32 bits (4 bytes)-3.4 x to +3.4 x double64 bits (8 bytes)-1.7 x to +1.7 x

Storage Space long int short byte

Default Values Integer types – 0 Floating point types – 0.0

Assignment Incompatibility Variables can be initialized wrongly This situation gives rise to syntax errors Consider the following statement: int x = 2.0; Configuration: j2sdk1.4.1_ C:\chapter3\unicodeChar.java:5: possible loss of precision found : doublerequired: int int x = 2.0; ^ 1 error Process completed

Assignment Incompatibility Consider the following statement: short x = ; This gives rise to syntax error also. Configuration: j2sdk1.4.1_ C: \chapter3\unicodeChar.java:5: possible loss of precision found : int required: short short x = ; ^ 1 error Process completed

Assignment Incompatibility Consider the following segment of code: int x = 2; byte y = x; -----Configuration: j2sdk1.4.1_ C:\istings\data_types\default_types.java:6: possible loss of precision found : int required: byte byte y = x; ^ 1 error Process completed.

Character type - char The character data type named char is : Any printable symbol found on the keyboard, or Certain sequence of characters called escape sequence. In either case, it requires 16 bits (2 bytes) of memory to store the char value A char value can be represented decimal value in the range 0 to 65,536, or as Unicode character in the range ‘\u0000” to ‘\uFFFF ’ Data typeStorage RequiredRange in DecimalRange in Unicode Char16 bits (2 bytes)0 to 65,536\u0000 to \uFFFF

Boolean Type Java’s logical data type is called boolean. The set of values that represent the boolean data type is true and false. This data type is implemented when comparing primitive types. Boolean variables are declared the same way as other variables The default of a boolean variable is false Consider the following statement boolean x = 0; Configuration: j2sdk1.4.1_ C: \chapter3\unicodeChar.java:5: incompatible types found : int required: boolean boolean x = 0; ^ 1 error Process completed.

Operator and Operations on Data Computers are known as number crunching machines. To crunch numbers, they need to perform operations on the numbers Java has five types of operations to perform on primitive data values: Arithmetic operations Relational operations Logical operations Bit-wise operations, and Bit-shift operations We will study the first three – Arithmetic, Relational and Logical operations

Arithmetic Operator and Operations Java defines five binary arithmetic operators: + - * / % They are used to form arithmetic expressions. The format of an arithmetic expression is: operand operator operand; Operands are any valid identifier or numeric literal, and Operator is any of five arithmetic operators. See summarized below OperatorNameAlgebraic formExampleResult +Additionx + y Subtractionx – y *Multiplicationx * y18 * 236 /Divisionx / y37 / 57 %Modulus operationx % y37 % 52

The operator / vs % The operators (+, -, * ) have the usual arithmetic meaning The operator ( / ), gives the quotient when applied to division That is why: 37/5 = 7, and not 7.4 The operator ( % ), gives the remainder when applied to division Hence, 37 % 5 = 2.

The operator / vs % If a task takes a worker 127 minutes to complete, how many hours and how many minutes did it take the person to complete. If we were to program this, we would have to tell the computer precisely how to carry out the calculation. That is: The number of hours would be (127 / 60) 2 hours, and The number of minutes would be (127 % 60) 7 minutes.

Example A small company wants you to write a program to figure out the number of boxes needed to ship book orders without wasting space. They have four types of boxes: extra large, large, medium and small, which can hold 25, 15, 5 and 1 book(s) respectively. Write a Java program that accepts the number of books to be shipped and displays the number of boxes needed with their type. For example if the company wants to ship 81 books your output should be 3 big boxes, 1 medium box and 1 small box.

Solution As before let us identify the elements of the problem Let us call the entity – PackingBooks No list the characteristics (attributes) of PackingBooks Constants Variables Constructor Operations Methods

PackingBooks - Attributes Constants Extra large box Large box Medium box Small box Variables books Extra large Large Medium Small

PackingBooks - Constructor The problem suggests only one argument required – the number of books PackingBooks( books) Mutator Method determineBoxes() Accessor Methods getBigBox() getLargeBox() getMediumBox() getSmallBox()

Class PackingBooks 1.class Packing 2.{ 3.static final int XTRA_LARGE_BOX = 25, 4. LARGE_BOX = 15, 5. MEDIUM_BOX = 5, 6. SMALL_BOX = 1; 7. 8.int books; 9.int big, large, medium, small; Packing(int books) 12.{ 13.this.books = books; 14.}

Class PackingBooks – Mutator Method void determineBoxes() 17.{ 18.big = books/XTRA_LARGE_BOX; 19.books = books % XTRA_LARGE_BOX; large = books/LARGE_BOX; 22.books = books % LARGE_BOX; medium = books/MEDIUM_BOX; 25.small = books % MEDIUM_BOX; 26.}

Class PackingBooks – Mutator Method 27. int getXtraLargeBox() 28.{ 29.return big; 30.} int getLargeBox() 33.{ 34.return large; 35.} int getMediumBox() 38.{ 39.return medium; 40.} int getSmallBox() 43.{ 44.return small; 45.} 46.}

Class PackingBooks – Test class 1.class TestPacking 2.{ 3.public static void main(String [] arg) 4.{ 5.Packing pack = new Packing(127); 6.pack.calculate(); 7. 8.System.out.println(pack.getXLarge() + " extra large boxex\n" + pack.getLarge() 9. + " large boxex\n" + pack.getMedium() " medium boxes\n" + pack.getSmall() " small box\n" + pack.getTotal() " total boxes\n") ; 13.} 14.}

Integer Operations Integer oprations ResultExampleActual ResultCorrect Result int + intnumber too large int - intnumber too large int * intnumber too large * int / intArithmetic Exception125/0ArithmeticExceptionNo correct result int % intArithmetic Exception125 % 0ArithmeticExceptionNo correct result Integer operations can produce erroneous results

Floating Point Operations Floating -Point operations can produce erroneous results Floating-Point OperationsResults float + floatInfinity float - float-Infinity float * floatInfinity float / floatInfinity -float / float-Infinity -float / 0.0-Infinity 0.0/0.0NaN -float * float-Infinity Modulus operation ( % )Same as division

Evaluate Arithmetic expressions – In general, arithmetic expressions are evaluated from left to right

Evaluate Arithmetic expressions The order of evaluating an expression may be altered. Criteria Unary operators are done first - they have the highest priority. Parenthesize (sub-expressions) have the next level of priority. Multiplication, division and modulus have next level of priority Addition and subtraction have the lowest level of priority.

Evaluate Arithmetic expressions – 4 * The operations * / % must be carried out before addition and subtraction

Evaluate Arithmetic expressions 2 + ( 3 – 4) * The parentheses must be carried out before + - * / %

Evaluate Arithmetic expressions 11 % 4 * 2 – 14/3 + (8 –2 * -3)

Converting Algebraic Expression s = s 0 +v 0 t + ½ gt 2 s = s0 + v0 * t + g * t * t / 2.0; or s = s0 + v0 * t +1.0/2 *g * t * t ; or s = s0 + v0 * t +0.5 *g * t * t ; or s = s0 + v0 * t + (float)1/2 *g * t * t ;

Centigrade = 1.class DataTypes 2.{ 3. public static void main(String[] arg) 4. { 5. double fahrenheit = 42.0; 6. double centigrade = 5/9*(fahrenheit ); 7. System.out.println(centigrade); 8. } 9.}

The Fundamental Types What will happen if you attempt to compile each of the following lines of code? 1.int x = 25.0; 2.float x = 1.0; 3.byte x = 130; 4.char x = 128; 5.boolean x = 1;

Relational Operator and Operations There are six binary relational operators in Java. They are used to form conditional expressions. They are used with primitive numeric and the character types only.

Relational Operators & Operations OperatorOperationUsage patternExample <Strictly less thanx < y100 < 200 <=Less than or equal to x <= y100 <= 200 >Strictly greater thanx > yx > y200 > 100 >=Greater than or equal tox >= y200 >= 100 ==Is equal tox == y200 == 100 !=Not equal tox != y200 != 100

Relational expression Relational expression is a combination of two primitive types separated by a relational operator. The result from evaluating the expression is one of the boolean values, true or false. The general form of simple conditional statements is: Left_Operand Relational_Operator Right_Operand Example: 10 > 15 ‘a’ != ‘A’

Evaluating Relational Expressions When evaluation relational expressions, you must: First resolve all arithmetic expressions to get the primitive values. Then compare the primitive values as specified by the relational operator Example: Use the following declaration to evaluate the relational expressions int x = 10, y = 20; double z = 5.0; Evaluate the following relational expressions. 1. x / y < z 2. x%y - 10 >= x - y/x - z

Evaluate Relational Expression: x / y < z int x = 10, y = 20; double z = 5.0; x / y < z 0 true

Evaluate Relational Expression: x%y - 10 >= x - y/x - z int x = 10, y = 20; double z = 5.0; x % y - 10 >= x - y / x - z false

Evaluate Relational Expression: x%y – (10 >= x ) - y/x - z int x = 10, y = 20; double z = 5.0; X % y – ( 10 >= x ) - y/x - z

Evaluate Relational Expression: x%y – (10 >= x ) - y/x - z int x = 10, y = 20; double z = 5.0; x % y - ( 10 >= x ) - y / x - z 10 true ??? ?

Evaluating Relational Expressions The value from a relational expression can be assigned to a Boolean variable. The format is: boolean id = relational_expression. For example : int x = 120; double y = 20; boolean flag = 2 * x > y + 2; Note: The relational expression must be evaluated first. The resulting value is assigned to the Boolean variable flag. In this case the value true is assigned to the variable flag.

Logical Operator and Operations Java has three logical operators: logical-AND ( && ) – Determines the validity of two relational expressions logical-OR ( || ) - Determines the validity of one or both two relational expressions logical-NOT ( ! ) – Negates the result of a boolean value This means that the relational expressions must first be evaluated, before logical operators can be applied.

Evaluate Logical Expression: x + y > z && x – y < z int x = 10, y = 20; double z = 5.0; x + y > z && x – y < z true true true

Evaluate Logical Expression int x = 10, y = 20; double z = 5.0; x - y > z || x – y < z false true true

Evaluate Logical Expression: !( x + y > z && x – y < z ) int x = 10, y = 20; double z = 5.0; !(x + y > z && x – y < z) true true true false