You are on page 1of 61

Page 1 of 61

Chapter 3. Operators and Assignments


Exam Objectives

instanceof

equals(Object)
java.lang.String java.lang.Boolean
java.lang.Object

! " " & | && || " # $


" $ " " !

" " "

Supplementary Objectives

% "

$ " " " $ "


$ "

&
! $

% " "
! " "

3.1 Precedence and Associativity Rules for Operators


' " " !
( )* +

$ # ) *,

$ $

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 2 of 61

- $ $ "

' ( ) " "

$ + ! ++
-- $ ! + - ++ -- ~ !
$ ! new ( )
$

? : +

. " + $

. !
"

/! !

' ! [] . (parameters) expression++ expression--

% ! ++expression --expression +expression -expression ~ !

% ! new (type)

0 " * / %

. " + -

& << >> >>>

1 < <= > >= instanceof

/+ == !=

$ 2 .3 &

$ 2 4-1 ^

$ 2 -1 |

5 .3 &&

5 -1 ||

5 ?:

. = += -= *= /= %= <<= >>= >>>= &= ^= |=

$ $
$ $ !
$

2 + 3 * 4 " 2 + (3 * 4) $ 14 * +

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 3 of 61

$ $
$ $ !

1 + 2 - 3 ((1 + 2) - 3) + - "
"

- - 4 (- (- 4)) $ 4 -
"

"

3.2 Evaluation Order of Operands

6" "

6" "
! 7 && || ?:

7 ! & 88
*9* 7 " " 7 "
" 7 : ! $
,

int b = 10;
System.out.println((b=3) + b);

" $ 6 13 " $,

(b=3) + b
3 + b b " )
3 + 3
6

" "

/! $ "
& ); )<

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 4 of 61

3.3 Conversions
$ # " ! $
& " ! $
& " # "
$ $ + ! #

Unary Cast Operator: (type)

6" # #
" ! =$ " #
! $
! $ $ " !
double int 6" ! "
$ !,

(> ?) > ?

( ) " . $
" $ " @
! "

5 " " $ 5 $ "


" "
" " null

/! $ " " 5 $
& AA BA;

Narrowing and Widening Conversions


: " " ! " "
$ !
@ " ! " ( :
)* " $ " : ! int "
double $ " " long float

5 " $ !
$ . " $

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 5 of 61

$ " : )* $ " 3 "


$ char $ byte short $ " ,
" $ char byte
short

" !
& AA 5 " !
# 5 " ! !
# !

$ $ " ! +
@ " $ $ " +
$ " =$ " $
" +

Numeric Promotions

3 $ 3
" $

Unary Numeric Promotion

$ int "
int $ " " C $ "

$ " byte short char int


$ "

% $ ! ,

+ - & )8 8*

$ ~ & ) *) <8

C ! new int[20] $ !
20 " int " & ;* *D*

! C ! table['a'] $ ! !
'a' " int " & ;* *D)

" << >> >>> & ) *; <E

Binary Numeric Promotion

$ " "
" $ $ $ int F " T
$ $

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 6 of 61

T int " TC $
" int

byte short char $ " int

$ ! ,

* / % + - & )8 8*

< <= > >= & )E A<

+ == != & ) *D A<

$ & ^ | & ) *) <8

Type Conversion Contexts


" $ ! ,

" " " & ); ;9


& AA BAD

" " " & ) *< 9A


& AA BAD

" " & )8 8<

" " String & )A


AB

3.4 Simple Assignment Operator =


$ !,

$ G #
" " " " $ =

" " & " " "


" " "

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 7 of 61

Assigning Primitive Values


$ ! " " ,

int j, k;
j = 10; // j gets the value 10.
j = 5; // j gets the value 5. Previous value is overwritten.
k = j; // k gets the value 5.

$ $ ! 7
"

int i;
i = 5; // i gets the value 5.
i = i + 1; // i gets the value 6. + has higher precedence than =.
i = 20 - i * 2; // i gets the value 8: (20 - (i * 2))

Assigning References
5 $ & *) 8
$ ! ,

Pizza pizza1 = new Pizza("Hot&Spicy");


Pizza pizza2 = new Pizza("Sweet&Sour");

pizza2 = pizza1;

H pizza1 (( pizza2 ((
$ $ . pizza1 pizza2 pizza2 $
(( pizza1 . "
Pizza

. "
7 1
" 7
" " 7 " 7

. & AA

Multiple Assignments
$
" ! 7

int j, k;
j = 10; // j gets the value 10 which is returned
k = j; // k gets the value of j, which is 10, and this value is returned

$ $ "

k = j = 10; // (k = (j = 10))

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 8 of 61

0 + " $

Pizza pizzaOne, pizzaTwo;


pizzaOne = pizzaTwo = new Pizza("Supreme"); // Aliases.

$ ! $ " ,

int[] a = {10, 20, 30, 40, 50}; // an array of int


int index = 4;
a[index] = index = 2;

@ " index $ a[index] "


I " $,

a[index] = index = 2;
a[4] = index = 2;
a[4] = (index = 2); // index gets the value 2. = is right associative.
a[4] = 2; // The value of a[4] is changed from 50 to 2.

Numeric Type Conversions on Assignment


" "
" " - $
$ " " $ "
!

// Implicit Widening Primitive Conversions


int smallOne = 1234;
long bigOne = 2000; // Implicit widening: int to long.
double largeOne = bigOne; // Implicit widening: long to double.
double hugeOne = (double) bigOne; // Cast redundant but allowed.

" $ 7 " '


" $ $
$ " ! !
long " $ " float "

long bigInteger = 98765432112345678L;


float realNo = bigInteger; // Widening but loss of precision: 9.8765436E16

. $ " " $
$ ,

byte short char int

byte short char

"

// Above conditions fulfilled for implicit narrowing primitive conversions.


short s1 = 10; // int value in range.
short s2 = 'a'; // char value in range.

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 9 of 61

char c1 = 32; // int value in range.


char c2 = (byte)35; // byte value in range. int value in range, without cast.
byte b1 = 40; // int value in range.
byte b2 = (short)40; // short value in range. int value in range, without cast.
final int i1 = 20;
byte b3 = i1; // final value of i1 in range.

// Above conditions not fulfilled for implicit narrowing primitive conversions.


// Explicit cast required.
int i2 = -20;
final int i3 = i2;
final int i4 = 200;
short s3 = (short) i2; // Not constant expression.
char c3 = (char) i3; // final value of i3 not determinable.
char c4 = (char) i2; // Not constant expression.
byte b4 = (byte) 128; // int value not in range.
byte b5 = (byte) i4; // final value of i4 not in range.

. $ " " $ 7 $
! +

: 7 " $ " "

// Explicit narrowing primitive conversions requiring cast.


// The value is truncated to fit the size of the destination type.
float huge = (float) 1.7976931348623157d; // double to float.
long giant = (long) 4415961481999.03D; // (1) double to long.
int big = (int) giant; // (2) long to int.
short small = (short) big; // (3) int to short.
byte minute = (byte) small; // (4) short to byte.
char symbol = (char) 112.5F; // (5) float to char.

)B $ $ " # * 8 "

! "
# $

0000000000000000000001000000010000101011110100001100001100001111 4415961481999 (1)


00101011110100001100001100001111 735101711 (2)
1100001100001111 -15601 (3)
00001111 15 (4)
0000000001110000 'p' (5)

" "
" & ) *9 99 ! $ " $ $
+

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 10 of 61

Review Questions

F" char c = 'A';

@ $ " " c intI

& $

int i = c;

int i = (int) c;

int i = Character.getNumericValue(c);

@ $ $ I

public class Assignment {


public static void main(String[] args) {
int a, b, c;
b = 10;
a = b = c = 20;
System.out.println(a);
}
}

& $

$ $ ( " c
a = b = c = 20; (

$ a = b = c = 20;

$ $ 10 $

$ $ 20 $

@ $ $ I

public class MyClass {


public static void main(String[] args) {
String a, b, c;
c = new String("mouse");
a = new String("cat");
b = a;
a = new String("dog");
c = b;

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 11 of 61

System.out.println(c);
}
}

& $

$ mouse $

$ cat $

$ dog $

$ cat dog $

3.5 Arithmetic Operators: *, /, %, +, -


!
$ char

Arithmetic Operator Precedence and Associativity


)) $
$ %
$ " "
" " "
" "

% &
% + -

* $ / % %
+ -

Evaluation Order in Arithmetic Expressions

6" "
- " ! +
$ "

! a + b * c a$ $ " b,

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 12 of 61

$ $ $ " c. = $ " *
$ + 3 a b
c ! "

Range of Numeric Values


. $ " " " " & BB B9
" MAX_VALUE MIN_VALUE $
$

" "
: 7
7 $

H 7 7 " !
$ 7

Integer Arithmetic

$ " ! "
( ( $ ArithmeticException " /
% $ ." "
$ ! ,

int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is Integer.MIN_VALUE.


int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is Integer.MAX_VALUE.

" " 7 7 =$ " !


7 7 " $
7 7 " ! # $ long
! " $ long ,

long notTooBig = Integer.MAX_VALUE + 1L; // 2147483648L in range.


long notTooSmall = Integer.MIN_VALUE - 1L; // -2147483649L in range.

Floating-point Arithmetic

5 7 " 7 7
$ " 7 7 7 " $
& : )B . 7 " (
! $ $ $ "

System.out.println( 4.0 / 0.0); // Prints: Infinity


System.out.println(-4.0 / 0.0); // Prints: -Infinity

! ' ( ! ' ) % &

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 13 of 61

" " ! "


double float : )B &
POSITIVE_INFINITY NEGATIVE_INFINITY $ java.lang.Float
java.lang.Double . " $ " $

: 7 ! ( "
double float : )B % $ $ ,

$ Double.MIN_VALUE Float.MIN_VALUE ( C !
(5.1E-324 - 4.9E-324) % $ " ( 0.0 0.0F

$ -Double.MIN_VALUE -Float.MIN_VALUE ( C !
(-Double.MIN_VALUE * 1E-1) % $ " ( -0.0 -
0.0F

3 " ( + " ( -0.0 == 0.0 true

5 " '' 3 3
! + 7* . ! 7 " (
( ,

System.out.println(0.0 / 0.0); // Prints: NaN

33 NaN $ java.lang.Float
java.lang.Double . " " 33 33 . !
+ != " " 33 " 33 false . +
3 3$ " 33 $ true = $ "
$ # " 33 isNaN()
$ java.lang.Float java.lang.Double

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 14 of 61

Strict Floating-Point Arithmetic: strictfp

. 7 6" $ ///7<8;)B7
float A;7 double $6
H0
! 7
" 6
H0 $ & " (

6
H0 # $ strictfp
" 7 strictfp
. strictfp !
strictfp (
! !
strictfp ! =$ "
5 ! $ "

Unary Arithmetic Operators: -, +

"
- " $ !
" ,

int value = - -10; // (-(-10)) is 10

3 # C $ $
-- & )< A) J
" "

=$ " BK & F;
8E9

Multiplicative Binary Operators: *, /, %

Multiplication Operator: *

0 L $

int sameSigns = -4 * -8; // result: 32


double oppositeSigns = 4.0 * -8.0; // result: -32.0
int zero = 0 * -0; // result: 0

Division Operator: /

" / "

int i1 = 4 / 5; // result: 0
int i2 = 8 / 8; // result: 1
double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value 1.0.

" $ + " $
( 3 " " " " "

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 15 of 61

$ 7

. ArithmeticException $ $ " $ (
" (

7 (

double d2 = 4.0 / 8; // result: 0.5


double d3 = 8 / 8.0; // result: 1.0
double d4 = 12.0F / 8; // result: 1.5F

double result1 = 12.0 / 4.0 * 3.0; // ((12.0 / 4.0) * 3.0) which is 9


double result2 = 12.0 * 3.0 / 4.0; // ((12.0 * 3.0) / 4.0) which is 9

Remainder Operator: %

$ $ " " "


! + : ! " < 8
+ * B %
"

int quotient = 7 / 5; // Integer division operation: 1


int remainder = 7 % 5; // Integer remainder operation: 2

: $ " " "


! (x % y) $ $ ,

MM 2 L J N

$ 7 " $ + " "


$ ! $ $$ "
,

5 < N 8,

7 == (7 / 5) * 5 + (7 % 5)
== ( 1 ) * 5 + (7 % 5)
== 5 + (7 % 5)
2 == (7 % 5) <N 8 + B

5 < N 78 ,

7 == (7 / -5) * -5 + (7 % -5)
== ( -1 ) * -5 + (7 % -5)
== 5 + (7 % -5)
2 == (7 % -5) < N 78 + B

5 7< N 8 ,

-7 == (-7 / 5) * 5 + (-7 % 5)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 16 of 61

== ( -1 ) * 5 + (-7 % 5)
== -5 + (-7 % 5)
-2 == (-7 % 5) i.e., (-7 % 5) is equal to -2

5 7< N 78 ,

-7 == (-7 / -5) * -5 + (-7 % -5)


== ( 1 ) * -5 + (-7 % -5)
== -5 + (-7 % -5)
-2 == (-7 % -5) i.e., (-7 % -5) is equal to -2

" $ " " "


" " . 7 " " " "
$ ,
" "

int r0 = 7 % 7; // 0
int r1 = 7 % 5; // 2
long r2 = 7L % -5L; // 2L
int r3 = -7 % 5; // -2
long r4 = -7L % -5L; // -2L
boolean relation = -7L == (-7L / -5L) * -5L + r4; // true

. ArithmeticException $ $ $ (

3 7
$ ( r ,

MM 7 L)

$ a b " " " q + (a/b)


$ ! 7 ,

double dr0 = 7.0 % 7.0; // 0.0


float fr1 = 7.0F % 5.0F; // 2.0F
double dr1 = 7.0 % -5.0; // 2.0
float fr2 = -7.0F % 5.0F; // -2.0F
double dr2 = -7.0 % -5.0; // -2.0
boolean fpRelation = dr2 == (-7.0) - (-5.0) * (long)(-7.0 / -5.0); // true
float fr3 = -7.0F % 0.0F; // NaN

Additive Binary Operators: +, -

J 7 " ,
" J
& )A AB

. " " $ );
! $ $ " !
"

* !% &

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 17 of 61

% & , & +
3 + 2 - 1 ((3 + 2) - 1) 4
2 + 6 * 7 (2 + (6 * 7)) 44
-5+7- -6 (((-5)+7)-(-6)) 8
2+4/5 (2+(4/5)) 2
13 % 5 (13 % 5) 3
11.5 % 2.5 (11.5 % 2.5) 1.5
10 / 0 ArithmeticException

2+4.0/5 (2.0+(4.0/5.0)) 2.8


4.0 / 0.0 (4.0 / 0.0) Infinity
-4.0 / 0.0 ((-4.0) / 0.0) -Infinity
0.0 / 0.0 (0.0 / 0.0) NaN

Numeric Promotions in Arithmetic Expressions


% - +
$ $ byte short char
" int $ " int "
$ " ;9 int
" $ + ! $
! $ byte b int ! (-b),

byte b = 3; // int literal in range. Implicit narrowing.


b = (byte) -b; // Explicit narrowing on assignment required.

$
$ int $ : ! * /! )*
$ : )) 3 " " ! (c / s)

+ % &

public class NumPromotion {


public static void main(String[] args) {
byte b = 32;
char c = 'z'; // Unicode value 122 (\u007a)
short s = 256;
int i = 10000;
float f = 3.5F;
double d = 0.5;
double v = (d * i) + (f * - b) - (c / s); // (1) 4888.0D
System.out.println("Value of v: " + v);
}
}

- ,

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 18 of 61

Value of v: 4888.0

+ % &

! "
" $ " "

byte b = 10;
short s = 20;
char c = 'z'; // 122 (\u007a)
int i = s * b; // Values in s and b converted to int.
long n = 20L + s; // Value in s converted to long.
float r = s + c; // Values in s and c promoted to int, followed by implicit
// widening conversion of int to float on assignment.
double d = r + i; // value in i promoted to float, followed by implicit
// widening conversion of float to double on assignment.

byte short char


int .
$ ! "

short h = 40; // OK: int converted to short. Implicit narrowing.


h = h + 2; // Error: cannot assign an int to short.

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 19 of 61

" ! h + 2 int . !
short + !

h = (short) (h + 2); // OK

3 int " 2 $ #,

h = h + (short) 2; // Requires an additional cast.

int " "


! 7 + $
short "

Arithmetic Compound Assignment Operators: *=, /=, %=, +=, -=

. $ !,

$ ,

= (> ?) ( ( ))

> ? " 3
= =
)* " $
6" $ ! 7
" )8

- % & %
. / T & !x0 & 1 .

x *= a x = (T) ((x) * (a))


x /= a x = (T) ((x) / (a))
x %= a x = (T) ((x) % (a))
x += a x = (T) ((x) + (a))
x -= a x = (T) ((x) - (a))

(T) $
$ $ ! ,

int i = 2;
i *= i + 4; // (1) Evaluated as i = (int) (i * (i + 4)).

byte b = 2;
b += 10; // (2) Evaluated as b = (byte) ((int) b + 10).

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 20 of 61

b = b + 10; // (3) Will not compile. Explicit cast required.

. * int " int "


" &
=$ " B " int " byte " b int
byte " +
$ " ) $ $
$

" ! $
$ a[i]
" ,

a[i] += 1;

$ "
& )< A)

- & ) ** <* $
& ) *) <9 & ) *; 9)

Review Questions

* @ $ ! $ " 7 I

& $

2.0 * 3.0

2 * 3

2/3 + 5/7

2.4 + 1.6

0x10 * 1L * 300.0

- @ " ! (1 / 2 + 3 / 2 + 0.1)I

& $

**

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 21 of 61

*A

B*

2 @ $ $ I

public class Integers {


public static void main(String[] args) {
System.out.println(0x10 + 10 + 010);
}
}

& $

$ $ !
0x10 + 10 + 010

@ $ 28

@ $ 30

@ $ 34

@ $ 36

! @ $ 101010

3 @ $ ! " I

& $

(- 1 -)

(+ + 1)

(+-+-+-1)

(--1)

(1 * * 1)

! (- -1)

4 @ " " $ ! - -1-3 * 10 / 5-1 I

& $

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 22 of 61

O9

OA

<

*D

! 3 "

5 @ " I

& $

short s = 12;

long l = 012;

int other = (int) true;

float f = -123;

double d = 0x12345678;

3.6 The Binary String Concatenation Operator +


J "
@ String
" 3 7String
" $,

: " " " String $


"

H # true false null


. " $ " null "null"
!

: "
toString() 0 "
Object "
toString() & *D B

$ $ String String
& *D 8

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 23 of 61

String theName = " Uranium";


theName = " Pure" + theName; // " Pure Uranium"
String trademark1 = 100 + "%" + theName; // "100% Pure Uranium" (1)

100 " "100"


" $ Integer $
100 toString()
,

new Integer(100).toString();

3 '%' "%" * "


" ,

String trademark2 = 100 + '%' + theName; // "137 Pure Uranium"

J , 100 + '%' (100 + 37) 5


! J $ $
! ,

System.out.println("We put two and two together and get " + 2 + 2);

" "We put two and two together and get 22" "We put two
and two together and get 4" 2 String "2"
String "We put two and two together and get
2" $ String "2" $
$,

"We put two and two together and get " + 2 + 2


"We put two and two together and get " + "2" + 2
"We put two and two together and get 2" + 2
"We put two and two together and get 2" + "2"
"We put two and two together and get 22"

+ .
"

System.out.println("We put two and two together and get " + (2 + 2));

" " String $


+ ! & *D A ;B;

3.7 Variable Increment and Decrement Operators: ++, --


H ++ -- $ " ,
" " $
" " "

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 24 of 61

" " $

Increment Operator ++

' ! $ ,

++i 1 i $" i " !


+ " $

i += 1;
result = i;
return result;

' ! $ ,

j++ " j " ! 1 j.


+ " $ ,

result = j;
j += 1;
return result;

Decrement Operator --

' ! $ ,

--i 1 i $" i "


! .

' ! $ ,

j-- " j " ! 1


j.

Examples of Increment and Decrement Operators

// (1) Prefix order: increment operand before use.


int i = 10;
int k = ++i + --i; // ((++i) + (--i)). k gets the value 21 and i becomes 10.
--i; // Only side effect utilized. i is 9. (expression statement)

// (2) Postfix order: increment operand after use.


long i = 10;
long k = i++ + i--; // ((i++) + (i--)). k gets the value 21L and i becomes 10L.
i++; // Only side effect utilized. i is 11L. (expression statement)

. $ !
& ;) **)

/! * $ ,

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 25 of 61

k = ((++i) + (--i)) Operands are determined.


k = ( 11 + (--i)) i now has the value 11.
k = ( 11 + 10) i now has the value 10.
k = 21

/! $ " " "


" $

@ F" a " $
$ (++(++a)) ++ " "
" (++a) "

$ char byte short


$ " " "
! $ int " (++b) 11 int " i
" byte " b +
int $ $ " int " byte

byte b = 10;
int i = ++b; // i is 11, and so is b.

7
! $ JJ " $

double x = 4.5;
x = x + ++x; // x gets the value 10.0.

Review Questions

6 @ I

& $

! (1 + 2 + "3") $ "33"

! ("1" + 2 + 3) $ "15"

! (4 + 1.0f) $ float " 5.0f

! (10/9) $ int " 1

! ('a' + 1) $ char " 'b'

@ $ $ I

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 26 of 61

public class Prog1 {


public static void main(String[] args) {
int k = 1;
int i = ++k + k++ + + k;
System.out.println(i);
}
}

& $

$ $ !
++k + k++ + + k

$ $ " 3$

$ $ " 4$

$ $ " 7$

$ $ " 8$

@ $ $
I

public class MyClass {


public static void main(String[] args) {
char c;
int i;
c = 'a'; // (1)
i = c; // (2)
i++; // (3)
c = i; // (4)
c++; // (5)
}
}

& $

! 3 $

@ $ $ I

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 27 of 61

public class Cast {


public static void main(String[] args) {
byte b = 128;
int i = b;
System.out.println(i);
}
}

& $

$ byte int
$

$ $ 128 $

$ 128
" byte

$ $ $ ClassCastException $

$ $ 255 $

* @ $ $ $ I

public class EvaluationOrder {


public static void main(String[] args) {
int[] array = { 4, 8, 16 };
int i=1;
array[++i] = --i;
System.out.println(array[0] + array[1] + array[2]);
}
}

& $

13

14

20

21

24

3.8 Boolean Expressions

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 28 of 61

! " boolean " " true false

! $ $ $
!

! & )E A< )
& ) *D A< & ) ** <D
& ) *B <B & ); ;<
instanceof & AA BA;

3.9 Relational Operators: <, <=, >, >=


F" a b !
$ )A

2 ,
a < b a bI
a <= b a + bI
a > b a bI
a >= b a + bI

. !
"
boolean " 1 " $

double hours = 45.5;


boolean overtime = hours >= 35.0; // true.
boolean order = 'A' < 'a'; // true. Binary numeric promotion applied.

1 " 0 ! # $
2

int a = 1, b = 7, c = 10;
boolean valid1 = a <= b <= c; // (1) Illegal.
boolean valid2 = a <= b && b <= c; // (2) OK.

& " " " ! a <= b <= c


* ! " $ $ , ((a <= b) <= c) /" (a <= b)
$ boolean "
(> ? <= c) $

3.10 Equality

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 29 of 61

Primitive Data Value Equality: ==, !=

F" a b " " " +


$ )<

3 + $ " 7
a == b a b + I " " " I /+
a != b a b + I " " " I +

+ == + != "
" boolean "
+

int year = 2002;


boolean isEven = year % 2 == 0; // true.
boolean compare = '1' == 1; // false. Binary numeric promotion applied.
boolean test = compare == false; // true.

5 ! 7 +
7 " ! : !
! (1.0 - 2.0/3.0 == 1.0/3.0) false

. ! # * *
$ 2 & + "
" " ! a == b == c $ $ , ((a == b)
== c) /" (a == b) $ boolean "
" + (> ? == c) $ c
! $ ! * B )

int a, b, c;
a = b = c = 5;
boolean valid1 = a == b == c; // (1) Illegal.
boolean valid2 = a == b && b == c; // (2) Legal.
boolean valid3 = a == b == true; // (3) Legal.

Object Reference Equality: ==, !=

+ == + !=
$ F" r s "
+ $ )9

4 , ! 7
r == s r s + I " " I /+
r != s r s + I " " I +

, K C

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 30 of 61

$ 7 & AA

Pizza pizza_A = new Pizza("Sweet&Sour"); // new object


Pizza pizza_B = new Pizza("Sweet&Sour"); // new object
Pizza pizza_C = new Pizza("Hot&Spicy"); // new object

String banner = "Come and get it!"; // new object


boolean test = banner == pizza_A; // (1) Compile-time error.
boolean test1 = pizza_A == pizza_B; // false
boolean test2 = pizza_A == pizza_C; // false

pizza_A = pizza_B; // Denote the same object, are aliases.


boolean test3 = pizza_A == pizza_B; // true

banner == pizza_A * String Pizza


" test1 test2 false
pizza_A pizza_B $ ((
" test3 true $ pizza_A pizza_B

+ + #$ $

null "
" + $ null
" " "

if (objRef != null) {
// ... use objRef ...
}

Object Value Equality


Object " public boolean equals(Object obj) $
& AB B)) " + )
Object true
$ + ==
" equals()
Object " + + :
equals() & ** < ;A*

5 .' " equals() !


java.lang.String java.util.BitSet java.util.Date java.io.File $
" : $ String " +
+ : $ " + " "
$ $ +

// Equality for String objects means same character sequence.


String movie1 = new String("The Revenge of the Exception Handler");
String movie2 = new String("High Noon at the Java Corral");
String movie3 = new String("The Revenge of the Exception Handler");
boolean test0 = movie1.equals(movie2); // false
boolean test1 = movie1.equals(movie3); // true

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 31 of 61

// Equality for Boolean objects means same primitive value


Boolean flag1 = new Boolean(true);
Boolean flag2 = new Boolean(true);
boolean test2 = flag1.equals(flag2); // true

// Pizza class does not override the equals() method,


// can use either equals (inherited from Object) or ==.
Pizza pizza1 = new Pizza("VeggiesDelight");
Pizza pizza2 = new Pizza("VeggiesDelight");
Pizza pizza3 = new Pizza("CheeseDelight");
boolean test3 = pizza1.equals(pizza2); // false
boolean test4 = pizza1.equals(pizza3); // false
boolean test5 = pizza1 == pizza2; // false
pizza1 = pizza2; // Aliases
boolean test7 = pizza1.equals(pizza2); // true
boolean test6 = pizza1 == pizza2; // true

3.11 Boolean Logical Operators: !, ^, &, |


!
& .3 | -1 ^ -1 # 4-1
boolean boolean "
& | ^ !
& ) *) <8

F" !
)E # $ "

5 # 8
!x 1 7" !
.3 x & y true C $ false

-1 x | y true C $ false

4-1 x ^ y true C $ false

$ " #
&& || & ) *B <B 7" $
) *D

6 &) ! # 8
x y !x x & y x | y x ^ y

true true false true true false


true false false false true true

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 32 of 61

false true true false true true


false false true false false false

Operand Evaluation for Boolean Logical Operators


" ! " " .3 4-1 -1
" " $

if (i > 0 & i++ < 10) {/*...*/} // i will be incremented, regardless of value in i.

" $
.3 -1 & ) *B
<B $ ! ,

boolean b1, b2, b3 = false, b4 = false;


b1 = 4 == 2 & 1 < 4; // false, evaluated as (b1 = ((4 == 2) & (1 < 4)))
b2 = b1 | !(2.5 >= 8); // true
b3 = b3 ^ b2; // true
b4 = b4 | b1 & b2; // false

- " ! ,

(b4 = (b4 | (b1 & b2)))


(b4 = (false | (b1 & b2)))
(b4 = (false | (false & b2)))
(b4 = (false | (false & true)))
(b4 = (false | false))
(b4 = false)

3 b2 $ " # $ "

Boolean Logical Compound Assignment Operators: &=, ^=, |=

5 ) **
7 " 7
! . "
! & ) *) <9

# 8 %
. / b a% ! Boolean0 & 1 .
b &= a b = (b & (a))
b ^= a b = (b ^ (a))
b |= a b = (b | (a))

Examples of Boolean Logical Compound Assignment

boolean b1 = false, b2 = false, b3 = false;

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 33 of 61

b1 |= true; // true
b2 ^= b1; // true
b3 &= b1 | b2; // (1) false. b3 = (b3 & (b1 | b2)).
b3 = b3 & b1 | b2; // (2) true. b3 = ((b3 & b1) | b2).

" $ * B " "


"

3.12 Conditional Operators: &&, ||


5 && || P | !
" ( F" x y " boolean !
) *B

5 .3 x && y true C $ false

5 -1 x || y true C $ false

% # & | $ $
&& || boolean
" boolean " 7" $
) *) 3 " 7"

3 #

&) !
x y x && y x || y

true true true true


true false false true
false true false true
false false false false

Short-circuit Evaluation
" ! " " .3 -1 7
" " 7
! 7 7
" $ 7 "

" $
$ !
,

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 34 of 61

boolean b1 = 4 == 2 && 1 < 4; // false, short-circuit evaluated as


// (b1 = ((4 == 2) && (1 < 4)))
boolean b2 = !b1 || 2.5 > 8; // true, short-circuit evaluated as
// (b2 = ((!b1) || (2.5 > 8)))
boolean b3 = !(b1 && b2); // true
boolean b4 = b1 || !b3 && b2; // false, short-circuit evaluated as
// (b4 = (b1 || ((!b3) && b2)))

- " " " b4 $,

(b4 = (b1 || ((!b3) && b2)))


(b4 = (false || ((!b3) && b2)))
(b4 = (false || ((!true) && b2)))
(b4 = (false || ((false) && b2)))
(b4 = (false || false))
(b4 = false)

3 b2 " 7 "

& 7 " "

if (objRef != null && objRef.doIt()) { /*...*/ }

$ 7 $ !
" objRef null $ & "
objRef null " 7 $
NullPointerException

$ && || " 7
7 @ & |
"
$ ! ,

if (i > 0 && i++ < 10) {/*...*/} // i is not incremented if i > 0 is false.
if (i > 0 || i++ < 10) {/*...*/} // i is not incremented if i > 0 is true.

Review Questions

- @ $ ! " trueI

& $ $

(false | true)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 35 of 61

(null != null)

(4 <= 4)

(!true)

(true & false)

2 @ I

& $ $

% $

6" "

* / % " "

. short " -128 +127 "

(+15) !

3 @ $ I

public class BoolOp {


static void op(boolean a, boolean b) {
boolean c = a != b;
boolean d = a ^ b;
boolean e = c == d;
System.out.println(e);
}

public static void main(String[] args) {


op(false, false);
op(true, false);
op(false, true);
op(true, true);
}
}

& $

. false

. true

false

true

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 36 of 61

4 @ ! $ I

public class OperandOrder {


public static void main(String[] args) {
int i = 0;
int[] a = {3,6};
a[i] = i = 9;
System.out.println(i + " " + a[0] + " " + a[1]);
}
}

& $

$ ! ArrayIndexOutOfBoundsException

' "9 9 6"

' "9 0 6"

' "9 3 6"

' "9 3 9"

5 @ $ I

public class Logic {


public static void main(String[] args) {
int i = 0;
int j = 0;

boolean t = true;
boolean r;

r = (t & 0<(i+=1));
r = (t && 0<(i+=2));
r = (t | 0<(j+=1));
r = (t || 0<(j+=2));
System.out.println(i + " " + j);
}
}

& $ $

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 37 of 61

! )

3.13 Integer Bitwise Operators: ~, &, |, ^


. " $ & F; 8E9
$ $ $ "

$ ~ !
& ! .3 | ! -1 ^ ! -1 # !
4-1

$ $ $ "
" % $
~
$ $ " $
int long

F" A B " 0 1 7 7
" $ $ ) *;

& | ^
& ) ** <D

* 1 # '
!
! &# !& # ,

$ ~A " " ,1 0 0 1

$ .3 A & B 1 1C $ 0

$ -1 A | B 1 1C $ 0

$ 4-1 A ^ B 1 1C $ 0

$ $ $ $
) *8 $ A B " 7 7
" ) *8 ) *D $
" 1 true " 0 false

- , ! # '
A B ~A A & B A | B A ^ B

1 1 0 1 1 0

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 38 of 61

1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0

Examples of Bitwise Operator Application


char v1 = ')'; // Unicode value 41
byte v2 = 13;

int result1 = ~v1; // -42


int result2 = v1 & v2; // 9
int result3 = v1 | v2; // 45
int result4 = v1 ^ v2; // 36

) *A $ $ %
" int 3
" 7 7
7 7

2 !# '
~v1 v1 & v2 v1 | v2 v1 ^ v2

~ 0...0010 1001 0...0010 1001 0...0010 1001 0...0010 1001


& 0...0000 1101 | 0...0000 1101 ^ 0...0000 1101
= 1...1101 0110 = 0...0000 1001 = 0...0010 1101 = 0...0010 0100
= 0xffffffd6 = 0x00000009 = 0x0000002d = 0x00000024
= -42 = 9 = 45 = 36

" ! $
$ /! )B 5 " & *D )
)E9

# '

public class BitOperations {


public static void main(String[] args) {
char v1 = ')'; // Unicode value 41
byte v2 = 13;
printIntToStr("v1:", v1); // 41
printIntToStr("v2:", v2); // 13
printIntToStr("~v1:", ~v1); // -42
printIntToStr("v1 & v2:", v1 & v2); // 9
printIntToStr("v1 | v2:", v1 | v2); // 45
printIntToStr("v1 ^ v2:", v1 ^ v2); // 36
}

public static void printIntToStr(String label, int result) {


System.out.println(label);
System.out.println(" Binary: " + Integer.toBinaryString(result));
System.out.println(" Hex: " + Integer.toHexString(result));
System.out.println(" Decimal: " + result);

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 39 of 61

}
}

- ,

v1:
Binary: 101001
Hex: 29
Decimal: 41
v2:
Binary: 1101
Hex: d
Decimal: 13
~v1:
Binary: 11111111111111111111111111010110
Hex: ffffffd6
Decimal: -42
v1 & v2:
Binary: 1001
Hex: 9
Decimal: 9
v1 | v2:
Binary: 101101
Hex: 2d
Decimal: 45
v1 ^ v2:
Binary: 100100
Hex: 24
Decimal: 36

Bitwise Compound Assignment Operators: &=, ^=, |=

$ $ ) *<
" $
, $ "
$ byte short char
& ) ** <*

3 # ' %
. / T1 & 1 !b0 & 1 .
b &= a b = (T) ((b) & (a))
b ^= a b = (T) ((b) ^ (a))
b |= a b = (T) ((b) | (a))

Examples of Bitwise Compound Assignment

int v0 = -42;
char v1 = ')'; // 41
byte v2 = 13;

v0 &= 15; // 1...1101 0110 & 0...0000 1111 => 0...0000 0110 (= 6)
v1 |= v2; // (1) 0...0010 1001 | 0...0000 1101 => 0...0010 1101 (= 45)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 40 of 61

. * ! " char " v1 byte " v2


int $ char

3.14 Shift Operators: <<, >>, >>>


$"
" " "
7 " " 7 3
"
7 . " 7

.3 7 " 7 $ #"
0x1f )* 7 int #" 0x3f A)
7 long " # " $
7 int 7 # ! $
7 long 7 $
D )* $ 7 int D A)
$ 7 long

F" a " $ n
$ ) *9 " n ) *9
" $
" 7 BK

4 &!
& a << n & a n $ 0

& $ a >> n & a n $

& $ ( a >>> & a n $ 0


n

& char byte short int $


$ int long " 5 #
$ "
"

3 "
a n =$ "
" 7
a

" 0 &
" " $ " " "
"

The Shift-left Operator <<

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 41 of 61

. ( $

int i = 12;
int result = i << 4; // 192

int " i $,

i << 4
= 0000 0000 0000 0000 0000 0000 0000 1100 << 4
= 0000 0000 0000 0000 0000 0000 1100 0000
= 0x000000c0
= 192

/ 7 " B " ! 12*24 192

byte short " ! $ "


! $,

byte b = -42; // 11010110


short n = 4;
int result = b << n; // -672

" $ b n " ! "


short " n int byte " b int 4
,

b << n
= 1101 0110 << 0000 0000 0000 0100
= 1111 1111 1111 1111 1111 1111 1101 0110 <<0000 0000 0000 0000 0000 0000 0000 0100
= 1111 1111 1111 1111 1111 1111 1101 0110 << 4
= 1111 1111 1111 1111 1111 1101 0110 0000
= 0xfffffd60
= -672

" ! -42*24 -672

5 # $ $

byte a = 32, b;
int j;

j = a << 3; // 256
b = (byte) (a << 3); // 0. Cast mandatory.

(a << 3) 256

a << 3
= 0000 0000 0000 0000 0000 0000 0010 0000 << 3
= 0000 0000 0000 0000 0000 0001 0000 0000
= 0x00000100
= 256

" j 256 " b 0 !


$ "

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 42 of 61

! " $ $ " "


7 $ $ D )* " . ! $ 7
$ " 7 7 7 $ $

12 << 36
= 0000 0000 0000 0000 0000 0000 0000 1100 << (0...0010 0100 & 0001 1111)
= 0000 0000 0000 0000 0000 0000 0000 1100 << 0...0000 0100
= 0000 0000 0000 0000 0000 0000 0000 1100 << 4
= 0000 0000 0000 0000 0000 0000 1100 0000
= 0x000000c0
= 192

" 7 36 .3 7 $ #11111 31 0x1f "


4 (36 % 32) (12 << 36) + (12
<< 4) 192

The Shift-right-with-sign-fill Operator >>

. &
7 " " (
" "

int i = 12;
int result = i >> 2; // 3

" i $ 7 $

i >> 2
= 0000 0000 0000 0000 0000 0000 0000 1100 >> 2
= 0000 0000 0000 0000 0000 0000 0000 0011
= 0x00000003
= 3

/ 7 " " $ "


! ! " ! 12/22
3

& $ " "

byte b = -42; // 11010110


int result = b >> 4; // -3

byte " b int $ 7

b >> 4
= 1111 1111 1111 1111 1111 1111 1101 0110 >> 4
= 1111 1111 1111 1111 1111 1111 1111 1101
= 0xfffffffd
= -3

$ ! 7 " " ,

-42 >> -4
= 1111 1111 1111 1111 1111 1111 1101 0110 >> (1...1111 1100 & 0001 1111)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 43 of 61

= 1111 1111 1111 1111 1111 1111 1101 0110 >> 0...0001 1100
= 1111 1111 1111 1111 1111 1111 1101 0110 >> 28
= 1111 1111 1111 1111 1111 1111 1111 1111
= 0xffffffff
= -1

" 7 -4 .3 7 $ #11111 31 0x1f "


28 (-4 % 32) " (-42 >> -4) + " (-42
>> 28)

The Shift-right-with-zero-fill Operator >>>

. ( $
" " "

- " " " 7 7$ 7( 7 >>> 7 7$ 7 7 >>


+ " ! (12 >> 2) ! (12 >>> 2)
" ,

12 >>> 2
= 0000 0000 0000 0000 0000 0000 0000 1100 >>> 2
= 0000 0000 0000 0000 0000 0000 0000 0011
= 0x00000003
= 3

" 7 $ $ ! ,

byte b = -42; // 1101 0110


int result = b >>> 4; // 268435453

" " ! (-42 >>> 4) $ ! (-


42 >> 4) $ " -3 byte " b int
$ ( 7

b >>> 4
= 1111 1111 1111 1111 1111 1111 1101 0110 >>> 4
= 0000 1111 1111 1111 1111 1111 1111 1101
= 0x0ffffffd
= 268435453

$ ! " 7 7 7
28 $ " ,

-42 >>> -4
= 1111 1111 1111 1111 1111 1111 1101 0110 >>> 28
= 0000 0000 0000 0000 0000 0000 0000 1111
= 0x0000000f
= 15

Shift Compound Assignment Operators: <<=, >>=, >>>=

) *E " $
,.
$ " $

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 44 of 61

byte short char

5 &! %
/ T & 1 !x0 & 1 .
x <<= a x = (T) ((x) << (a))
x >>= a x = (T) ((x) >> (a))
x >>>= a x = (T) ((x) >>> (a))

Examples of Shift Compound Assignment Operators

int i = -42;
i >>= 4; // 1...1101 0110 >> 4 => 1...1111 1101 (= -3).

byte a = 12;
a <<= 5; // (1) -128. Evaluated as a = (byte)((int)a << 5)
a = a << 5; // Compile-time error. Needs explicit cast.

! * # $
byte " a int
" $ $ byte,

a = (byte) (a << 5)
= (byte) (0000 0000 0000 0000 0000 0000 0000 1100 << 5)
= (byte) 0000 0000 0000 0000 0000 0001 1000 0000
= 1000 0000
= 0x80
= -128

3.15 The Conditional Operator: ?


$ !
$ !,

? 1
: 2

! true 1 " C $
2 " - 1 2 " "
" ! "
!

boolean leapYear = false;


int daysInFebruary = leapYear ? 29 : 28; // 28

! + " if-else
! ,

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 45 of 61

(a?b?c?d:e:f:g) " (a?(b?(c?d:e):f):g)

3.16 Other Operators: new, [], instanceof


new $
& ;; **< $ []
& ;* *DD & ;*
*D; & <8 )D9

Pizza onePizza = new Pizza(); // Create an instance of Pizza class.

[]
& ;* *DD

int[] anArray = new int[5];// Declare and construct an int array of 5 elements.
anArray[4] = anArray[3]; // Element at index 4 gets value of element at index 3.

! instanceof K &
AA BA;

Pizza myPizza = new Pizza();


boolean test1 = myPizza instanceof Pizza; // True.
boolean test2 = "Pizza" instanceof Pizza; // Compile error. String is not Pizza.
boolean test3 = null instanceof Pizza; // Always false. null not an instance.

Review Questions

6 @ $ ! $ I

public class MyClass {


public static void main(String[] args) {
test(1<<32, "1<<32");
test(1<<31, "1<<31");
test(1<<30, "1<<30");
test(1, "1" );
test(0, "0" );
test(-1, "-1" );
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 46 of 61

public static void test(int i, String exp) {


if ((i >> 1) != (i >>> 1)) System.out.println(exp);
}
}

& $ $

"1<<32"

"1<<31"

"1<<30"

"1"

"0"

! "-1"

@ $ 6" I

& $ $

<<<

&

%=

>>>

! <=

&&=

F" " x int $ " " $


$ " x $ 7 7
" I

& $

x << 1;

x = x * 2;

x *= 2;

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 47 of 61

x += x;

x <<= 1;

@ $ $
I

& $

&

* F" $ $ ! " I

byte b = 1;
char c = 1;
short s = 1;
int i = 1;

& $

s = b * 2;

i = b << s;

b <<= s;

c = c + b;

s += i;

3.17 Parameter Passing


- & *; < .
"# & "#
6" ' " $ ! $
$
& ;)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 48 of 61

! $ ,

+ . ( )
. ( )
( )

+ ! "
+ this
& ;) **; )
& ;A *BA (
"
+
#

objRef.doIt(time, place); // Explicit object reference


int i = java.lang.Math.abs(-1); // Fully qualified class name
int j = Math.abs(-1); // Class name
someMethod(ofValue); // Object or class implicitly implied
someObjRef.make().make().make(); // make() returns an object reference

. " make()
! !
!

$ "#
" ,
& ;) **B ))

. $ ,

5 " 0
" " " " & ) *9
& AA

6" " " "


) BD ( $ "
" "

"
" "
"

6 + +
$ !& + " +

' " ' " "


5 1 "

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 49 of 61

. 1 "

" $
"

" $ F" $
,

int i = 4;

leftRight(i++, i);

"

leftRight(4, 5);

leftRight(4, 4);

: ! ! + $ "
$
" "

3.18 Passing Primitive Data Values


@ " " " "
" &
$

3 ! " "

" $ "
" $ " "
=$ " $ " &
); ;E

+ + "

public class CustomerOne {


public static void main (String[] args) {
PizzaFactory pizzaHouse = new PizzaFactory();
int pricePrPizza = 15;
double totPrice = pizzaHouse.calcPrice(4, pricePrPizza); // (1)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 50 of 61

System.out.println("Value of pricePrPizza: " + pricePrPizza); // Unchanged.


}
}

class PizzaFactory {
public double calcPrice(int numberOfPizzas, double pizzaPrice) { // (2)
pizzaPrice = pizzaPrice/2.0; // Change price.
return numberOfPizzas * pizzaPrice;
}
}

- ,

Value of pricePrPizza: 15

/! )) calcPrice() PizzaFactory B
CustomerOne.main() * " 4
int numberOfPizzas 3 pricePrPizza
int $ pizzaPrice double
" pricePrPizza pizzaPrice
$ double ' " " : );

* + + .+ $ "

" pizzaPrice calcPrice()


" pricePrPizza " 15
" "
"

3.19 Passing Object Reference Values


"

" "
" !
! " "

" $
& AA

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 51 of 61

*+ 9 , ! "

public class CustomerTwo {


public static void main (String[] args) {
Pizza favoritePizza = new Pizza(); // (1)
System.out.println("Meat on pizza before baking: " + favoritePizza.meat);
bake(favoritePizza); // (2)
System.out.println("Meat on pizza after baking: " + favoritePizza.meat);
}
public static void bake(Pizza pizzaToBeBaked) { // (3)
pizzaToBeBaked.meat = "chicken"; // Change the meat on the pizza.
pizzaToBeBaked = null; // (4)
}
}

class Pizza { // (5)


String meat = "beef";
}

- ,

Meat on pizza before baking: beef


Meat on pizza after baking: chicken

/! ); Pizza * . Pizza
8 $ (( bake() B
" favoritePizza
pizzaToBeBaked bake() )

- + "
" $ # $
favoritePizza $ $ #
(( & pizzaToBeBaked null ;
" favoritePizza "
bake() : )8

- + + . 9 , ! "

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 52 of 61

$ "
$

6" ( ( ( (
5 7 7 $ "
$ "
" C " pricePrPizza " /! ))
favoritePizza null /! );=$ "
6"

3.20 Passing Array References


. 6" & ;* *DD . " $

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 53 of 61

" " + "


0 " " $
& AA

-+ %

public class Percolate {

public static void main (String[] args) {


int[] dataSeq = {6,4,8,2,1}; // Create and initialize an array.

// Write array before percolation.


for (int i = 0; i < dataSeq.length; ++i)
System.out.print(" " + dataSeq[i]);
System.out.println();

// Percolate.
for (int index = 1; index < dataSeq.length; ++index)
if (dataSeq[index-1] > dataSeq[index])
swap(dataSeq, index-1, index); // (1)

// Write array after percolation.


for (int i = 0; i < dataSeq.length; ++i)
System.out.print(" " + dataSeq[i]);
System.out.println();
}

public static void swap(int[] table, int i, int j) { // (2)


int tmp = table[i]; table[i] = table[j]; table[j] = tmp;
}

public static void swap(int v1, int v2) { // (3)


int tmp = v1; v1 = v2; v2 = tmp;
}
}

- ,

6 4 8 2 1
4 6 2 1 8

/! )8 $

3 swap() B table
swap() main() * $
" dataSeq " " dataSeq
" table " . swap()
" dataSeq $ "
: )A
swap() $" !0 1 "
$

2 + + .%

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 54 of 61

=$ " swap() ) $ $ $ "

swap(dataSeq[index-1], dataSeq[index]);

$ " $ "

3.21 Array Elements as Actual Parameters


. # " " "
&
;* *D; " "
"

2% + $ "

public class FindMinimum {

public static void main(String[] args) {


int[] dataSeq = {6,4,8,2,1};

int minValue = dataSeq[0];


for (int index = 1; index < dataSeq.length; ++index)
minValue = minimum(minValue, dataSeq[index]); // (1)

System.out.println("Minimum value: " + minValue);


}

public static int minimum(int i, int j) { // (2)


return (i <= j) ? i : j;
}
}

- ,

Minimum value: 1

/! )A " dataSeq "


" * j minimum() B
& ) *9 7 7" " "
"

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 55 of 61

3% 9 , ! "

public class FindMinimumMxN {

public static void main(String[] args) {


int[][] matrix = { {8,4},{6,3,2},{7} }; // (1)

int min = findMinimum(matrix[0]); // (2)


for (int i = 1; i < matrix.length; ++i) {
int minInRow = findMinimum(matrix[i]); // (3)
if (min > minInRow) min = minInRow;
}
System.out.println("Minimum value in matrix: " + min);
}

public static int findMinimum(int[] seq) { // (4)


int min = seq[0];
for (int i = 1; i < seq.length; ++i)
min = Math.min(min, seq[i]);
return min;
}
}

- ,

Minimum value in matrix: 2

/! )< seq findMinimum() ;


" " matrix *
$ $ $ $ $
matrix[0] findMinimum() B / $
" findMinimum() )

3.22 final Parameters


. $ # $ final
. # $ - C
# ( " ! "
" " "
& ;*D *;A # "
( @ final
K

calcPrice() /! )) $ $ $
pizzaPrice final

public double calcPrice(int numberOfPizzas, final double pizzaPrice) { // (2)


pizzaPrice = pizzaPrice/2.0; // (3)
return numberOfPizzas * pizzaPrice;
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 56 of 61

calcPrice() $ $ "
final pizzaPrice )

. ! bake() /! ); $ $ $
pizzaToBeBaked final

public static void bake(final Pizza pizzaToBeBaked) { // (3)


pizzaToBeBaked.meat = "chicken"; // (3a) Allowed.
pizzaToBeBaked = null; // (4) Not allowed.
}

bake() $ $ "
final pizzaToBeBaked ; 3
" final
$ )

3.23 Program Arguments


. main()
,

java Colors red green blue

3 java
Colors main() Colors

& main() String " String


[]

/! )9 "red" "green" "blue" main()


Colors args[0] args[1] args[2] "
" length String args 3
! "

@ ( String
main() "
main() " null

' $
" +

4+ + %

public class Colors {


public static void main(String[] args) {
for (int i = 0; i < args.length; i++)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 57 of 61

System.out.println("Argument no. " + i + " (" + args[i] + ") has " +


args[i].length() + " characters.");
}
}

1 ,

>java Colors red green blue


Argument no. 0 (red) has 3 characters.
Argument no. 1 (green) has 5 characters.
Argument no. 2 (blue) has 4 characters.

Review Questions

- @ $ $ $ I

public class ParameterPass {


public static void main(String[] args) {
int i = 0;
addTwo(i++);
System.out.println(i);
}

static void addTwo(int i) {


i += 2;
}
}

& $

2 @ $ $ I

public class Passing {


public static void main(String[] args) {
int a = 0; int b = 0;
int[] bArr = new int[1]; bArr[0] = b;

inc1(a); inc2(bArr);

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 58 of 61

System.out.println("a=" + a + " b=" + b + " bArr[0]=" + bArr[0]);


}

public static void inc1(int x) { x++; }

public static void inc2(int[] x) { x[0]++; }


}

& $

$ x[0]++;

$ $ "a=1 b=1 bArr[0]=1" $

$ $ "a=0 b=1 bArr[0]=1" $

$ $ "a=0 b=0 bArr[0]=1" $

$ $ "a=0 b=0 bArr[0]=0" $

3 F"

// Filename: Args.java
public class Args {
public static void main(String[] args) {
System.out.println(args[0] + " " + args[args.length-1]);
}
}

$ $ ! $ I

java Args In politics stupidity is not a handicap

& $

$ $ ArrayIndexOutOfBoundsException

$ "java handicap"

$ "Args handicap"

$ "In handicap"

$ "Args a"

! $ "In a"

4 @ $
$ I

public class ParameterUse {

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 59 of 61

static void main(String[] args) {


int a = 0;
final int b = 1;
int[] c = { 2 };
final int[] d = { 3 };
useArgs(a, b, c, d);
}

static void useArgs(final int a, int b, final int[] c, int[] d) {


// INSERT STATEMENT HERE.
}
}

& $ $

a++;

b++;

b = a;

c[0]++;

d[0]++;

! c = d;

Chapter Summary

$ $ ! ,

6" "

" , $ $ ,
! $

" !

"

" + +

" "
, final

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 60 of 61

Programming Exercises

$ $ # "
:! $
$ " $

// Filename: Sunlight.java
public class Sunlight {
public static void main(String[] args) {
// Distance from sun (150 million kilometers)
int kmFromSun = 150000000;

int lightSpeed = 299792458; // meters per second

// Convert distance to meters.


int mFromSun = kmFromSun * 1000;

int seconds = mFromSun / lightSpeed;

System.out.print("Light will use ");


printTime(seconds);
System.out.println(" to travel from the sun to the earth.");
}

public static void printTime(int sec) {


int min = sec / 60;
sec = sec - (min*60);
System.out.print(min + " minute(s) and " + sec + " second(s)");
}
}

5 $ # int String
F" 42
"101010"
" 6"

5 $ " "
$ ! $ $

java ArgumentSkipper one two three a b c d

one

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006


Page 61 of 61

three
b
d

5 $ $ $ "

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh5C30.htm 6/16/2006