Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.

Slides:



Advertisements
Similar presentations
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.
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.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
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.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Logical Operators and Conditional statements
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.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
String Escape Sequences
Expressions, Data Conversion, and Input
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
CSCI 1100/1202 January 16, Why do we need variables? To store intermediate results in a long computation. To store a value that is used more than.
 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.
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
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.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CS 112 Introduction to Programming Variables; Type Casting; Using Variables in for Loops Yang (Richard) Yang Computer Science Department Yale University.
1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
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:
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
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.
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
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.
© 2006 Pearson Education Chapter 2: Objects and Primitive Data Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Object Oriented Programming
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Boolean Expressions and If
Type Conversion, Constants, and the String Object
Escape Sequences What if we wanted to print the quote character?
Increment and Decrement
Lecture 3 Expressions Richard Gesick.
Objects and Primitive Data
Arithmetic Expressions & Data Conversions
Expressions and Assignment
Data Types and Expressions
Chap 7. Advanced Control Statements in Java
Data Types and Expressions
Arithmetic Expressions & Data Conversions
Data Types and Expressions
Presentation transcript:

Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int (class Integer), long (class Long) two of them represent floating point numbers float (class Float), double (class Double) one of them represents characters: char (class Character) and one of them represents boolean (logical) values: boolean (class Boolean)

Numeric Primitive Data “Objects” of different numeric data types occupy different number of cells Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x 10308 with 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 1018 IEEE 754 format

Recap: Arithmetic Operations The storage of a computer is limited; this leads to potential surprises: numerical data types, especially float and double, have limited precision: a computer cannot store all of the numbers precisely in its claimed range e.g., the numbers a double can represent: +/- 1.7 x 10308; but there are infinite number of numbers in between Historical example: The Patriot Missile Failure in 1991 a computer cannot represent 0.1 precisely; for a 24-bit floating point number they used, it is off by 0.000000095. After 100 hours in operation, it is off by about 0.34 seconds, leading to an error of 600 meters for the detected Scud missile. (http://www.ima.umn.edu/~arnold/disasters/patriot.html)

Multiple variables can be created in one declaration Variables: Revisited We already know that a variable must be declared, specifying the variable's name and the type of information that will be held in it As of now, think of a variable as a name for a location in memory cell (we will revisit the concept later) int total; int count, temp, result; Multiple variables can be created in one declaration data type variable name

Variables A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; String msg1 = new String( “Hello” ); String msg2 = “Hello” ; When a variable is referenced in a program, its current value is used

Change the Value of a Variable: Assignment Statement An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; The expression on the right is evaluated and the result is stored in the variable on the left The value that was in total is overwritten Remember: you can only assign a value to a variable that is consistent with the variable's declared type

Constants A “constant variable” is an identifier that is similar to a variable except that it holds one value for its entire existence Why constants: give names to otherwise unclear literal values facilitate changes to the code prevent inadvertent errors In Java, we use the final modifier to declare a variable constant, and the convention is to use all capital words to name a constant final double PI = 3.14159265; The compiler will issue an error if you try to assign value to a constant variable after its declaration

Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions (we will see logical expressions later) are essentially special methods applied to numerical data objects: compute numeric results and make use of the arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder %

Division and Remainder If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals? 8 / 12 equals? The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % 3 equals? 8 % 12 equals?

Recap: Arithmetic Operations In daily life, we generally do not distinguish different types of numbers, but a computer does; this leads to the third type of surprise the result of an operation depends on data types: e.g., 4 / 8 vs 4.0 / 8.0 e.g., “Year “ + 2005

Arithmetic Expressions Arithmetic operators can be combined into complex arithmetic expressions, e.g., result = total + count / max - offset; The evaluation order of the operators in an arithmetic expression is determined by a well-defined precedence which determines the order in which they are evaluated Precedence rules multiplication (*), division (/), and remainder (%) are evaluated prior to addition (+) and subtraction (-) operators with the same precedence are evaluated from left to right parentheses can always be used to force the evaluation order

Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1

Assignment Revisited (again) You can consider assignment as an operator, with a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side

Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value)

Variables and Assignment What do these two statements do? Value stored in x y a b b b x = y; y = x; Question: How do I swap the values of two variables?

How do I Swap the Values of Two Variable? t1 = x; t2 = y; x = t1; y = t2; Use two temporaries: t = x; x = y; y = t; Use one temporary:

Swapping Values of Two Variables No temporaries! Value stored in x y a b a+b b a+b a b a Don’t write such code!! x = x + y; y = x - y; x = x - y;

More Assignment-related Operators Increment and decrement operators: ++, -- Assignment operators: +=, -=, *=, /= these three expressions have the same effect count = count + 1; count += 1; count ++; these two expressions have the same effect count = count - 10; count -= 10;

Data Conversions What is data conversion? Why data conversions? data conversion is the conversion of an object of one type to an object of a different type, e.g., an int to a double, a double to an int, an int to a string Why data conversions? Java is a strongly typed language, i.e., every object has a type, and the result of an operation depends on the type of the operands remember: 4 / 8  4.0 / 8.0 however, sometimes it is more efficient (and natural) to store data as one type, but during a computation, we may want to treat the data as a different type to get desired results the Ariane 5 example, the Patriot missile example for example, we may want to store data as integers, but during a computation, we want to treat integers as floating point values to get the desired results, e.g., we want miles / gallons to be treated as floating point / int miles; int gallons; System.out.print( miles / gallons ); sometimes we just write mixed-type expression

Mixed-type Expressions: Example An integer literal is by default of type int that is, a literal number 4 in Java is of type int to say that the number 4 is of type long, write 4l or 4L (4L is preferred over 4l since lower case “l” is hard to distinguish from 1) A floating point literal is by default of type double to day that the number 0.5 is of type float, write 0.5f or 0.5F Sometime we write 4.0 / 8, which is a mixed-type expression Java defines only: int / int, double / double to perform the mixed-type numerical operation, Java needs to convert the operands to be of the same type

Mixed-type Expressions: Example 2 We have already seen examples such as System.out.println( “Year: ” + 2005 ); Here “Year: ” is of type String, but 2005 is an integer We know that Java has defined string1 + string2 but not a string + integer

Different Type Conversions in Java Identity conversion (i.e., no conversion) Conversions related to primitive data types widening primitive conversions narrowing primitive conversions Conversions related to general classes widening reference conversions narrowing reference conversions we will cover these two cases later in the course; they are powerful tools to allow polymorphism Conversions related to Strings string conversions: i.e., convert a numerical object to a string, e.g., the number 17 to the string “17”

Widening Primitive Conversions Widening primitive conversions are those that do not lose information about the overall magnitude of a numeric value Java defines 19 primitive conversions as widening primitive conversions byte  short, int, long, float, double short  int, long, float, double char  int, long, float, double int  long, float, double long  float, double float  double They are generally safe because they tend to go from a small data type to a larger one (such as a short to an int) can problems happen in some of the cases?

Narrowing Primitive Conversions Java defines 23 primitive conversions as narrowing primitive conversions byte  char short  byte, char char  byte, short int  byte, short, char long  byte, short, char, int float  byte, short, char, int, long double byte, short, char, int, long, float Narrowing primitive conversions may lose overall magnitude of a numeric value, or precision

How Do Data Conversions Happen? Implicitly: arithmetic (numeric) promotion occurs automatically when the operands of a binary arithmetic operator (note “=“ is not one) are of different types the promotion uses widening conversion, i.e., if either operand is double, the other is converted to double otherwise, if either operand is float, the other is converted to float otherwise, if either operand is long, the other is converted to long otherwise, both operands are converted to int Examples: - 4.0 / 8 (which / is it: double/double, float/float, int/int) - 4 / 8.0 (which / is it: double/double, float/float, int/int) - 4 + 5 / 9 + 1.0 + 5 / 9 / 10.0 (what is the value?)

How Do Data Conversions Happen? Implicitly: string conversion applies only to the operands of the operator + occurs automatically: when one of the operands is a string, the other operand is converted to a string Examples: System.out.println( “Year: “ + 2000 ); System.out.println( “Year: “ + (2000 + 5) ); System.out.println( “Year: “ + 200 + 5); System.out.println( 200 + 5 + “Year: “ ); See Addition.java

How Do Data Conversions Happen? Implicitly: assignment conversion occurs automatically when the value of an expression is assigned to a variable of another type: only widening primitive conversions are allowed or a special case of narrowing primitive conversions: the expression is a constant of type int: e.g., 2 * 200 the type of the variable is byte, short or char the compiler can check to be sure that the value is representable by the type of the variable Examples: byte theAnswer = 42; // is this OK? float myFloat1 = 2; // is this OK? float myFloat1 = 2.0; // is this OK? float myFloat3 = theAnswer; // is this OK?

How Do Data Conversions Happen? Explicitly: Casting Casting is the most powerful and dangerous technique for data conversions Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value/variable being converted for example, if total and count are integers, but we want a floating point result when dividing them, we can explicitly cast total to be a float: result = (float) total / count;

Casting Pay particular attention when you forcefully cast a narrowing conversion, e.g., when you cast a float/double to an int, the float/double is just truncated to an int (e.g., 0.99 is truncated to 0), not rounded to an int (e.g., 0.5 will be rounded to 1) Example: double myDouble = 2.4 / 3.0; int myInt = (int) myDouble; // what is the value of myInt ?

Using Math Rounding In the example of slide 10, if you want myInt to be 1, i.e., 0.8 is rounded to the nearest integer, use the Math.round() method: double myDouble = 2.4 / 3.0; int myInt = (int) Math.round( myDouble );

Math.abs(), Math.cos(), Math.sqrt() Using Math Rounding We invoke Math.round() from the Math class without creating an object This is because round is defined as a static method in the class of Math Static methods are called class methods we invoke a static method through the class name, instead of through an instance (i.e., an object) of the class The Math class defines many other static methods, providing various mathematical functions, such as absolute value, trigonometry functions, square root, etc. Math.abs(), Math.cos(), Math.sqrt()

Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic decisions Java's conditional statements: the if and if-else statements the conditional operator the switch statement

The if Statement The if statement has the following syntax: The condition must be a boolean expression. e.g., a boolean variable, a == b, a <= b. It must evaluate to either true or false. if is a Java reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.

The if Statement: Examples An example: String str = “good”; if (GPA > 3.0) str = “excellent”; System.out.println (“Your GPA is " + str); First, the condition is evaluated. The value of GPA is either greater than the value of 3.0, or it is not. If the condition is true, the assignment statement is executed. If it is not, the assignment statement is skipped. Either way, the call to println is executed next.

Logic of an if statement condition evaluated true false statement

The if-else Statement An else clause can be added to an if statement to make it an if-else statement: if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both

Logic of an if-else statement condition evaluated true false Statement 1 Statement 2

What if I Want to Run Several Statements: Block Statements Several statements can be grouped together into a block statement A block is delimited by braces ( { … } ) A block statement can be used wherever a statement is called for in the Java syntax For example, in an if-else statement, the if portion, or the else portion, or both, could be block statements

Boolean Expressions: Basics A condition of an if statement often uses one of Java's equality operators (==, !=) or relational operators (<, >, <=, >=), which all return boolean results: == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=) if ( condition ) statement1; else statement2;

More Complex (Compound) Boolean Expressions: Logical Operators Boolean expressions can also use the following logical operators: ! Logical NOT && Logical AND || Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it has one operand), but logical AND and logical OR are binary operators (they each have two operands)

Loop Statements while statement do statement for statement while ( condition ) statement; while statement do statement for statement do { statement list; } while ( condition ); for ( initialization ; condition ; increment ) statement;

Flowchart of a while Loop condition evaluated while ( condition ) statement; false statement true

Example System.out.print( “Enter a month (1 to 12): “); int month = scan.nextInt(); while (month < 1 || month > 12) { System.out.println( month + “ is not a valid month.” ); month = scan.nextInt(); } // set initial value of month so that the while condition // below is false initially int month = -1; while (month < 1 || month > 12) { System.out.print( “Enter a month (1 to 12): “); month = scan.nextInt(); }

The do Statement: Syntax Both do and while are reserved words do { statement; } while ( condition ); The statement is executed once initially, then the condition is evaluated The statement is repetitively executed until the condition becomes false

Flowchart of a do Loop do { statement; } while ( condition ); true condition evaluated false

Comparing the while and do Loops statement true condition evaluated false while loop true condition evaluated statement false do loop A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed Therefore the body of a do loop will execute at least once

Example int month; // no need to initialize month do { System.out.print( “Enter a month (1 to 12): “); month = scan.nextInt(); } while (month < 1 || month > 12); // beginning of the next statement

The for Statement: Syntax The initialization portion is executed once before the loop begins The statement is executed until the condition becomes false Reserved word for ( initialization ; condition ; increment ) statement; Both semi-colons are always required The increment portion is executed at the end of each iteration

The for Statement: Syntax Each expression in the header of a for loop is optional if the initialization is left out, no initialization is performed if the condition is left out, it is always considered to be true if the increment is left out, no increment operation is performed

Flowchart of a for loop initialization condition evaluated false for ( initialization ; condition ; increment ) statement; initialization condition evaluated false statement true increment

The for Statement for ( initialization ; condition ; increment ) statement; A for loop is equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }

The for Statement: Example int sum = 0; for (int counter = 1; counter <= max; counter++) sum += counter; // beginning of the next statement Establish initial value of control variable. int counter = 1 Determine if final value of control variable has been reached. true counter <= max sum+= counter counter++ Increment the control variable. false Body of loop (this may be multiple statements)