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.re removin# )nteger values 2007 JavaOneSM Conference | Session TS-2707 | 8 .ove The set contains Short values.1 "!! 0c1 Thro-s e3ce+ ion 0&1 7one of he a.ut -e.

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

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

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

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 | .ollection<->$remove a<es /b0ect4 no ( Also .0 .Moral • .

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

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

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

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

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

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

7 .ode aren> -ell &efine& ( The% &o no o.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 | .Moral ( Eo no use 345 as a Set elemen or 1ap <e% • e>uals an& hash.

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

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

1o..t #et a chance to see -hether assertion succeeds or fails 2007 JavaOneSM Conference | Session TS-2707 | 20 .ften *oes This Test Pass+ 0a1 " 0.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 ? .

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

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

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

H'0 PM?2H'0 PM 2007 JavaOneSM Conference | Session TS-2707 | 25 .es ne.frame-or< o .e er han&le his si ua ion ( Thurs&a%4 .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.

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

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

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

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

private public inal Eoolean alive = 5)D)7F. & & 2007 JavaOneSM Conference | Session TS-2707 | 2: .reate singleton 2a ter2 initiali(ing other public static inal -lvis -5D)S = new -lvis().*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). ields ++ .1o. inal Eoolean lives() { return alive.

ception ( Wa ch ou for circulari ies in class ini iali.ime cons an s4 ei her ( Au o-un.o3ing can occur -hen %ou leas e3+ec i ( " can cause 7ullHointer-.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-.a ion '0 2007 JavaOneSM Conference | Session TS-2707 | .a ion ( Cons ruc ins ances a en& of class ini iali.

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

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

0in +rac ice1 0.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.)hat *oes It Print+ 0a1 . 2007 JavaOneSM Conference | Session TS-2707 | '' . lso it is difficult to use correctl'.

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

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

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 .

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

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

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

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

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

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

C.tEoolean().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("). & $ea of Trou. boolean toEe = rnd$ne. S'stem$out$println(result). & & 2007 JavaOneSM Conference | Session TS-2707 | 5' .

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

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

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

2#2#71# 2007 JavaOneSM Conference | Session TS-2707 | 57 .o4in# conversion 6D?. .4 T21 0K.inar' numeric promotion performs un.% 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 .E7 to numeric t'pes. ( O her-ise4 he secon& an& hir& o+eran&s are of %+es S.%. .le in %+e .%. and the t'pe of the conditional e4pression is the promoted t'pe of the second and third operands.#. an& S2 res+ec ivel%# Ae T.% e4 hen he %+e of he con&i ional e3+ression is . :ote that .ther-ise. then there are several cases: J "f one of he o+eran&s is of %+e .e he %+e ha resul s from a++l%ing .%97.e he %+e ha resul s from a++l%ing .E7 and value set conversion 6D?.le in %+e char4 hen he %+e of he con&i ional e3+ression is char# ( .oolean an& he %+e of he o her is of %+e Boolean4 hen he %+e of he con&i ional e3+ression is . if the second and third operands have t'pes that are converti.0T.o3ing conversion o 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 .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.ther-ise.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% .6#.le 6D?.4 an& le T2 .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.01 o lu.nother /oo! 657 8 G: $pec 6J/$ %?.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.%.% 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.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# ( .B.inar' numeric promotion 6D?.57 is applied to the operand t'pes.

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

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 .e -een -o -ra++e& in egral %+es4 use i %else ins ea& of G : 2007 JavaOneSM Conference | Session TS-2707 | 5: .

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

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

ften *oes It Print Fround 4ound+ 0a1 7ever 0.1o..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.ina ion -i h 1ath$round0 loat) is <illing us# 2007 JavaOneSM Conference | Session TS-2707 | 62 .

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

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

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 .

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

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

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