TS-2707 | Software Engineering | Computer Programming

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

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

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

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

i < "!!.1o. s$remove((short) (i * ")). or(short i = !. i##) { s$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>(). & & 2007 JavaOneSM Conference | Session TS-2707 | : .

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

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

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

)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 | .1 6 0c1 8 0&1 7one of he a.' .s e>uals and hash.ove ? i varies from run o run 345.ode are .

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

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.o h hos names can .o h hos names eCual o null# Since hos s com+arison reCuires name resolu ion4 his o+era ion is a .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 .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.

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

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

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

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

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

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

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

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

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.es ne.H'0 PM?2H'0 PM 2007 JavaOneSM Conference | Session TS-2707 | 25 .

=. & 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(). inal Eoolean alive = 5)D)7F. private -lvis() { & private static private public inal Eoolean 5)D)7F = true. & & 2007 JavaOneSM Conference | Session TS-2707 | 26 . inal Eoolean lives() { return alive.

& & 2007 JavaOneSM Conference | Session TS-2707 | 28 .ove public class -lvis { ++ Singleton pattern: thereCs onl' one -lvis public static inal -lvis -5D)S = new -lvis(). inal Eoolean lives() { return alive.1 Heartbrea= Hotel 0c1 " varies 0&1 7one of he a. 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).)hat *oes It Print+ 0a1 Hound Aog 0.

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

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

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

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

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

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

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

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

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

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 .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 .

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

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

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.ove ? hro-s 8rra'/ut/ Eounds-.er4 an& so can he M o+era or 2007 JavaOneSM Conference | Session TS-2707 | ': .1 .

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

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

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 .R ) M buc=ets$length ( Or use +o-er-of.uc<e • 1ath$abs(hashDal M buc=ets$length) ( Or (hashDal >>> ") M buc=ets$length ( Or (hashDal Q !.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 .

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

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

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

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

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

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

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: .

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

t)nt()..1 Sel&om 0c1 Almos ever% ime i >s run 0&1 )ver% ime i >s run 2007 JavaOneSM Conference | Session TS-2707 | 6. . & & 0a1 7ever 0. int i = rnd$ne. i (1ath$round(i) B= i) S'stem$out$println(9Fround 4ound9).1o.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 .1o.ften *oes It Print Fround 4ound+ 0a1 7ever 0..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.

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

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

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 .

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

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

ttac! of the "lone. 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& . Reven#e of the $hift.Java™ Puzzlers.

Sign up to vote on this title
UsefulNot useful