Java Puzzlers 239
Kylar writes "When you have spare time and decide to do something with a book (That's like an analog webpage, for the neuronauts among us), how often do you turn to a computer related book? How often has it happened in the last year? Right. The problem being that computer books are often either: a) boring, b) difficult to read, c) poorly written, or possibly: d) made of cheese." Read on for the rest of Kylars' review.
Traps, Pitfalls, and Corner Cases - Java Puzzlers | |
author | Joshua Bloch, Neal Gafter |
pages | 282 |
publisher | Addison-Wesley |
rating | 9 out of 10 |
reviewer | Tom Byrne |
ISBN | 0-321-33678-X |
summary | 95 Corner cases and traps that any serious java developer should be aware of (or entertained by.) |
Java Puzzlers is none of the above(*), being well written, amusing, whimsical, and above all, informative. Bloch and Gafter have brought us a book that entertains us with corner-cases, one-in-a-million chances and other happenings that explore the ins, outs, and guts of the Java Programming Language.
Anyone who has been a serious java programmer in the last several years should know the name Josh Bloch, and more importantly, should have read his book Effective Java. Josh, acting as java's platform architect has been directing and guiding Java into it's current incarnation as a mature, robust (Cue the laughter from the peanut gallery) programming language.
This book primarily references the Java 1.5 programming language, and some of the puzzles are 1.5-specific, although a significant portion of the problems are applicable to previous versions. Also, this book is aimed towards people who are competent-to-expert java programmers, and although there is a lot of good information, people who are new to Java will probably be a bit lost. As it stands, I have 7 years of Java experience, and I was only able to figure out about 15% of the puzzles without resorting to code, or more frequently the answer. The reason that I didn't stop to try out most of these problems is that the book is eminently readable, and difficult to put down (unusual for a computer book, and doubly so for one that delves deeply into a language specification document.)
This book dives into a lot of esoteric bits of the Java Language Specification, also known as "The Big Paper That Sometimes Tells Us Why Java Acts Like That," and there are lots of bits in there that don't even make sense, let alone seem intuitive.
Divided into 10 parts, each part presents a series of different code problems that usually present a small method or class that looks innocuous, but in reality exposes a piece of behavior that is strange, spectacular, or, more often, completely confusing. The book exposes flaws in the language, including one of my personal pet peeves, their inability to have a consistent Date object, and this is noted in Puzzle 62 by my favorite line in the book: "The lesson for API designers is: If you can't get it right the first time, at least get it right the second..."
One topic that I found was a continually recurring theme had to do with handling primitives and what happens when they are cast into different types. Java provides a lot of ways to deal with primitives, and for the most part, they play nicely with each other. There are several occurrences that really surprised me. A perfect example is the following innocent statements:
byte b = -1;
char c = (char)b;
so c=-1, right? Wrong. Places like this are things that you could potentially knock your head against the wall trying to figure out why something doesn't do what it appears to do.
(In this case, byte is signed, char isn't, and the widening cast fills in bits, leaving c=65535.)
A good job is also done describing best-practices for API and library designers, as well as us, the more mundane programmers.
The only downside (from my background and point of view - that of an applications architect, and not generally as a language or API designer) - is that some of the amazing optical illustrations can cause dizziness and nausea - although I can't guarantee that won't happen by the loops and twists that your mind will be tied into because of the puzzles.
Lastly, Bloch & Gafter include an appendix that serves as a summary to all the pitfalls and traps that are introduced in the book, and almost could be an appendix to Bloch's 'Effective Java'.
The bottom line is that in reading this book I learned a fair amount about several edge cases and issues that I had actually encountered - and it increased my understanding as to HOW java does things - although I'm fairly certain that I'll never understand the WHY. And most of all - I enjoyed this book, from start to finish, and that's rare, and worth the time.
You can purchase Java Puzzlers from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
I enjoyed Java Puzzlers, but... (Score:5, Funny)
master of the obvious (Score:2, Insightful)
That's not expected??
Kind of (Score:2, Insightful)
It has always diven me nuts how Java forces its own signed-ness on it's primitives. The fact that you can't have an unsigned int in Java 1.5 is a huge pain, because it is not like it is simpler to just use char everywhere, since then you lose all the autoboxing capability of Integer/int. So, you have to deal with it yourself. It's a big mistake IMO.
Re:Kind of (Score:5, Insightful)
Sigh... Not true. Wether chars default to signed or unsigned is vendor specific in the ANSI C spec. If you code depends on chars being signed or not then you have to state it explicitly if you want your code to be portable. I have been bitten by this on one important occasion when I was still in Industry and have never forgotten it.
Re:Kind of (Score:2)
Re:Kind of (Score:2)
Or even worse, the lack of an unsigned byte when reading in binary data structures. I don't claim to be a Java expert by any stretch (so I may be missing an obvious way to do this), but do you know how unnecessarily complex it is to convert a read-in byte to it's CORRECT unsigned value? Why isn't there an automatic way to do this at all? You can't just assign the byte to an int, as it'll still be negative (if above 127). I think in
Re:Kind of (Score:3, Informative)
Re:Kind of (Score:2)
But I will admit one point you have: reading in blocks of ints is another solution to my problem, as you could AND out each 8-bit component of what you want into another int (then shift obviousl
Re:Kind of (Score:2)
No, I'm responding to the right comment. I only mentioned chars in passing. I said ALL I/O uses Ints AND that this makes Unicode support easier.
But I will admit one point you have: reading in blocks of ints is another solution to my problem
Which was my point.
, as you could AND out each 8-bit component of what you want into another int (then shift obviously), and get the sam
Yikes! (Score:3, Funny)
Because characters aren't numbers. (Score:2, Insightful)
So given that characters aren't n
Re:Because characters aren't numbers. (Score:3, Informative)
Can't be helped. You have to give the computer a way of understanding characters. Array indexes are a natural way for computers to do that.
That's not to say the idea of a character coding that translates between characters and numbers isn't sensible, but the character itself is not a number - it's a character.
A character in Java *is* a character. Nothing more, nothing less. It's a character. What
Re:Because characters aren't numbers. (Score:2)
1. Input/Output. Since you only have numbers in computers, you have to transmit the characters somehow.
2. Logical operations. Character sets often have bit encodings or numerical spacings that easily allow for things like lower case to upper case.
But Unicode doesn't fit in
Re:master of the obvious (Score:5, Insightful)
This is why in computer science they have a term for supposed "idiosyncracies" like this: "Garbage In Garbage Out" (GIGO)
Re:master of the obvious (SPOILER) (Score:3, Informative)
Well, maybe that's the intended purpose. But its semantics don't sit totally easy with that. What does this print? (from p.25)
System.out.println('H' + 'a');
It prints '169'. The book goes on:
From a linguistic standpoint, the resemblance between char values and strings is illusory. As far as the language is concerned, a char is an unsigned 16-bit primitive integer - nothing more.
Yeah, in practice this
Re:master of the obvious (SPOILER) (Score:2)
System.out.println('H' + 'a');
It prints '169'. The book goes on:
The real problem is the overloading of the '+' sign. This is just more evidence that operator overloading is harmful in general purpose langauges. Sure, that '+' is convenient for putting strings together, but it does cost in clarity.
The reason for this behavior, BTW, is do you can do things like this:
Re:master of the obvious (SPOILER) (Score:2)
Re:master of the obvious (SPOILER) (Score:3, Interesting)
Yes it is indeed.
The JavaDoc for the Character class actually bemoans this in detail. My only point was that the Java Language allowed the numerical operations for such purposes. Writing a proper Unicode case converter is something that Sun has already done for us. (Thank God.)
And yet it keeps lots of old C syntax which gives you plenty enough rope to hang yourself with (from which flows several of the puzzl
Re:master of the obvious (Score:2)
Actually, the Java Language Specification is pretty clear that char is a number [sun.com]. From the spec:
char, being a number, is subject to integer math operations. Like someone posted, 'A' + 'B' comes up with the result 131 - as an int, at that, because all integer math on types
Re:master of the obvious (Score:2)
In other words, char represents a Unicode value from '\u0 to \uffff'. The fact that it can be cast to a numerical value and operated on is secondary to the fact that it's not really a number and should not be treated as such.
Re:master of the obvious (Score:2)
Not interested (Score:4, Funny)
/. is made of cheese (Score:4, Funny)
To the moon, Java!
is surprize good? (Score:3, Informative)
I'm somewhat puzzled by the premise of the book. I thought C/C++ was full of puzzlers, and that Java was supposed to fix all that. Puzzlers may be cute, but they are definitely bad (except for job security may be). BTW, my little test shows that this example also applies to C, except that it isn't as surprising since you have to specifically declare the variable as unsigned, e.g.
int b = -1;
unsigned char c = (unsigned char)b;
Without "unsigned", char is -1, as expected.
Thats the whole point of the "puzzler" (Score:5, Insightful)
Why should a primitive byte be signed, but not a primitive char?
And why can't I have an unsigned int primitive in Java?
Primitives in Java are a real pain to work with compared to most languages.
Re:Thats the whole point of the "puzzler" (Score:5, Insightful)
Because a byte is a numeric class, and a char is a character class? Your question is like asking why booleans can't be signed or unsigned.
Re:Thats the whole point of the "puzzler" (Score:2)
Off topic, but is there any C that defines sizeof(char) != 1? I'd be interested to
Re:Thats the whole point of the "puzzler" (Score:2)
Re:Thats the whole point of the "puzzler" (Score:5, Informative)
What's the difference between short and char in Java?
One is signed, the other is unsigned.
chars are treated just like numbers in Java. You can do numeric comparisons with them, you can add them, you can subtract them, they're just numbers.
By definition, a char in Java is a 16-bit unsigned value. It happens to represent a single UTF-16 sequence, although arguably you could have done that using a short.
But, here, check the language spec [sun.com]. A char is just an unsigned short. That's it.
Re:Thats the whole point of the "puzzler" (Score:2)
I think you misunderstand the spec. From your link:
For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
Just because it's a numerical value doesn't mean that it's an actual number.
chars are treated just like numbers in Java. You can do numeric comparisons with them, you can add them, you can subtract them, they're just numbers.
This is incorrect. If you
Re:Thats the whole point of the "puzzler" (Score:2)
And this differentiates char from short how, exactly?
The answer? A short gets translated to an int using a signed cast, and a char gets translated to an int using an unsigned cast.
Beyond that, the two data types are identical.
In fact, that whole "always convert to integer" thing essentially makes the use of bytes and shorts completely worthless outside of arrays, since all math done using them is just integer math.
Re:Thats the whole point of the "puzzler" (Score:2)
That's a good point. I supposed I should have also mentioned that byte and short are really just for low-footprint memory storage. 'int' is the currency of choice in the Java language. Casting up to int ensures that all math happens in a byte aligned fashion, not to mention that reduces the amount of silicon required by an embedded Java processor.
Re:Thats the whole point of the "puzzler" (Score:2)
You can't have an unsigned int primitive because that would lead to confusion when trying to index into arrays. The type of an array index is signed int, and is that way for a bounds checking reason. If you had access to a primitive unsigned
Re:Thats the whole point of the "puzzler" (Score:2)
That never really stuck me as a reasonable explanation.
I always felt it was a cop out at some level on the part of java to exclude unsigned ints. Its java, for christ's sake, can't the array bounds issue be taken care of?
Re:Thats the whole point of the "puzzler" (Score:2)
Frankly, I'm with you though, I wish they would just bite the bullet and fix up the raw types to have a signe
Re:Thats the whole point of the "puzzler" (Score:2)
there are only 256 potential opcodes. You'd need unsigned comparisons,
unsigned flavors of all the arithmetic operators for each data width and
so forth. Probably have to introduce a one-byte "unsigned" prefix, and you
might have to deal with the combination of the "unsigned" prefix and the
"far" prefix for conditional jumps. This would slow down, complexify, and
expand the size of the interpreter, which already takes 8 Meg to print
"Hello Wo
Re:Thats the whole point of the "puzzler" (Score:5, Insightful)
Bullshit. I've coded through asm, c, c++, java and they all have their own ways of doing things which you need to be aware of. The language is NOT the problem.
Re:Thats the whole point of the "puzzler" (Score:2)
Re:Thats the whole point of the "puzzler" (Score:2)
Because all numeric types are signed in Java, whereas char is not intended as a numeric type but rather a direct mapping to UTF-16 (which uses codepoints 0 through 65535). It makes perfect sense.
And why can't I have an unsigned int primitive in Java?
Highly debatable issue, but I think the simplification in types is worth more than unsigned types are.
Re:Thats the whole point of the "puzzler" (Score:2)
So, the types reflect the signedness of their use. However, I've rarely if ever used signed bytes... I have tons of (int)b&0xFF in my wire savvy code
Re:is surprize good? (Score:2, Informative)
By the way, here is a great online puzzlers lecture by the two same guys. Its located here: http://www.javalobby.com/av/javapolis/25/bloch-pu
Re:is surprize good? (Score:2)
Java is a quite a bit simpler than C++, but it certainly has its share of tricky corner cases and surprising features. I started reading through the first few chapters while browsing in a bookstore, and although I was quite proficient in Java years ago there were some puzzles that stumped me. It reminded me just how complicated parts of Java are. Anyone who claims to know Java
Re:is surprize good? (Score:2)
Re:is surprize good? (Score:2)
Re:is surprize good? (Score:2)
Actually it was invented in 1994 [about.com] and is younger than most big scriping languages today, many of which support arbitary sized numbers automagically (using int for numbers small enough internally and a more complicated type for big ones). There is absolutely no excuse for Javas flaws through the age argument. Most other languages invented around that time even managed to make the primitives look like objects from the language user point of view.
Re:is surprize good? (Score:2, Informative)
Without "unsigned", the signedness of char is undefined. See also the C standard (ISO 9899:1999).
Which explains why in C++ (a derived language) special specializations were made from templates to include both signed char and unsigned char, with a third charT template type for internal "char"-like data.
GCC includes a compile-time flag that allows you to make them unsigned (-funsigned-char).
Re:is surprize good? (Score:2)
Nitpick of the day: not "undefined" but "implementation defined".
In C's version of standardese, "undefined" basically means something you shouldn't ever do, but the compiler isn't required to stop you from doing. "Implementation defined" means something that may vary in some way from one compiler to the next, but that it's still perfectly reasonable to do.
--
The universe is a figment of its own imagination.
Re:is surprize good? (Score:2)
Java has a shit ton. The Java language spec is several times the size of C++. Its larger even if you ignore the standard libraries. And 1.5 is just adding on more cruft. THe only other language even close to Java on this front is perl.
Re:is surprize good? (Score:2)
NOW are you surprised?
Nope :)
Re:is surprize good? (Score:2)
Java puzzles? I do them everyday (Score:3, Insightful)
Unfortunately, real-life java problems are never very interesting.
Invariably the solution consists of editing an annoying xml config file, or perhaps correcting one of my daily misconceptions about some boring detail in whatever convoluted j2ee framework I am forced to work with.
Re:Java puzzles? I do them everyday (Score:2)
Re:Java puzzles? I do them everyday (Score:5, Insightful)
Virtually all real-life coding problems are uninteresting. It is nothing to do with Java.
Re:Java puzzles? I do them everyday (Score:2)
Re:Java puzzles? I do them everyday (Score:2)
Maybe I just haven't burnt out yet, but I find most [i]coding[/i] problems interesting.
Editing an XML configuration file isn't that interesting, I'll grant you that, but no one calls that "coding".
Code books in general? (Score:4, Insightful)
-Rick
Re:Code books in general? (Score:3, Insightful)
Re:Code books in general? (Score:2)
I'm sure (Score:3, Funny)
gcc puzzlers (Score:2)
Re:I'm sure (Score:2)
Would you settle for slightly different titles like these?
C Traps and Pitfalls [literateprogramming.com]
Enough Rope to Shoot Yourself in the Foot [holub.com]
Fortunately, there's also: :-)
The C Answer Book [about.com]
Which obviously has all the answers.
Actually, none of these is settling at all -- all three are excellent books, at least IMO. Much of Holub's book also applies about as well to Java as to C or C++, for that matter.
--
The universe is a figment o
Re:I'm sure (Score:2)
mmm... book made of cheese... (Score:2)
Online Version? (Score:3)
Re:Online Version? (Score:2)
Why yes there is:
http://msdn.safaribooksonline.com/?XmlId=03213367
Missing Option (Score:3, Insightful)
E) Out of date before the ink is dry.
Re:Missing Option (Score:3, Interesting)
disappointed -- try the java cert exam (Score:5, Insightful)
Have any other more interesting/fun examples?
If you want some puzzlers, look for copies of the Sun Java Programmer certification exam. There's lots of "we're not testing to see if you're a good programmer, just testing to see if you can find the unexpected result in the insanity-pepper code" snippets there.
boxlight
Re:disappointed -- try the java cert exam (Score:3, Insightful)
private int foo()
{
try
{
return 0;
}
finally
{
return 1;
}
}
Re:disappointed -- try the java cert exam (Score:4, Informative)
When the Java syntax was being invented (borrowed from C is more like it), this should have been addressed by disallowing return statements within finally blocks. The only way control should exit a finally clause is by falling out the end.
Re:disappointed -- try the java cert exam (Score:2)
I consider myself a somewhat experienced java developer, but they got me every single time. If you think you'r smart you certainly have to read this book, it'll slap you back to the ground.
Example (let's hope I don't violate any copyright here, my intentions are to get more copies sold anyway
Provide a dec
Another Example (Score:2, Interesting)
Re:Another Example (Score:2)
Garbage In, Garbage Out
SPOILER: Re:Another Example (Score:3, Informative)
public static void main(String[] args)
is the same as this:
public static void main(bad.String[] args)
and java can't find any main to execute because it is looking for:
public static void main(java.lang.String[] args)
See?
Re:disappointed -- try the java cert exam (Score:2)
Vg ybbxf yvxr cersvkvat n pbafgnag ol gur ahzore 0 vf n jnl gb fcrpvsvl gung gur ahzore vf va bpgny. Gurersber, 012 vf gur fnzr nf fnlvat bpgny 12, juvpu vf, bs pbhefr, gra.
However, I've never coded in Java, so that's just my uninformed guess. Regardless, that's a pretty good puzzler.
Re:disappointed -- try the java cert exam (Score:2)
012 = 12 (decimal)
0o12 = 10 (decimal)
0x12 = 18 (decimal)
0b12 = Fry says, "Its OK Bender. There's no such thing as two."
Analog? (Score:2)
Books are just as digital as webpages, with the possible exception of illustrations.
7 years with Java and... (Score:2)
char c = (char)b;
so c=-1, right? Wrong."
There are some fun to read CS books. (Score:2)
The Exceptional C++ [amazon.com] books are also easy reading.
It really just depends on what you want. Way back when I was first moving from C to C++, I bought the book Simple C++ [amazon.com]. While it was a good book that was easy to read, it took far too long for me to gleam the information
Typo (Score:2)
a char with a value of 65535? (Score:4, Insightful)
The correct value of is the glyph or other character corresponding to entry 65535 in whatever character encoding Java is currently using. (Assuming UCS-2, it's an invalid codepoint and therefore undefined.)
Yes, for purposes of demonstrating that is stored as a signed value and isn't the example is correct, but that's still a little more of an under-the-hood mentality that's more appropriate to C than to Java.
Re:a char with a value of 65535? (Score:2)
Now you're confusing the issue. You have conflated three distinct concepts -- a character code, which is a value denoting a specific character within a given encoding; a character, which is the abstract identity of a specific written glyph; and the glyph itself, which is a physical realization of the character in question. So no wonder you are confused.
A "char,
Oh come on! (Score:2, Insightful)
I know slashdot is hardly the pinnacle of good reporting, but that summary is bordering on t
Re:Oh come on! (Score:3, Funny)
Re:garbage collector (Score:3, Insightful)
Re:garbage collector (Score:2)
You're right though, most programmers worth a damn don't make assumptions like this when it comes to data type conversion.
It should be at least a little bit interesting to all, however, since the code is valid a
Re:garbage collector (Score:2, Insightful)
When we use big servers, Java 1.5, huge centralized clusters (offsite backup!), connection pooling, application level caching, big Oracle clusters, and pro (expensive) app servers (no tomcat) not only can we handle millions of cycles, we can handle a lot, lot, lot more at 6 sigma reliability and better.
I'm guessing your problem is a deeper architectural issue, not a "bug with Java".
Re:garbage collector (Score:2, Insightful)
Re:Puzzling indeed (Score:4, Insightful)
2) Speed of development.
3) Lack of "cute" features that break easily.
4) Javadoc!!
5) Bazillions of pre-written, pre-tested source-available library functions.
Re:Puzzling indeed (Score:2)
As far as I can tell, only 4 can qualify in favour of Java.
1, 2, 3 and 5, on the other hand, should drive devs towards Python or Ruby.
Re:Puzzling indeed (Score:2)
They may be strengths of python and Ruby(i don't have much ruby experience), but can you give examples of how they do not apply to java?
Re:How many java apps are you running? (Score:2)
I was using an object oriented version of Pascal (Turbo Pascal 7) before Java existed. My high school didn't teach the Object Pascal features, but they were there.
Java is being used heavily, but more for information systems work than software you'd buy at a store.
Re:How many java apps are you running? (Score:2)
Re:How many java apps are you running? (Score:3, Interesting)
My browser and email are actually written in Javascript with a small C core.
Re:Interesting? mod this clown down. (Score:3, Interesting)
Nope, Gecko is written in C++ but the whole Firefox interface, which is for all means and purposes "my browser" is written in XUL, which is nothing more than Javascript + CSS + XML.
Which is why you can get browsers such as K-Meleon, also based on Gecko and still different browsers (K-Meleon being written in C++/Win32).
Re:Puzzling indeed (Score:5, Funny)
From now on? Just to piss you off.
Re:Puzzling indeed (Score:4, Funny)
Ah, there's nothing more productive than starting up the "your language sucks, you should code in [insert my language of choice here] because it's what real programmers use" argument. I've yet to meet a coder whose ability I truly respected that ever got into such an argument. But, hey, maybe this is really useful. Under that guise, let's run the entire argument here and anytime you feel like a language being discussed is for half-wits, you can reference this.
So, here's the argument in order from first salvo to coup-de-grace
Re:Buy it here! (Score:3, Informative)
No you don't (Score:2, Funny)
Re:JAVA? (Score:2)
String s = new String(new byte[] { 0x41, 0x42, 0x43 }, "UTF-8");
To get "ABC". I haven't got a clue why you would want to do convert characters to or from *any* integer, unless you would like to write a ROT-13 codec. I laugh at languages that use *that* as a way to show their strength (and many do).
The book Java Puzzlers doesn't assume you would like to do something like that. The whole book is about getting a more complete understanding of the language