Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.

Slides:



Advertisements
Similar presentations
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
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.
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.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
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.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
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.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
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.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
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.
L EC. 02: D ATA T YPES AND O PERATORS (1/2) Fall Java Programming.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Copyright © 2003 Pearson Education, Inc. Slide 2-1 Problem Solving with Java™ Second Edition Elliot Koffman and Ursula Wolz Copyright © 2003 Pearson Education,
 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)
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
OperatorstMyn1 Operators The sequence in which different operators in an expression are executed is determined by the precedence of the operators. Operators.
2440: 211 Interactive Web Programming Expressions & Operators.
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.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Simple Data Types and Statements. Namespaces namespace MyNamespace { // …. { MyNamespace::func1() using namespace OtherNamespace; Comments: // /* xxxx.
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.
Chapter 2: Using Data.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Mathematical Calculations in Java Mrs. G. Chapman.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
August 6, 2009 Data Types, Variables, and Arrays.
Chapter 3 The Basic Data Types C/C++ Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Chapter 2 Variables.
Mathematical Calculations in Java Mrs. C. Furman.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
COMP Primitive and Class Types Yi Hong May 14, 2015.
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.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Chapter 14 JavaScript: Part II The Web Warrior Guide to Web Design Technologies.
Programming Principles Operators and Expressions.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
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.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 2 Variables.
Lecture 3 Java Operators.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Object Oriented Programming
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Type Conversion, Constants, and the String Object
Escape Sequences What if we wanted to print the quote character?
Chapter 2 Variables.
Expressions and Assignment
elementary programming
Primitive Types and Expressions
Chapter 2 Variables.
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Chapter 2: Introducing Data Types and Operators

 Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables within a method  Use the arithmetic operators  Use the relational and logical operators

 Understand the assignment operators  Use shorthand assignments  Understand type conversion in assignment  Cast incompatible types  Understand type conversion in expressions

 Java is a strongly typed language.  All operations are type checked by the compiler.  The data type determines what operations can be performed on the data.  Data types determine:  How the data is stored in memory.  How much memory is allocated for a given type.  The minimum/maximum value that type can store.  How the item is used in expressions.

 Java has 8 built-in types, called primitive types.  Each type is based on a class, but are not objects of their respective classes. TypeMeaning booleanRepresents true/false values byte8 bit integer (whole number) char16 bit Unicode character double64 bit double-precision floating point value float32 bit single-precision floating point value int32 bit integer (whole number) long64 bit integer (whole number) short16 bit integer (whole number)

 Whole numbers either positive or negative.  Java does not support unsigned integers. TypeRangeSize byte -128 to 127Signed 8-bit integer short -32,768 to 32,767Signed 16-bit integer int -2,147,483,648 to 2,147,483,647Signed 32-bit integer long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Signed 64-bit integer Note: Although char is technically an integer, its use is to represent characters and will be discussed separately.

 Floating-point types represent numbers with a fractional component.  May be either positive or negative. TypeApproximate rangePrecisionSize float -3.4*10 38 to +3.4* digitsSigned 32-bit double -1.70* to +1.7* digitsSigned 64-bit

 Java uses a 16 bit structure to store character data called Unicode.  char is an unsigned 16-bit value ranging from 0 – 65,535.  The ASCII character set represents the first 128 values of the Unicode set (0 – 127).  Character variables (char) can be assigned a value either by using a character, or its numeric value.  char ch = ‘X’;or char ch = 88;

 Represents a true/false value.  You cannot use yes/no, 0/1, on/off.  Outcome of all relational operations is a boolean value.

 Literals are un-named fixed values in your program such as 333, 24.67, ‘A’, or “Gary”.  Numeric values without a decimal point default to the int data type.  Numeric values with a decimal point default to the double data type.

 Hexadecimal values = base 16  Octal values = base 8  Binary values = base 2  Can assign integral values using different bases;  hex = 0xFF;// 256 in decimal  oct = 011// 9 in decimal  bin = 0b1100// 12 in binary

 Many characters are not visible.  Tab, carriage return, new line, backspace, etc.  Single and double quotes have special meaning in Java  You can embed escape sequences in data to cause different effects.  You can also assign escape sequences to the char data type.

Escape SequenceDescription \’single quote \”double quote \\backslash \rcarriage return \nnew line \fform feed \thorizontal tab \bbacksapce \dddoctal constant where ddd is the octal value \uxxxxhexadecimal constant where xxxx is a hexadecimal value

 A string is a group of characters.  Must be enclosed in double quotes.  May include escape sequences.  A string of a single character is not the same as a char. Strings are objects regardless of their length.  “Java is fun”

 Variables hold data that can change during program execution.  Variables must be declared before you can use them.  Declaration:dataTypeidentifier;  Example: double interestRate;  intnumberStudents;  char middleInitial;

 Initialization sets the beginning value of a variable.  Add and assignment operator (=) and value.  Format: dataType identifer = value;  Example:double interestRate =.125;  int numberStudents = 16;  char middleInitial = ‘R’;

 By default, numeric literals consisting of whole numbers are int types; floating-point numeric literals are double types.  To initialize a float type using a numeric literal, you must add a cast.  float price = f; or float price = F;  float price = (float) ;

 You can use other variables to initialize a variable.  Must be the same data type  Must be already initialized.  You can also use a formula to initialize a variable.  int beginningReading = 24587;  int endingReading = 30658;  int amountUsed = endingReading – beginningReading;

 Variables can be declared within any block of code (bounded by curly braces).  A block defines a scope.  Variables defined within a code block are not available outside of the code block.  When the block ends, the variables are said to be out of scope.  Variables defined in an outer block, are accessible to any inner block.

public static void main(String args[]) { int count = 4; System.out.println("Count is " + count); { int anotherCount = 10; int count = 23; // Already declared in outer code block. System.out.println("Count is " + count); System.out.println("Another count is " + anotherCount); } System.out.println("Another count is " + anotherCount); // variable out of scope } Note: Lines highlighted in red are flagged as errors.

 Operators are symbols that tell the compiler to perform a specific mathematical or logical operation.  Arithmetic  Increment/Decrement  Relational  Logical  Short Circuit  Assignment

OperatorMeaning +Addition (also unary plus) -Subtraction (also unary minus) *Multiplication /Division %Modulus (remainder) ++Increment (by a value of 1) -- Decrement (by a value of 1)

OperatorMeaning ==Equal to !=Not equal to >Greater than <Less than >=Greater than or equal to <=Less than or equal to

OperatorMeaning &AND aka logical AND |OR aka logical OR ^XOR (Exclusive OR) One and only one operand is true ||Short-circuit OR aka conditional OR &&Short-circuit AND aka conditional AND !Not

 In a series of comparisons (ANDs and Ors), Java will stop evaluating sets of operands if a previous set of operands results in a true result for an OR condition or false for an AND condition.  if (10 3 || 9 == 10)  Since the first set (10 < 12) is true, there is no need to evaluate the other two sets. The result is true.

 if (10 3 && 9 == 10)  10 3 is false. Therefore, the last set (9 == 10) will not be evaluated. The expression is false.  If you want to force Java to complete all evaluations, then use logical ANDs (&) and logical Ors (|).

 The assignment operator (=) assigns the value on the right side of the operator to the variable on the left.  Format: resultVariable = someValue;

 Simplifies coding of certain assignment statements. OperatorShorthandLonghand +=x += 5x = x + 5 -=x -=5x = x – 5 *=x *= 5x = x * 5 /=x /= 5x = x / 5 %=x %= 5x = x % 5

 You may have to user variables of different types.  Remember: Java is a strictly typed language.  Automatic type conversion happens when:  the two types are compatible.  when the destination type is larger than the source type.  Called widening conversion.  In all cases, there is no automatic conversion from floating-point types to integer types.

 A cast is an instruction to the compiler to convert one type to another.  Format: (targetType) expression;  Data loss may occur when you go from a larger sized type to a smaller sized type (narrowing conversion).  Casting may be necessary with integer math since the result of integer math is an integer (no decimal values).

double x, y; byte b; int i; char ch; x = 10.0; y = 3.0; i = (int) (x/y); // Cast double to int. Fractional part will be lost. i = 100; b = (byte) i; // No data loss since a byte can hold a value up to 255. i = 257; b = (byte) i; // This will be a run-time error since the maximum value of a byte is 255. b = 88; // ASCII code for X ch = (char) b; // Cast between incompatible types.

OperatorsPrecedence (highest to lowest) postfixexpr++ expr-- unary++expr -- --expr +expr -expr ~ ! multiplicative* / % additive+ - shift > >>> relational = instanceof equality== != bitwise AND& bitwise exclusive OR^ bitwise inclusive OR| logical AND&& logical OR|| ternary? : assignment= += -= *= /= %= &= ^= |= >= >>>=

 Parenthesis can be used to change the order of operations.  Items inside parenthesis are done before those outside.  You can nest parenthesis.  When items with the same precedence appear in the same expression, all binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

 Expressions are instructions that assign a value to a resultant variable.  Format: resultVariable = expression;  Expression consists of:  variables  literals  methods that return values  any combination of the above

 You can mix different types of data as long as they are compatible.  Java converts mixed types to the same largest type (promotion).  Integers and floating-point values would be promoted to floating-point.  Example: Given an int and double in the same expression, the int value would be promoted to a double.  Promotion only applies within the expression.

 Adding spaces in expressions can make it easier to read.  Parenthesis increase the precedence of the operations within them.  Redundant or addition parenthesis will not cause any errors or slow down the execution of the expression.  Like algebra, expressions inside parenthesis are performed before those outside of the parenthesis.