32
Java Primitives Java Primitives The Smallest Building The Smallest Building Blocks of the Language Blocks of the Language (corresponds with Chapter (corresponds with Chapter 2) 2)

Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Embed Size (px)

Citation preview

Page 1: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Java PrimitivesJava Primitives

The Smallest Building Blocks The Smallest Building Blocks of the Languageof the Language

(corresponds with Chapter 2)(corresponds with Chapter 2)

Page 2: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

TerminologyTerminology Primitive Data TypePrimitive Data Type – a category of data. A description of – a category of data. A description of

how the computer will treat bits found in memory.how the computer will treat bits found in memory. VariableVariable – a named location in memory, treated as a – a named location in memory, treated as a

particular data type, whose contents can be changed.particular data type, whose contents can be changed. ConstantConstant – a named location in memory, treated as a – a named location in memory, treated as a

particular type, whose contents cannot be changed.particular type, whose contents cannot be changed. DeclarationDeclaration – the act of creating a variable or constant and – the act of creating a variable or constant and

specifying its type.specifying its type. Literal Literal – a hard-coded piece of data, part of the statement – a hard-coded piece of data, part of the statement

and not based on a variable or constant declaration.and not based on a variable or constant declaration. OperatorOperator – a symbol that describe how to manipulate data – a symbol that describe how to manipulate data

and variables in memoryand variables in memory ExpressionExpression – a combination of operators, variables, – a combination of operators, variables,

constants and/or literals that produces a resulting piece of constants and/or literals that produces a resulting piece of datadata

AssignmentAssignment – copying the results of an expression into a – copying the results of an expression into a variable.variable.

StatementStatement – a program instruction telling the CPU what to – a program instruction telling the CPU what to do. (All statements end with semicolon).do. (All statements end with semicolon).

Page 3: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Java Primitive Data typesJava Primitive Data typesJava Primitive Data typesJava Primitive Data types booleanboolean -- true/false -- true/false char char -- Unicode -- Unicode

character (good for character (good for internationalization)internationalization)

bytebyte -- 8-bit signed -- 8-bit signed integerinteger

shortshort --16-bit signed --16-bit signed integerinteger

int int -- 32-bit signed -- 32-bit signed integerinteger

longlong -- 64-bit -- 64-bit signed integersigned integer

float float -- 32-bit -- 32-bit floating point floating point numbernumber

doubledouble -- 64-bit -- 64-bit floating point nbrfloating point nbr

Page 4: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

IdentifiersIdentifiers Identifier = the Identifier = the namename of a variable, constant, class, or of a variable, constant, class, or

methodmethod Rules for using identifiers:Rules for using identifiers:

An identifier must start with a letter, an underscore, or a dollar An identifier must start with a letter, an underscore, or a dollar sign.sign.

An identifier cannot contain operators, such asAn identifier cannot contain operators, such as+, -, and so on.+, -, and so on.

An identifier cannot be a reserved word. (See Appendix A, “Java An identifier cannot be a reserved word. (See Appendix A, “Java Keywords,” for a list of reserved words).Keywords,” for a list of reserved words).

An identifier cannot beAn identifier cannot be truetrue, , falsefalse, or, ornullnull..

An identifier can be of any length.An identifier can be of any length.

Page 5: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Declaring VariablesDeclaring Variables

int x; // declares x to be anint x; // declares x to be an

// integer variable;// integer variable;

double radius; // declares radius todouble radius; // declares radius to

// be a double variable;// be a double variable;

char a; // declares a to be achar a; // declares a to be a

// character variable;// character variable;

General format:

datatype identifier;

Declaring multiple variables of the same type:

datatype identifier1, identifier2,

identifier3;

Page 6: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Assignment StatementsAssignment Statements

x = 1; // Assign 1 to x;x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;radius = 1.0; // Assign 1.0 to radius;

a = 'A'; // Assign 'A' to a;a = 'A'; // Assign 'A' to a;

General format:

VariableIdentifier = expression;

These expressions are all just Literals!

Note: the = sign is an assignment operator. It is NOT a test for equality.

Page 7: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Declaring and InitializingDeclaring and Initializingin One Stepin One Step

int x = 1;int x = 1;

double d = 1.4;double d = 1.4;

float f = 1.4f;float f = 1.4f;

char a = ‘a’;char a = ‘a’;

Note: character literals are enclosed in single quotes

NOTE: by default floating NOTE: by default floating point literals are assumed to point literals are assumed to be doubles. If you want to be doubles. If you want to assign a floating point literal assign a floating point literal to a float variable, you must to a float variable, you must append the “f” to the end of append the “f” to the end of the number.the number.

declaration

assignment

Page 8: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

ConstantsConstants

final datatype CONSTANTNAME = VALUE; final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159; final double PI = 3.14159;

final int SIZE = 3;final int SIZE = 3;

The final modifier indicates that the identifier refers to a constant, not a variable. Constants must be initialized when declared.

Page 9: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Numeric LiteralsNumeric Literals int i = 34;int i = 34;

long l = 1000000;long l = 1000000;

float f = 100.2f;float f = 100.2f; or orfloat f = 100.2F;float f = 100.2F;

double d = 100.2ddouble d = 100.2d or ordouble d = 100.2D;double d = 100.2D;

Page 10: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Common Types of Common Types of OperatorsOperators

AssignmentAssignment ==

ArithmeticArithmetic ++ -- ** // %%

ComparisonComparison == == << > > <= <= >= >= !=!=

LogicalLogical &&&& |||| !! ^̂

equals

ANDOR

NOT

not equals

modulus

ExclusiveOR

Page 11: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Modulus (remainder) Modulus (remainder) OperatorOperator

Modulus is very useful in programming. For Modulus is very useful in programming. For example, an even number % 2 is always 0 and example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use an odd number % 2 is always 1. So you can use this property to determine whether a number is this property to determine whether a number is even or odd. Suppose you know January 1, 2005 even or odd. Suppose you know January 1, 2005 is Saturday, you can find that the day for is Saturday, you can find that the day for February 1, 2005 is Tuesday using the following February 1, 2005 is Tuesday using the following expression: expression:

Saturday is the 6th day in a week A week has 7 days

January has 31 days The 2nd day in a week is Tuesday

(6 + 31) % 7 is 2

Page 12: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Common Types of Common Types of ExpressionsExpressions

ArithmeticArithmetic Combine numeric data with arithmetic Combine numeric data with arithmetic

operatorsoperators Return a numberReturn a number

ConditionalConditional Combine boolean values with logical operatorsCombine boolean values with logical operators Boolean values can be derived from Boolean values can be derived from

comparison operators or boolean data valuescomparison operators or boolean data values Returna boolean valueReturna boolean value

Page 13: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Arithmetic ExpressionsArithmetic Expressions

1 + 11 + 1 x * yx * y 5 / 25 / 2 5 % 25 % 2 radius*radius*3.14159radius*radius*3.14159

Page 14: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Sample Statements with Sample Statements with Arithmetic ExpressionsArithmetic Expressions

//Compute the first area//Compute the first area

radius = 1.0;radius = 1.0;

area = radius*radius*3.14159;area = radius*radius*3.14159;

//Compute the second area//Compute the second area

radius = 2.0;radius = 2.0;

area = radius*radius*3.14;area = radius*radius*3.14;

Page 15: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Arithmetic ExpressionsArithmetic Expressions

)94

(9))(5(10

5

43

y

x

xx

cbayx

is translated to

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

Page 16: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Shortcut OperatorsShortcut Operators

Operator Example Equivalent

+= i+=8 i = i+8

-= f-=8.0 f = f-8.0

*= i*=8 i = i*8

/= i/=8 i = i/8

%= i%=8 i = i%8

Page 17: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Increment andIncrement andDecrement OperatorsDecrement Operators

x = 1;x = 1; x++;x++; ++x;++x; x--;x--; --x;--x;

y = 2 + x++;y = 2 + x++;

y = 2 + ++x;y = 2 + ++x; y = 2 + x--;y = 2 + x--;

y = 2 + --x;y = 2 + --x;

Add 1 to x

Subtract 1 from x

X is incremented after adding to 2

X is incremented before adding to 2

X is decremented after adding to 2

X is decremented before adding to 2

Page 18: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Increment andIncrement andDecrement Operators, Decrement Operators,

cont.cont.

int i = 10; int newNum = 10 * i++;

int newNum = 10 * i; i = i + 1;

Same effect as

int i = 10; int newNum = 10 * (++i);

i = i + 1; int newNum = 10 * i;

Same effect as

Page 19: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Integer vs. Floating Point Integer vs. Floating Point DivisionDivision

When performing operations involving two operands of different When performing operations involving two operands of different types, Java automatically converts the operand of a smaller types, Java automatically converts the operand of a smaller range to the data type of the larger range.range to the data type of the larger range.

Example:Example:

1/21/2 this will give 0 because both operands are integer this will give 0 because both operands are integer

1.0/21.0/2 or or 1/2.01/2.0 this will give 0.5 because the floating this will give 0.5 because the floating point literal is a double, so the integer literal (long) will be point literal is a double, so the integer literal (long) will be converted to a double; thus floating point division will take converted to a double; thus floating point division will take place.place.

Page 20: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Character Data TypeCharacter Data Type char letter = 'A'; char letter = 'A';

char letter = '\u00041';char letter = '\u00041';

char numChar = '4';char numChar = '4';

Unicode representation

Java uses Unicode instead of ASCII for character data representation

Page 21: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Character Escape Character Escape SequencesSequences

Backspace \b

Tab \t

Linefeed \n

Carriage return \r

Backslash \\

Single quote \'

Double quote \"

Page 22: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

The The booleanboolean Data Type Data Type boolean lightsOn = true;boolean lightsOn = true;

boolean lightsOn = false;boolean lightsOn = false;

boolean test = 1==1;boolean test = 1==1;

Returns Returns truetrue

boolean test = 1==2;boolean test = 1==2;

Returns Returns falsefalse

comparison expressions

Page 23: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

The + symbol as The + symbol as concatenation operatorconcatenation operator

System.out.println("The area is System.out.println("The area is " "

+ area + area

+ " for radius " + " for radius "

+ radius);+ radius);

String literals are enclosed in double quotes

Here, the + is used to concatenate strings together

Page 24: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Boolean Operators Boolean Operators RevisitedRevisited

Operator Name

! not

&& and

|| or

^ exclusive or

Page 25: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Truth Table for Operator !Truth Table for Operator !

p !p

true false

false true

Example

!(1 > 2) is true, because (1 > 2) is false.

!(1 > 0) is false, because (1 > 0) is true.

Page 26: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Truth Table for Operator Truth Table for Operator &&&&

p1 p2 p1 && p2

false false false

false true false

true false false

true true true

Example

(3 > 2) && (5 >= 5) is true, because (3 > 2) and (5 >= 5) are both true.

(3 > 2) && (5 > 5) is false, because (5 > 5) is false.

Page 27: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Truth Table for Operator ||Truth Table for Operator ||

p1 p2 p1 || p2

false false false

false true true

true false true

true true true

Example

(2 > 3) || (5 > 5) is false, because (2 > 3) and (5 > 5) are both false.

(3 > 2) || (5 > 5) is true, because (3 > 2) is true.

Page 28: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Truth Table for Operator ^Truth Table for Operator ^

p1 p2 p1 ^ p2

false false false

false true true

true false true

true true false

Example

(2 > 3) ^ (5 > 1) is true, because (2 > 3) is false and (5 > 1) is true.

(3 > 2) ^ (5 > 1) is false, because both (3 > 2) and (5 > 1) are true.

Page 29: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Numeric Type ConversionNumeric Type Conversion

Consider the following statements:Consider the following statements:

byte i = 100;byte i = 100;

long k = i * 3 + 4;long k = i * 3 + 4;

double d = i * 3.1 + k / 2;double d = i * 3.1 + k / 2;

Page 30: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Conversion RulesConversion RulesWhen performing a binary operation involving When performing a binary operation involving two operands of different types, Java two operands of different types, Java automatically converts the operand based on automatically converts the operand based on the following rules:the following rules:  1.    If one of the operands is double, the other is 1.    If one of the operands is double, the other is converted into double.converted into double.2.    Otherwise, if one of the operands is float, 2.    Otherwise, if one of the operands is float, the other is converted into float.the other is converted into float.3.    Otherwise, if one of the operands is long, 3.    Otherwise, if one of the operands is long, the other is converted into long.the other is converted into long.4.    Otherwise, both operands are converted 4.    Otherwise, both operands are converted into int.into int.

Page 31: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Type CastingType Casting

Implicit castingImplicit casting

double d = 3; (type widening)double d = 3; (type widening)

Explicit castingExplicit casting

int i = int i = (int)(int)3.0; (type narrowing)3.0; (type narrowing)

int i = int i = (int)(int)3.9; (Fraction part 3.9; (Fraction part is truncated) is truncated)

Cast operator

Page 32: Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)

Operator PrecedenceOperator Precedence CastingCasting ++++,, -- -- **,, / /,, % % ++,, - - <<,, <= <=,, > >,, => => ====,, !=; !=; &&&& |||| ==,, += +=,, -= -=,, *= *=,, /= /=,, %= %=

first

last

Parentheses can be used to override normal precedence