Chapter 2: Introducing Data Types and Operators. Know Java’s primitive types Use literals ...
-
Upload
harold-ward -
Category
Documents
-
view
227 -
download
1
Transcript of Chapter 2: Introducing Data Types and Operators. Know Java’s primitive types Use literals ...
JAVA: A BEGINNER’S GUIDEChapter 2: Introducing Data Types and Operators
KEY SKILLS AND CONCEPTS
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
KEY SKILLS AND CONCEPTS
Understand the assignment operators Use shorthand assignments Understand type conversion in
assignment Cast incompatible types Understand type conversion in
expressions
WHY DATA TYPES ARE IMPORTANT
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 PRIMITIVE TYPES
Java has 8 built-in types, called primitive types.
Each type is based on a class, but are not objects of their respective classes.Type Meaning
boolean Represents true/false values
byte 8 bit integer (whole number)
char 16 bit Unicode character
double 64 bit double-precision floating point value
float 32 bit single-precision floating point value
int 32 bit integer (whole number)
long 64 bit integer (whole number)
short 16 bit integer (whole number)
INTEGER TYPES
Whole numbers either positive or negative. Java does not support unsigned integers.
Type Range Size
byte -128 to 127 Signed 8-bit
integer
short -32,768 to 32,767 Signed 16-bit
integer
int -2,147,483,648 to
2,147,483,647
Signed 32-bit
integer
long -9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
Signed 64-bit
integerNote: Although char is technically an integer, its use is to represent charactersand will be discussed separately.
FLOATING-POINT TYPES
Floating-point types represent numbers with a fractional component.
May be either positive or negative.
Type Approximate range
Precision
Size
float -3.4*1038 to +3.4*1038 6-7 digits Signed 32-
bit
doubl
e
-1.70*10308 to
+1.7*10308
15-16 digits Signed 64-
bit
CHARACTER DATA TYPE
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;
BOOLEAN DATA TYPE
Represents a true/false value. You cannot use yes/no, 0/1, on/off. Outcome of all relational operations is a
boolean value.
LITERALS
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, OCTAL, AND BINARY LITERALS
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
CHARACTER ESCAPE SEQUENCES
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.
CHARACTER ESCAPE SEQUENCES
Escape Sequence
Description
\’ single quote
\” double quote
\\ backslash
\r carriage return
\n new line
\f form feed
\t horizontal tab
\b backsapce
\ddd octal constant where ddd is the octal value
\uxxxx hexadecimal constant where xxxx is a hexadecimal value
STRING LITERALS
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
Variables hold data that can change during program execution.
Variables must be declared before you can use them.
Declaration: dataType identifier; Example: double interestRate; int numberStudents; char middleInitial;
INITIALIZING A VARIABLE
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’;
INITIALIZING A VARIABLE
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;
DYNAMIC INITIALIZATION
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;
THE SCOPE AND LIFETIME OF VARIABLES 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.
THE SCOPE AND LIFETIME OF VARIABLESpublic 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
Operators are symbols that tell the compiler to perform a specific mathematical or logical operation. Arithmetic Increment/Decrement Relational Logical Short Circuit Assignment
ARITHMETIC OPERATORS
Operator
Meaning
+ Addition (also unary plus)
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus (remainder)
++ Increment (by a value of 1)
-- -- Decrement (by a value of 1)
RELATIONAL OPERATORS
Operator
Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
LOGICAL OPERATORS
Operator
Meaning
& 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
SHORT CIRCUIT OPERATORS
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 < 12 || 6 > 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.
SHORT CIRCUIT OPERATORS
if (10 < 12 && 3 > 3 && 9 == 10) 10 < 12 is true; but 3 > 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
The assignment operator (=) assigns the value on the right side of the operator to the variable on the left.
Format: resultVariable = someValue;
SHORTHAND ASSIGNMENTS
Simplifies coding of certain assignment statements.
Operator
Shorthand Longhand
+= x += 5 x = x + 5
-= x -=5 x = x – 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
%= x %= 5 x = x % 5
TYPE CONVERSION IN ASSIGNMENTS
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.
CASTING INCOMPATIBLE 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).
CASTING EXAMPLESdouble 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 Xch = (char) b; // Cast between incompatible types.
OPERATOR PRECEDENCE
Operators Precedence (highest to lowest)
postfix expr++ 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 = += -= *= /= %= &= ^= |= <<= >>= >>>=
OPERATOR PRECEDENCE
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
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
TYPE CONVERSION IN EXPRESSIONS
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.
SPACING AND PARENTHESIS
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.