Slashdot Mirror


Java Puzzlers

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.

46 of 239 comments (clear)

  1. I enjoyed Java Puzzlers, but... by Anonymous Coward · · Score: 5, Funny

    ...it took a long time to load the first page. On the other hand, if you drop the book on the ground, it automatically throws itself into the garbage can.

  2. master of the obvious by hometoast · · Score: 2, Insightful
    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.)


    That's not expected??
    1. Re:master of the obvious by AKAImBatman · · Score: 4, Insightful

      Amen. The Java Language Specification states that char IS NOT A NUMBER. It's a character representation and should be treated as such. Thus the entire example is contrived, and makes no sense. It *might* be interesting from the perspective of loading a file (e.g. buffer.append((char)in.read());), except that the IO streams provide Integers to get around the sign problem.

      This is why in computer science they have a term for supposed "idiosyncracies" like this: "Garbage In Garbage Out" (GIGO)

  3. Re:garbage collector by Azarael · · Score: 2, Insightful

    I doubt that most experienced programmers would get hung up over the byte b example. I'm pretty sure that you'd get similar behaviour with C and a lot of other languages.

  4. Not interested by TreeHugger04 · · Score: 4, Funny

    If the title of a puzzle book does not contain the letters s,u,d,o,k and u in it, I am not interested. Sorry.

    --
    A citizen of America will cross the ocean to fight for democracy, but won't cross the street to vote in an election.
  5. /. is made of cheese by fohat · · Score: 4, Funny

    The problem being that Slashdot Headlines are often either: a) Dupes, b) boring, c) difficult to read, d) poorly written, or possibly: q) made of cheese

    To the moon, Java!

    --
    Is there heaven? Is there Hell? Is that a Tuna Melt I smell?-Primus
  6. is surprize good? by gtrubetskoy · · Score: 2, Informative
    There are several occurrences that really surprised me

    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.

    1. Re:is surprize good? by Anonymous Coward · · Score: 2, Informative

      Every language with some substance will evolve have its "puzzlers".

      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-puz zlers?source=archives but unfortunately you'll need to login to see it. Enjoy!

    2. Re:is surprize good? by dascandy · · Score: 2, Informative

      > Without "unsigned", char is -1, as expected.

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

  7. Yikes! by Anonymous Coward · · Score: 3, Funny

    If that c != -1 example isn't obvious, it may be safe to assume that former VB programmers have started programming in Java! Run!

  8. Thats the whole point of the "puzzler" by brunes69 · · Score: 4, Insightful

    It is to expose a flaw in the language.

    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.

    1. Re:Thats the whole point of the "puzzler" by $RANDOMLUSER · · Score: 4, Insightful
      > Why should a primitive byte be signed, but not a primitive char?

      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.

      --
      No folly is more costly than the folly of intolerant idealism. - Winston Churchill
    2. Re:Thats the whole point of the "puzzler" by kaffiene · · Score: 4, Insightful

      >Primitives in Java are a real pain to work with compared to most languages.

      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.

    3. Re:Thats the whole point of the "puzzler" by _xeno_ · · Score: 4, 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. A char is just an unsigned short. That's it.

      --
      You are in a maze of twisty little relative jumps, all alike.
  9. Re:Puzzling indeed by $RANDOMLUSER · · Score: 3, Insightful

    1) Code readability.
    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.

    --
    No folly is more costly than the folly of intolerant idealism. - Winston Churchill
  10. Because characters aren't numbers. by MS-06FZ · · Score: 2, Insightful

    I think the whole notion of a "character" type being assigned a numerical value is dubious in the first place. 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. I like Python's approach to the solution - there simply is no "atomic" character type (defining such a thing when character sets have characters that aren't uniform size is questionable anyway)

    So given that characters aren't numbers, is it really so hard to imagine that people see that code and can't readily guess what sort of number a character is? I guess one could say that the character set is indexed with non-negative integers, so the character type should be non-negative - but a logical derivation isn't the same as a plain fact, and other languages aren't so sensible in those kinds of decisions...

    --
    ---GEC
    I'm but the humble pupil, seeking to snatch the scratchbuilt pebble from the master's fully articulated hand
    1. Re:Because characters aren't numbers. by AKAImBatman · · Score: 2, Informative
      I think the whole notion of a "character" type being assigned a numerical value is dubious in the first place.

      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 the author did was stupid. The only time you cast a character like that is when you're doing I/O. For example:
      InputStream in = new FileInputStream("Text File.txt");
      StringBuffer string = new StringBuffer();
      int data;
       
      while((data = in.read()) >= 0)
      {
          string.append((char)data);
      }
      Note that in.read() returns an Integer of byte data, so the sign problem never shows up.

      I like Python's approach to the solution - there simply is no "atomic" character type (defining such a thing when character sets have characters that aren't uniform size is questionable anyway)

      Java Characters *are* a uniform size. Every character is a 16 bit Unicode character. That's why you're not supposed to do what I just did in the example above (read in a byte at a time) because you may chop up the Unicode encoding. Instead you're supposed to use a Reader object, which will return 'char' values instead of 'int' values.
  11. Java puzzles? I do them everyday by helix_r · · 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.

    1. Re:Java puzzles? I do them everyday by Decaff · · Score: 4, Insightful

      Unfortunately, real-life java problems are never very interesting.

      Virtually all real-life coding problems are uninteresting. It is nothing to do with Java.

  12. Code books in general? by RingDev · · Score: 3, Insightful

    Why bother? I have 1 HTML/CSS book I keep on hand just because I've used it so much. Everything else, I use google. Its faster (for me) to find designs, references, and code samples online then it is for me to get a book, look up the index and flip through the pages. I even gave up on my old SQL bible as Google can get me syntax and samples faster then I can find them in the book.

    -Rick

    --
    "Most people in the U.S. wouldn't know they live in a tyrannical state if it walked up and grabbed their junk." - MyFirs
    1. Re:Code books in general? by ForumTroll · · Score: 2, Insightful

      The tutorials and code samples that are online are often trivial when compared to the in depth detail that you will find in a good book. Also, they're often out of date and some what misinformed. Don't get me wrong, I've done a lot of research online and lots of the information was very well presented and put together however I don't think I've ever seen a tutorial or paper that is as good or equivalent to some of the professionally written books available. I also hate reading large books or tutorials online. Perhaps, it's just a personal preference of mine.

      On a side note, if I had something that was small and lightweight I would probably start using http://safari.oreilly.com/">Safari Bookshelf. For several reasons, I just can't seem to enjoyably read an entire books worth of information sitting at my desk reading off a monitor.

      --
      "A Lisp programmer knows the value of everything, but the cost of nothing." - Alan Perlis
  13. I'm sure by jkind · · Score: 2, Funny

    I'm sure a book called C Puzzlers would sell at least twice as well as this.

    --
    ~jennifer.k~
  14. Re:Buy it here! by Anonymous Coward · · Score: 3, Informative

    I'm curious as to why this user's post was marked "informative". There are many places to buy the book, and the story provided one. In fact, the only significant difference between this link and the story is that this person has apparently posted a referral link to make some money.

  15. Online Version? by kevin_conaway · · Score: 2

    Is there an online version? This seems like the type of thing I'd do on my lunch break or when I need a diversion. Something along the lines of the Python Challenge, would be cool. To me, it seems more natural to do these puzzles in soft form.

  16. Re:Kind of by codegen · · Score: 5, Insightful
    See, to a C coder, this is non-obvious because both the types would be signed, and if you wanted it unsigned you would have to say so.

    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.

    --
    Atlas stands on the earth and carries the celestial sphere on his shoulders.
  17. Missing Option by Anonymous Coward · · Score: 3, Insightful

    Most technical books are: ...

    E) Out of date before the ink is dry.

    1. Re:Missing Option by Miniluv · · Score: 2, Interesting

      Thats why I buy technology books instead. If I want a technical reference I use the internet, but if instead I want a book that explains the concepts and assumptions of a specific technology, and then walks through some use cases where the technology makes sense versus some where it doesn't, then it won't go out of date until that whole technology does. I've gotten a tremendous benefit from reading books like this on SANs, performance optimization, various wireless technologies, SIP, etc. All techs that have been around for years, show no signs of disappearing, and none of the books talked about how to implement them using a specific vendor solution, but instead talked about how to evaluate the overall environment and determine if the technology was right.

  18. disappointed -- try the java cert exam by SamSeaborn · · Score: 4, Insightful
    I was excited when I saw the "Java Puzzlers" subject heading. But that byte to char example left me under-whelmed.

    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

    1. Re:disappointed -- try the java cert exam by mmusson · · Score: 2, Insightful

      I enjoy obscure code examples as an antidote to drinking the Java is perfect Koolaid. Examples like:

         private int foo()
         {
            try
            {
               return 0;
            }
            finally
            {
               return 1;
            }
         }

      --
      SYS 49152
    2. Re:disappointed -- try the java cert exam by pclminion · · Score: 3, Informative
      At least you get a warning when compiling that code: "finally clause cannot complete normally."

      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.

  19. Re:Puzzling indeed by greg_barton · · Score: 5, Funny

    Why would anyone use Java?

    From now on? Just to piss you off.

  20. Re:How many java apps are you running? by masklinn · · Score: 2, Interesting
    hint: your browser, email, OS, shell, image editor, spreadsheet, wordprocessor are

    My browser and email are actually written in Javascript with a small C core.

    --
    "The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
  21. No you don't by jpardey · · Score: 2, Funny

    Some of us don't hate gay people, while still hating the word "Neuronaut."

    --
    I have freaks! I did something right...
  22. Re:Interesting? mod this clown down. by masklinn · · Score: 2, 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).

    --
    "The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
  23. a char with a value of 65535? by poot_rootbeer · · Score: 3, Insightful
    (In this case, byte is signed, char isn't, and the widening cast fills in bits, leaving c=65535.)
    char
    , being a character datatype, shouldn't have its value expressed as an integer.

    The correct value of
    c
    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
    int
    is stored as a signed value and
    char
    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.
  24. Re:master of the obvious (SPOILER) by ishepherd · · Score: 3, Informative
    The Java Language Specification states that char IS NOT A NUMBER. It's a character representation

    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 sort of thing is mainly irrelevant, because you wouldn't actually USE chars like that. Still, it's interesting stuff.

    --
    fud, notfud, yes, no, maybe
  25. Oh come on! by Xarius · · Score: 2, Insightful

    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.

    I know slashdot is hardly the pinnacle of good reporting, but that summary is bordering on the idiotic. Were those daft little bits of meaningless fluffy non-humour put in there simply to up the word count?

    --
    C17H21NO4
    1. Re:Oh come on! by Surt · · Score: 2, Funny

      Perhaps kylar has been submitting a lot of stories, gradually moving where he inserts the random garbage into the story description, to find out just how far the slashdot editors will read before posting a story. His research seems to indicate the slashdot eds give up around 350 characters.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
  26. Another Example by Anonymous Coward · · Score: 2, Interesting
    I've been to one of their talks -- they work at Google, and give occasional tech talks for the other engineers. Here's an example that they actually got from somebody else: it was accompanied by some general banter, and multiple options. (Disclaimer: I don't know if this is in the book.)
    public class bad {
        public static void main(String[] args) {
            bad.String s = new bad.String("hello");
            System.out.print(s + " ");
            bad.String t = new bad.String("goodbye");
            System.out.println(s);
        }
        static class String {
            java.lang.String s;
            public String(java.lang.String t) {
                s = t;
            }
            public java.lang.String toString() {
                return s;
            }
        }
    }
    What does the code above do?

    a) Print "hello hello"
    b) Print "hello goodbye"
    c) Compile error
    d) Other

    Some banter of my own, roughly:
    Well, let's see. This seems like bad code, since why would you name a class String, but sure. So each bad.String has a java.lang.String inside it, and when you construct a new bad.String you get an object that contains the java.lang.String that you constructed it with. Of course, the toString() method just returns the java.lang.String that it stores. So first we make a String with "hello" and then we print it, followed by a space, and then we make a String with "goodbye", and print "hello" again. So I think this program should print "hello hello".

    I'll post the answer later if nobody gets it, but you can always try it yourself. I do recommend thinking about it, though: it's cute. Note that everything I said in the banter, except for what I think the answer is, is true.
  27. Re:Puzzling indeed by mrbuckles · · Score: 3, Funny
    He'll be here all week, folks.
    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

    1. [Language being discussed] is for n00bs! You should code in [language-1]
    2. Ha! You think [language-1] is great? I agree you're not as l4m3 as the n00bs who code in [language being discussed], but please -- time to go to [language-2]
    3. *Sigh* I'm so amused (not) when I come to /. and see you [language-2] coders flaming [language being discussed] coders or even [language-2] coders. It's all a bunch of crap and explains why so much money is spent tracking down buffer overflows and other security flaws. Get to machine language or get out!
    4. I use 3 keys when I program -- 0, 1 and enter. Bitches!
  28. Re:garbage collector by Heembo · · Score: 2, Insightful

    > When we moved into millions of cycles per second (big big solaris servers) we had similar problems...

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

    --
    Horns are really just a broken halo.
  29. Re:master of the obvious (SPOILER) by AKAImBatman · · Score: 2, Interesting

    Hmmm, but proper (internationalized) case conversion is ridiculously more complicated than that.

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

    That much is easy to answer. Java started its life as a new C++ compiler that didn't require a recompile of the entire project when just one class changed. To meet that goal, Gosling turned to using bytecode. That partly solved the problem, but he found he had to make several language changes to keep classes separate. By the time he was done, a new language had emerged.

  30. Re:garbage collector by bryanmanwaring · · Score: 2, Insightful

    It never ceases to amaze me how naive people can be when it comes to Java. The truth is, the underlying VM is a different technology than the "Manage it yourself" tradition of C/C++. While garbage collection is an additional process that occurs in a VM environment such as Java or .NET, there are peformance advantages to using such a process. (And no, I am not refering to the programmer laziness argument about not having to manage memory in Java... I am talking about the efficiency of allocation and deallocation that a Java VM affords)

    I do not plan on engaging in any arguments back and forth about the two types of memory management... But if you are truly interested in an article that means to show the reality of the "performance characteristics" of a Java VM, please read the article listed below. It is truly a well written article and worth the read.

    http://www-128.ibm.com/developerworks/java/library /j-jtp09275.html?ca=dgr-lnxw01JavaUrbanLegends

  31. Re:Kind of by MillionthMonkey · · Score: 2, Informative

    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 the end I just asigned the byte to an int, then did a bitwise-AND to throw out the extra sign bits it tacked on in the widening conversion so that it was back to positive.

    InputStream.read() doesn't return a byte. It returns an int between 0 and 255 inclusive. -1 means EOF. The most common idiom is to do something like this:

    int i;
    int numRead = 0;
    while ((i=inputStream.read()) >= 0)
        someByteArray[numRead++] = (byte)i;


    For bytes with values between 128 and 255 inclusive, the values will become negative. And why do you care? As long as every single one of the eight bits in each byte is correct, signed vs. unsigned is in the eye of the beholder. It doesn't enter into anything unless you start doing arithmetic on the bytes or print their numeric values, both of which involve implicit casts to int. To do arithmetic, Java always converts a byte, char, or short to int using an automatic, implicit cast (it converts float to double as well). If the bytes have unsigned semantics in your program, then never allow the compiler to implement an implicit cast since implicit casts assume signed values. Replace them with explicit casts that mask out the top 24 bits to zero yourself, preserving the semantics with respect to sign:

    int intVal = (0xFF & byteVal)

    When evaluating this expression, byteVal will be implicitly cast to a signed int and then the & operator zeroes out the sign extension bits to preserve semantics. Is this "unnecessarily complex"? I don't think so. I rarely even need to do it.

    This seems to horrify people used to the unsigned-type train wreck in ANSI C but I would not welcome unsigned types being added to Java at all. The existing type system in Java is perfectly adequate for getting work done and you don't have to keep remembering whether variables were declared as signed or not if you know they're always signed.

  32. SPOILER: Re:Another Example by Q2Serpent · · Score: 2, Informative

    Since there is a String class that exists within the bad class, this prototype:

        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?

  33. Re:Not interested...in sudoku by extremely · · Score: 2, Insightful

    If you have a super fast solution to the sudoku puzzle family you should probably write it up. Sudoku is NP-complete... if you've solved it then you've cracked every encryption protocol known to man...

    --

    $you = new YOU;
    honk() if $you->love(perl)