Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 Chapter 2: Introducing Data Types and Operators

2  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

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

4  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.

5  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)

6  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.

7  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*10 38 6-7 digitsSigned 32-bit double -1.70*10 308 to +1.7*10 308 15-16 digitsSigned 64-bit

8  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;

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

10  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.

11  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

12  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.

13 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

14  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”

15  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;

16  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’;

17  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 = 123.45f; or float price = 123.45F;  float price = (float) 123.45;

18  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;

19  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.

20 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.

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

22 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)

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

24 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

25  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.

26  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 (|).

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

28  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

29  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.

30  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).

31 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.

32 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= += -= *= /= %= &= ^= |= >= >>>=

33  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.

34  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

35  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.

36  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.


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

Similar presentations


Ads by Google