Java™ Puzzlers, Episode VI: The PhantomReference Menace. ttac! of the "lone. Reven#e of the $hift.

Joshua Bloch Chief Java Archi ec !oogle "nc#
Session TS-2707
2007 JavaOneSM Conference | Session TS-2707 |

William Pugh Professor $niversi % of Mar%lan&

Introduction
( )igh more Java* +la form +u,,les
( ( ( ( ( Shor +rogram -i h curious .ehavior Wha &oes i +rin / 0mul i+le choice1 The m%s er% reveale& 2o- o fi3 he +ro.lem The moral

( Covers language4 core li.raries4 an& more

2007 JavaOneSM Conference | Session TS-2707 |

'

%. &The Jo' of $ets(
public class ShortSet { public static void main(String args[]) { Set<Short> s = new HashSet<Short>(); or (short i = !; i < "!!; i##) { s$add(i); s$remove(i % "); & S'stem$out$println(s$si(e()); & &

2007 JavaOneSM Conference | Session TS-2707 |

5

)hat *oes It Print+
public class ShortSet { public static void main(String args[]) { Set<Short> s = new HashSet<Short>(); or (short i = !; i < "!!; i##) { s$add(i); s$remove(i % "); & S'stem$out$println(s$si(e()); & &

0a1 "

0.1 "!! 0c1 Thro-s e3ce+ ion 0&1 7one of he a.ove
2007 JavaOneSM Conference | Session TS-2707 | 6

)hat *oes It Print+ 0a1 " 0.ove The set contains Short values.1 "!! 0c1 Thro-s e3ce+ ion 0&1 7one of he a.re removin# )nteger values 2007 JavaOneSM Conference | Session TS-2707 | 8 .ut -e. .

nother /oo! public class ShortSet { public static void main(String args[]) { Set<Short> s = new HashSet<Short>().pression & S'stem$out$println(s$si(e()). & & 2007 JavaOneSM Conference | Session TS-2707 | 7 . ++ int%valued e. i < "!!. s$remove(i * "). or (short i = !. i##) { s$add(i).

s$remove(i * ").tends . i##) { s$add(i). i < "!!. public abstract boolean remove(/b0ect o).ollection<-> { public abstract boolean add(.pression & S'stem$out$println(s$si(e()).nother 0nother /oo! public class ShortSet { public static void main(String args[]) { Set<Short> s = new HashSet<Short>().e). & & public inter ace Set<->e. ++ int%valued e. $$$ & 2007 JavaOneSM Conference | Session TS-2707 | 9 . or (short i = !.

& & 2007 JavaOneSM Conference | Session TS-2707 | : .*o 2ou 3i4 It+ public class ShortSet { public static void main(String args[]) { Set<Short> s = new HashSet<Short>(). or(short i = !. i < "!!. s$remove((short) (i * ")). & S'stem$out$println(s$si(e()).1o. i##) { s$add(i).

ollection<->$remove a<es /b0ect4 no ( Also .0 .Moral • .ollection$contains4 1ap$get ( "n egral ari hme ic al-a%s resul s in int or long ( Avoi& mi3ing %+es ( Avoi& short= +refer int an& long ( Arra%s of short are he onl% com+elling use case 2007 JavaOneSM Conference | Session TS-2707 | .

9http:++www$google$com9. &More Jo' of $ets( import 0ava$net$2..ception { Set<345> avorites = new HashSet<345>(). 9http:++www$cs$umd$edu9 &.5. S'stem$out$println( avorites$si(e()). . 9http:++apache<%snort$s='bar$dreamhost$com9. 9http:++0avapu((lers$com9. & & 2007 JavaOneSM Conference | Session TS-2707 | . public class 3rlSet { private static inal String[] 3456781-S = { 9http:++0avapu((lers$com9. 9http:++ indbugs$source orge$net9. public static void main(String[] args) throws 1al ormed345-. or (String url7ame : 3456781-S) avorites$add(new 345(url7ame)).

9http:++www$google$com9. public class 3rlSet { private static inal String[] 3456781-S = { 9http:++0avapu((lers$com9.2 .ception { Set<345> avorites = new HashSet<345>(). public static void main(String[] args) throws 1al ormed345-. & & 2007 JavaOneSM Conference | Session TS-2707 | . S'stem$out$println( avorites$si(e()). 9http:++0avapu((lers$com9.0a1 5 )hat *oes It Print+ 0.ove import 0ava$net$2. or (String url7ame : 3456781-S) avorites$add(new 345(url7ame)). 9http:++www$cs$umd$edu9 &. 9http:++ indbugs$source orge$net9.1 6 0c1 8 0&1 7one of he a. 9http:++apache<%snort$s='bar$dreamhost$com9.

' .ove ? i varies from run o run 345.1 6 0c1 8 0&1 7one of he a.)hat *oes It Print+ 0a1 5 0 %+icall%4 assuming %ou>re on he ne 1 0.ro!en 2007 JavaOneSM Conference | Session TS-2707 | .s e>uals and hash.ode are .

9http:++www$google$com9. 9http:++0avapu((lers$com9. & & 2007 JavaOneSM Conference | Session TS-2707 | .nother /oo! 6%7 import 0ava$net$2. Identical 9http:++ indbugs$source orge$net9. public class 3rlSet { $ame IP ddress private static inal String[] 3456781-S = { 9http:++0avapu((lers$com9. or (String url7ame : 3456781-S) avorites$add(new 345(url7ame)).ception { Set<345> avorites = new HashSet<345>(). public static void main(String[] args) throws 1al ormed345-. S'stem$out$println( avorites$si(e()). 9http:++apache<%snort$s='bar$dreamhost$com9. 9http:++www$cs$umd$edu9 &.5 .

e resolve&4 he hos names mus .o h hos names eCual o null# Since hos s com+arison reCuires name resolu ion4 his o+era ion is a .e resolve& in o he same "P a&&resses= else if ei her hos name canD .nother /oo! 657 8 345 *ocumentation T-o $@A o.er on he hos 4 an& he same file an& fragmen of he file# T-o hos s are consi&ere& eCuivalen if .e eCual -i hou regar& o case= or .6 .loc<ing o+era ion# 2007 JavaOneSM Conference | Session TS-2707 | .o h hos names can .Bec s are eCual if he% have he same +ro ocol4 reference eCuivalen hos s4 have he same +or num.

public class 3riSet { private static inal String[] 34)6781-S = { 9http:++0avapu((lers$com9. 9http:++www$cs$umd$edu9 &. 9http:++ indbugs$source orge$net9.1o. public static void main(String[] args) throws 34)S'nta. & & 2007 JavaOneSM Conference | Session TS-2707 | . S'stem$out$println( avorites$si(e()). or (String uri7ame : 34)6781-S) avorites$add(new 34)(uri7ame)). 9http:++apache<%snort$s='bar$dreamhost$com9.-.8 .*o 2ou 3i4 It+ import 0ava$net$2. 9http:++0avapu((lers$com9.ception { Set<34)> avorites = new HashSet<34)>(). 9http:++www$google$com9.

7 .e% heir general con rac sF ( $se 34) ins ea& ( Ma<e 345 from 34) as necessar% • e>uals shoul& no &e+en& on environmen 2007 JavaOneSM Conference | Session TS-2707 | .ode aren> -ell &efine& ( The% &o no o.Moral ( Eo no use 345 as a Set elemen or 1ap <e% • e>uals an& hash.

number##. t$0oin().9. t$start(). number = ". &Rac' /ittle :um. public void test() throws )nterrupted-. number).ception { number = !. ?hread t = new ?hread(new 4unnable() { public void run() { assert->uals(<.tends 0unit$ ramewor=$?est.ase { int number.er( public class ?est e.9 . & & 2007 JavaOneSM Conference | Session TS-2707 | . & &).

tends 0unit$ ramewor=$?est. ?hread t = new ?hread(new 4unnable() { public void run() { assert->uals(<.: 2007 JavaOneSM Conference | Session TS-2707 | .1o. t$0oin().. 0a1 " al-a%s fails t$start().ception { number = !. public void test() throws )nterrupted-.ase { int number.ften *oes This Test Pass+ public class ?est e.1 " some imes +asses number##. number = ". 0. & &). 0c1 " al-a%s +asses & & 0&1 " al-a%s hangs . number).

.t #et a chance to see -hether assertion succeeds or fails 2007 JavaOneSM Conference | Session TS-2707 | 20 .u i ells us no hing al-a%s hangs J<nit doesn.1 " 0c1 " 0&1 " al-a%s fails some imes +asses al-a%s +asses ? .1o.ften *oes This Test Pass+ 0a1 " 0.

ception assert->uals(<.ase { int number.ception { number = !. ?hread t = new ?hread(new 4unnable() { public void run() { ++ @3nit never sees an' thrown e.tends 0unit$ ramewor=$?est.nother /oo! public class ?est e. number). & &). t$start(). t$0oin(). public void test() throws )nterrupted-. number = ". . number##. & & 2007 JavaOneSM Conference | Session TS-2707 | 2.

ception { i (error B= null) throw error. i (e.ception. ++ ?riggers test case ailure i an' thread asserts public void tearAown() throws -.ception e.ception B= null) throw e. & ailed 2007 JavaOneSM Conference | Session TS-2707 | 22 .*o 2ou 3i4 It+ 6%7 volatile -.ception. volatile -rror error.1o.

ception = e.1o. 2007 JavaOneSM Conference | Session TS-2707 | 2' . number). & & &).ception e) { e. & catch(-.*o 2ou 3i4 It+ 657 ?hread t = new ?hread(new 4unnable() { public void run() { tr' { assert->uals(<. & catch(-rror e) { error = e.

H'0 PM?2H'0 PM 2007 JavaOneSM Conference | Session TS-2707 | 25 .es ne.Moral ( J$ni &oes no su++or concurrenc% ( Gou mus +rovi&e %our o-n ( "f %ou &on> 4 %ou>ll ge a false sense of securi % ( Also see TS-2220 Tes ing Concurren Sof -are ( Eescri.frame-or< o .e er han&le his si ua ion ( Thurs&a%4 .

& public static void main(String[] args) { S'stem$out$println(-5D)S$lives() G 9Hound Aog9 : 9Heartbrea= Hotel9). & & 2007 JavaOneSM Conference | Session TS-2707 | 26 . &Elvis /ives #ain( public class -lvis { ++ Singleton pattern: thereCs onl' one -lvis public static inal -lvis -5D)S = new -lvis(). inal Eoolean lives() { return alive.=. private -lvis() { & private static private public inal Eoolean 5)D)7F = true. inal Eoolean alive = 5)D)7F.

& public static void main(String[] args) { S'stem$out$println(-5D)S$lives() G 9Hound Aog9 : 9Heartbrea= Hotel9).)hat *oes It Print+ 0a1 Hound Aog 0. private -lvis() { & private static private public inal Eoolean 5)D)7F = true.ove public class -lvis { ++ Singleton pattern: thereCs onl' one -lvis public static inal -lvis -5D)S = new -lvis().1 Heartbrea= Hotel 0c1 " varies 0&1 7one of he a. inal Eoolean lives() { return alive. & & 2007 JavaOneSM Conference | Session TS-2707 | 28 . inal Eoolean alive = 5)D)7F.

and auto>un.rea< 2o el 0c1 " varies 0&1 7one of he a.ception "lass initialization is tric!'.1 2ear .)hat *oes It Print+ 0a1 2oun& Eog 0.o4in# happens -here 'ou least e4pect it 2007 JavaOneSM Conference | Session TS-2707 | 27 .ove ? hro-s 7ullHointer-.

private -lvis() { & private static private public inal Eoolean 5)D)7F = true. inal Eoolean lives() { return alive.ingB 9Hound Aog9 : 9Heartbrea= Hotel9). ++ ?oo late inal Eoolean alive = 5)D)7F. & public static void main(String[] args) { S'stem$out$println(-5D)S$lives() G ++ 8uto% unbo.nother /oo! public class -lvis { ++ 4ecursive class initiali(ation public static inal -lvis -5D)S = new -lvis(). & & 2007 JavaOneSM Conference | Session TS-2707 | 29 .

1o.*o 2ou 3i4 It+ public class -lvis { private -lvis() { & private static inal Eoolean 5)D)7F = true. & public static void main(String[] args) { S'stem$out$println(-5D)S$lives() G 9Hound Aog9 : 9Heartbrea= Hotel9). private public inal Eoolean alive = 5)D)7F.reate singleton 2a ter2 initiali(ing other public static inal -lvis -5D)S = new -lvis(). ields ++ . & & 2007 JavaOneSM Conference | Session TS-2707 | 2: . inal Eoolean lives() { return alive.

a ion ( Cons ruc ins ances a en& of class ini iali.a ion '0 2007 JavaOneSM Conference | Session TS-2707 | .Moral ( Wra++e& +rimi ives aren> +rimi ives ( The% aren> com+ile.ception ( 7ever use Eoolean as a hree-value& re urn %+e ( Almos guaran ees 7ullHointer-.ime cons an s4 ei her ( Au o-un.ception ( Wa ch ou for circulari ies in class ini iali.o3ing can occur -hen %ou leas e3+ec i ( " can cause 7ullHointer-.

)nputStream in = new Eu ered)nputStream(new Kile)nputStream(tmp)). in$s=ip(F8H6S)I-). out$write(new b'te[F8H6S)I-]). . int irst = in$read(). out$write(<). out$close(). public class Fap { private static inal int F8H6S)I. Kile/utputStream out = new Kile/utputStream(tmp). &Mind the @ap( import 0ava$io$2. & & 2007 JavaOneSM Conference | Session TS-2707 | '. int last = in$read(). out$write(").= "! 2 "!<J.ception { Kile tmp = Kile$create?empKile(9gap9.?. public static void main(String args[]) throws )/-. S'stem$out$println( irst # last). 9$t.t9).

int last = in$read().= "! 2 "!<J. public class Fap { private static inal int F8H6S)I.ception { Kile tmp = Kile$create?empKile(9gap9. )hat *oes It Print+ 0. & & 2007 JavaOneSM Conference | Session TS-2707 | '2 . Kile/utputStream out = new Kile/utputStream(tmp). out$write(new b'te[F8H6S)I-]). S'stem$out$println( irst # last).0a1 . 9$t. out$write(<). public static void main(String args[]) throws )/-. int irst = in$read(). out$close().t9).1 ' 0c1 Thro-s e3ce+ ion 0&1 " varies import 0ava$io$2. in$s=ip(F8H6S)I-). out$write("). )nputStream in = new Eu ered)nputStream(new Kile)nputStream(tmp)).

0in +rac ice1 0. lso it is difficult to use correctl'.)hat *oes It Print+ 0a1 .1 ' 0c1 Thro-s e3ce+ ion 0&1 " varies from run o run 0accor&ing o s+ec1 s=ip returns a valueA i#nore it at 'our peril. 2007 JavaOneSM Conference | Session TS-2707 | '' .

in$s=ip(F8H6S)I-).nother /oo! import 0ava$io$2.ception { Kile tmp = Kile$create?empKile(9gap9. int irst = in$read(). public class Fap { private static inal int F8H6S)I. out$close(). )nputStream in = new Eu ered)nputStream(new Kile)nputStream(tmp)).t9). S'stem$out$println( irst # last). ++ 7ot guaranteed to s=ip entire gap int last = in$read(). 9$t. out$write(new b'te[F8H6S)I-]). public static void main(String args[]) throws )/-. out$write(<). out$write("). Kile/utputStream out = new Kile/utputStream(tmp).= "! 2 "!<J. & & 2007 JavaOneSM Conference | Session TS-2707 | '5 .

& & 2007 JavaOneSM Conference | Session TS-2707 | '6 . long nE'tes) throws )/-.ception(). remaining %= s=ipped.ception { long remaining = nE'tes.1o. i (s=ipped == !) throw new -/K-. while (remaining B= !) { long s=ipped = in$s=ip(remaining).*o 2ou 3i4 It+ static void s=ipKull'()nputStream in.

ro<en4 -ra+ i ( Ior AP" &esigners ( Eon> viola e he +rinci+le of leas as onishmen ( Ma<e i eas% o &o sim+le hings 2007 JavaOneSM Conference | Session TS-2707 | '8 .Moral ( The s=ip me ho& is har& o use an& error +rone ( $se %our s=ipKull' ins ea& of s<i+ ( There is an @I) o a&& i o )nputStream ( More generall%4 if an AP" is .

or (int re> : histogram) pair.ount).ount #= re>. 9pol'gene9. or (String word" : words) { or (String word< : words) { String pair = word" # word<. S'stem$out$println(C.ode()) M histogram$length. & & int pair. histogram[buc=et]##. 9recommend9. 9lubricants9 &.ount = !.C # pair. int buc=et = 1ath$abs(pair$hash. public static void main(String[] args) { int[] histogram = new int[L]. & & 2007 JavaOneSM Conference | Session TS-2707 | '7 . &1isto#ram M'ster'( public class Histogram { private static inal String[] words = { 9)9.B.

"P 0c1 S 0&1 7one of he a. & & 2007 JavaOneSM Conference | Session TS-2707 | '9 . 9lubricants9 &.ount).1 .)hat *oes It Print+ 0a1 NO 0. S'stem$out$println(C. & & int pair.ove public class Histogram { private static inal String[] words = { 9)9.ode()) M histogram$length. 9pol'gene9.C # pair. int buc=et = 1ath$abs(pair$hash. or (String word" : words) { or (String word< : words) { String pair = word" # word<. 9recommend9. histogram[buc=et]##.ount = !. public static void main(String[] args) { int[] histogram = new int[L].ount #= re>. or (int re> : histogram) pair.

ove ? hro-s 8rra'/ut/ Eounds-.ception 1ath$abs(int) can re urn a nega ive num.)hat *oes It Print+ 0a1 NO 0."P 0c1 S 0&1 7one of he a.er4 an& so can he M o+era or 2007 JavaOneSM Conference | Session TS-2707 | ': .1 .

or (String word" : words) { or (String word< : words) { String pair = word" # word<.are ull' chosenB { 9)9.ount = !. int buc=et = 1ath$abs(pair$hash. & & 50 2007 JavaOne Conference | Session TS-2707 | SM . or (int re> : histogram) pair.nother /oo! public class Histogram { private static inal String[] words = ++ . 9pol'gene9. ++ 9pol'genelubricants9$hash. S'stem$out$println(C.ount #= re>. & & int pair.ount). 9recommend9. histogram[buc=et]##. 9lubricants9 &.ode()) M histogram$length.C # pair.ode() == )nteger$1)76D853public static void main(String[] args) { int[] histogram = new int[L].

++ 1ath$abs ollows M histogram[buc=et]##. or (String word" : words) or (String word< : words) { String pair = word" # word<.C # pair. 9recommend9.ode() M histogram$length). public static void main(String[] args) { int[] histogram = new int[L].ount = !.1o.ount). 9pol'gene9. & & 2007 JavaOneSM Conference | Session TS-2707 | 5. & int pair.*o 2ou 3i4 It+ public class Histogram { private static inal String[] words = { 9)9. or (int re> : histogram) pair. S'stem$out$println(C. 9lubricants9 &. int buc=et = 1ath$abs(pair$hash.ount #= re>. .

e nega ive ( To ransla e a signe& hash value o a .-o leng h arra% (hashDal Q (buc=ets$length * ")) 2007 JavaOneSM Conference | Session TS-2707 | 52 .uc<e • 1ath$abs(hashDal M buc=ets$length) ( Or (hashDal >>> ") M buc=ets$length ( Or (hashDal Q !.R ) M buc=ets$length ( Or use +o-er-of.Moral • 1ath$abs &oesnD guaran ee nonnega ive resul • )nteger$1)76D853.== %)nteger$1)76D853- ( The M o+era or is remain&er4 no mo&= can .

tEoolean(). & & 2007 JavaOneSM Conference | Session TS-2707 | 5' . S'stem$out$println(result). & $ea of Trou. boolean toEe = rnd$ne. 7umber result = (toEe SS BtoEe) G new )nteger(O) : new Kloat(").C.les( public class Hamlet { public static void main(String[] args) { 4andom rnd = new 4andom().

7umber result = (toEe SS BtoEe) G new )nteger(O) : new Kloat(").1 "$! 0c1 Thro-s e3ce+ ion 0&1 7one of he a. S'stem$out$println(result).)hat *oes It Print+ public class Hamlet { public static void main(String[] args) { 4andom rnd = new 4andom(). & & 0a1 O 0.ove 2007 JavaOneSM Conference | Session TS-2707 | 55 .tEoolean(). boolean toEe = rnd$ne.

oveH O$! The G : o+era or has s range .)hat *oes It Print+ 0a1 O 0.1 "$! 0c1 Thro-s an e3ce+ ion 0&1 7one of he a.ehavior -hen a++lie& o misma che& in egral -ra++er %+es 2007 JavaOneSM Conference | Session TS-2707 | 56 .

& & 2007 JavaOneSM Conference | Session TS-2707 | 58 . 7umber result = (toEe SS BtoEe) G new )nteger(O) : new Kloat("). boolean toEe = rnd$ne.nother /oo! public class Hamlet { public static void main(String[] args) { 4andom rnd = new 4andom().tEoolean(). S'stem$out$println(result).

4 T21 0K. and the t'pe of the conditional e4pression is the promoted t'pe of the second and third operands. if the second and third operands have t'pes that are converti.e he %+e ha resul s from a++l%ing .57 is applied to the operand t'pes.#.e he %+e ha resul s from a++l%ing . :ote that .%.0T.inar' numeric promotion performs un.o4in# conversion 6D?. . ( O her-ise4 he secon& an& hir& o+eran&s are of %+es S.e he null %+e14 hen ha is he %+e of he con&i ional e3+ression# ( "f one of he secon& an& hir& o+eran&s is of %+e . an& S2 res+ec ivel%# Ae T.le in %+e shor 4 hen he %+e of he con&i ional e3+ression is shor # J "f one of he o+eran&s is of %+e Charac er an& he o her o+eran& is a cons an e3+ression of %+e in -hose value is re+resen a.%. .le 6D?.% e# J "f one of he o+eran&s is of %+e Shor an& he o her o+eran& is a cons an e3+ression of %+e in -hose value is re+resen a.ther-ise.le in %+e .o3ing conversion o S.E7 to numeric t'pes.% e or B% e an& he o her is of %+e shor or Shor 4 hen he %+e of he con&i ional e3+ression is shor # J "f one of he o+eran&s is of %+e T -here T is .6#.% e4 hen he %+e of he con&i ional e3+ression is .oolean# ( "f one of he secon& an& hir& o+eran&s is of he null %+e an& he %+e of he o her is a reference %+e4 hen he %+e of he con&i ional e3+ression is ha reference %+e# ( .2#2#71# 2007 JavaOneSM Conference | Session TS-2707 | 57 .le in %+e char4 hen he %+e of he con&i ional e3+ression is char# ( .nother /oo! 657 8 G: $pec 6J/$ %?.E7 and value set conversion 6D?.B.le in %+e T4 hen he %+e of he con&i ional e3+ression is T# J "f one of he o+eran&s is of %+e B% e an& he o her o+eran& is a cons an e3+ression of %+e in -hose value is re+resen a.%97.4 an& le T2 .inar' numeric promotion 6D?.01 o lu.oolean an& he %+e of he o her is of %+e Boolean4 hen he %+e of he con&i ional e3+ression is .%.o3ing conversion o S2# The %+e of he con&i ional e3+ression is he resul of a++l%ing ca+ ure conversion 0K6#.% e4 shor 4 or char4 an& he o her o+eran& is a cons an e3+ression of %+e in -hose value is re+resen a.5?7 The t'pe of a conditional e4pression is determined as follo-s: ( "f he secon& an& hir& o+eran&s have he same %+e 0-hich ma% .ther-ise. then there are several cases: J "f one of he o+eran&s is of %+e .

7umber result. & else { result = new Kloat(").*o 2ou 3i4 It+ public class Hamlet { public static void main(String[] args) { 4andom rnd = new 4andom().tEoolean().1o. & S'stem$out$println(result). i (toEe SS BtoEe) { result = new )nteger(O). & & 2007 JavaOneSM Conference | Session TS-2707 | 59 . boolean toEe = rnd$ne.

e -een -o -ra++e& in egral %+es4 use i %else ins ea& of G : 2007 JavaOneSM Conference | Session TS-2707 | 5: .Moral ( Avoi& mi3ing %+es ( The G : o+era or has coun erin ui ive seman ics -hen use& -i h -o &ifferen -ra++er %+es ( "f %ou mus selec .

&@round Round( public class 4ound { public static void main(String[] args) { 4andom rnd = new 4andom().E.t)nt(). i (1ath$round(i) B= i) S'stem$out$println(9Fround 4ound9). & & 2007 JavaOneSM Conference | Session TS-2707 | 60 . int i = rnd$ne.

& & 0a1 7ever 0. int i = rnd$ne..1 Sel&om 0c1 Almos ever% ime i >s run 0&1 )ver% ime i >s run 2007 JavaOneSM Conference | Session TS-2707 | 6.1o. i (1ath$round(i) B= i) S'stem$out$println(9Fround 4ound9).t)nt().ften *oes It Print Fround 4ound+ public class 4ound { public static void main(String[] args) { 4andom rnd = new 4andom(). .

ina ion -i h 1ath$round0 loat) is <illing us# 2007 JavaOneSM Conference | Session TS-2707 | 62 .1 Sel&om 0c1 Almos ever% ime i >s run ? :8#7L of he imeF 0&1 )ver% ime i >s run Silen 4 loss% conversion from int o loat in com..1o.ften *oes It Print Fround 4ound+ 0a1 7ever 0.

out one . loat has E e4ponent . 2ou lose a.t)nt().its.nother /oo! public class 4ound { public static void main(String[] args) { 4andom rnd = new 4andom().it of precision for each oneF 2007 JavaOneSM Conference | Session TS-2707 | 6' . ++ ?his one gets invo=ed public static long round(double). int i = rnd$ne. i (1ath$round(i) B= i) ++ i 9promoted9 to S'stem$out$println(9Fround 4ound9). & & loat public static int round( loat).

i (1ath$round((double) i) B= i) S'stem$out$println(9Fround 4ound9). int i = rnd$ne.*o 2ou 3i4 It+ public class 4ound { public static void main(String[] args) { 4andom rnd = new 4andom().1o. & & 2007 JavaOneSM Conference | Session TS-2707 | 65 .t)nt().

Moral ( $ilent &-idenin#( conversion from int to loat is loss' and dan#erous ( Ei o for long o double ( The loat %+e is sel&om calle& forH use double ( Me ho& overloa&ing is &angerous4 +ar icularl% -hen com.ine& -i h une3+ec e& M-i&eningN 2007 JavaOneSM Conference | Session TS-2707 | 66 .

shar+ cornersOavoi& hemF ( Pee+ +rograms clear an& sim+le ( "f %ou aren> sure -ha a +rogram &oes4 i +ro.l% &oesn> &o -ha %ou -an ( $se Iin&Bugs*= i fin&s all 9 .ro her 2007 JavaOneSM Conference | Session TS-2707 | 68 .a.ugs in his al<F ( Eon> co&e li<e m% ."onclusion ( Java +la form is reasona.l% sim+le an& elegan ( Bu i has a fe.

.$hameless "ommerce *ivision ( :6 +u.les ( 62 illusions ( Tons of fun 2007 JavaOneSM Conference | Session TS-2707 | 67 .

Reven#e of the $hift. Episode VI: The PhantomReference Menace. Joshua Bloch Chief Java Archi ec !oogle "nc# Session TS-2707 2007 JavaOneSM Conference | Session TS-2707 | William Pugh Professor $niversi % of Mar%lan& .Java™ Puzzlers. ttac! of the "lone.

Sign up to vote on this title
UsefulNot useful