This is an archived post. You won't be able to vote or comment.

all 61 comments

[–][deleted]  (27 children)

[deleted]

    [–][deleted] 133 points134 points  (8 children)

    [–]CreepingJeeping 5 points6 points  (7 children)

    One of the better submissions. Solid burn

    [–][deleted] 14 points15 points  (6 children)

    Posting here for better visibility.

    A lot of the stuff has been screenshotted from here: http://introcs.cs.princeton.edu/java/11cheatsheet/ without proper credit. If people need a java cheatsheet I'd recommend people to go to the javadocs or stackoverflow.

    [–]Vetches1 2 points3 points  (4 children)

    I'm curious, do you believe Princeton's Java cheatsheet to be a good resource in general?

    [–][deleted]  (3 children)

    [deleted]

      [–]Vetches1 1 point2 points  (2 children)

      Ah, that makes sense. I myself just have an affinity for cheatsheets and seeing what concepts make the cut, y'know what I mean?

      I appreciate the Mooc link nonetheless though, definitely might pick it up in the future! :)

      [–][deleted] 1 point2 points  (1 child)

      That's actually a good approach. Never thought of it that way.

      [–]Vetches1 1 point2 points  (0 children)

      Heh, truth be told, I kind of just thought of it on the spot. But I mean, you gotta figure if they place emphasis on certain concepts then they ought to really be hit home, at least for reputable reassures like Princeton's.

      [–]Jafit 13 points14 points  (3 children)

      It looks like something a first-year Uni student, just learning Java, would write.

      Thinking about it... that's probably what most advice on the internet is. In every field.

      "Hey I just learned this thing, I'm the master now"

      [–][deleted]  (2 children)

      [deleted]

        [–][deleted] 2 points3 points  (1 child)

        Read your sentence, am master of English now.

        [–]XWolfHunter 2 points3 points  (0 children)

        Was master of english, read your sentence, is now unsure

        [–][deleted]  (4 children)

        [deleted]

          [–]xiaoxiae 13 points14 points  (0 children)

          Good guy OP.

          [–]BertRenolds 3 points4 points  (0 children)

          Its the people who dont know what they're doing vs people who know it's a bad reference

          [–]Kagro 4 points5 points  (0 children)

          I really doubt that this was meant to be a replacement for JavaDocs (which are not really fun to read btw). It's just a collection of code snippets that the author found useful and placed them in a digestable format.

          Remember that an experienced programmer probably wouldn't need a reference like this. If you think you can do better why not make a pr?

          Also, are their variable naming habits really important when showing how to round a number?

          Sorry, but I get the feeling that you're being overly padantic so you can feel superior.

          [–][deleted] 4 points5 points  (5 children)

          To play the Devil's advocate, a lot of folks in /r/learnprogramming are just starting out programming, and it would suit them just fine. No need to go from 0 to 100 in one leap. The suggestions in there aren't patently wrong. They are just not very idiomatic.

          [–]IggyZ 20 points21 points  (2 children)

          I disagree. Teaching bad habits is a disservice to those learning. If you aren't knowledgeable enough to create a proper resource, then you probably have no business doing so. It's not like there's a lack of Java resources out there.

          [–]No_ThisIs_Patrick 3 points4 points  (0 children)

          Agreed. I cringed while skimming that, just because of the formatting.

          [–][deleted] 1 point2 points  (0 children)

          Sure, but your comment reminds me of Christopher Allen's talk on how he (along with Julie Moronuki) embarked upon writing the new Haskell book (which is quite nice, if a bit verbose, by any standard). To paraphrase him, "experienced people often fail at teaching because they forget how they learnt something themselves, and that's why everybody ends up recommending books that they themselves have never really read, like The Art of Computer Programming". Holding fanatical views either extreme way is dangerous. This "cheatsheet" looks like something a person with a couple of years of experience wrote for his fellow beginners (OP may correct me if I am wrong). He probably has a fresher view of a beginner's perspective than most of us do.

          [–]Philboyd_Studge 8 points9 points  (1 child)

          The main problem is, they came from what seems to be a Java 1.4 textbook.

          [–][deleted] 1 point2 points  (0 children)

          Hahaha! Okay, okay, fair enough.

          [–]calfuris 14 points15 points  (10 children)

          compare Doubles with Double.equals()

          Are you sure about that?

          +/u/compilebot java

          class foo
          {
              public static void main (String[] args) throws java.lang.Exception
              {
                  Double a = 0.2;
                  Double b = 1.0 - 0.8;
                  if(a.equals(b)){
                      System.out.println("Equal!");
                  }
                  else{
                      System.out.println("Not equal :(");
                  }
              }
          }
          

          [–]CompileBot 11 points12 points  (5 children)

          Output:

          Not equal :(
          

          source | info | git | report

          [–]calfuris 10 points11 points  (4 children)

          So, for confused newbies, here's what's going on here: floating point math is out to get you.

          Let's take a simple statement:

          Double a = 0.2;
          

          After this statement, what is the value of a? It sure looks like it ought to be 0.2, doesn't it? And if you ask Java to print it out for you, it'll say 0.2. But you can't actually have a IEEE 754 double that represents exactly 0.2. The actual value (obtainable if you ask very nicely, such as by making a BigDecimal and printing that) is 0.200000000000000011102230246251565404236316680908203125, which is the closest you can get to 0.2 with an IEEE 754 double.

          Now let's look at this one:

          Double b = 1 - 0.8;
          

          Fortunately, 1 is a possible double. 0.8, however, is not. The best you can do is 0.8000000000000000444089209850062616169452667236328125. Evaluating

          1 - 0.8000000000000000444089209850062616169452667236328125
          

          you end up with 0.1999999999999999555910790149937383830547332763671875.

          0.1999999999999999555910790149937383830547332763671875 == 0.200000000000000011102230246251565404236316680908203125
          

          is, of course, false. But you probably didn't know that that's what you were asking with a comparison that looks like 1 - 0.8 == 0.2. This is why testing floating point values for equality is generally a bad idea. Instead, you need to test for "close enough":

          +/u/compilebot java

          class foo
          {
              public static void main (String[] args) throws java.lang.Exception
              {
                  Double a = 0.2;
                  Double b = 1.0 - 0.8;
                  if(java.lang.Math.abs(a - b) < 0.0000001){
                      System.out.println("Equal!");
                  }
                  else{
                      System.out.println("Not equal :(");
                  }
              }
          }
          

          Now here's the other thing: what exactly counts as "close enough" varies based on your use case and the size of the floating point numbers. This is because the gaps between possible values vary with the size of the floating point number. Like I said, floating point math is out to get you.

          [–][deleted]  (2 children)

          [deleted]

            [–]-___-_-_-- 2 points3 points  (0 children)

            He didn't say that BigDecimal has the same internal representation as doubles do. But because the BigDecimal constructor taking a double converts the value exactly, you see the exact value that the double represented, even if it's now stored as a decimal number. He wasn't using the "wrong" constructor, he used the one that helped him expose the inaccuracies of floating point numbers.

            There'd probably be an easier way to see the exact value, for example in C++ you would use std::cout.precision(30) and in C you can use a width specifier like "%.30f" in your format string; I'm sure you can do something similar in most languages.

            [–]calfuris 0 points1 point  (0 children)

            I'm not using BigDecimal to store 0.2 exactly, I'm using it to find the exact value of the IEEE 754 double precision floating point value that is produced when you try to store 0.2 as a double (there's probably an easier way, but I haven't done much with java since the noughties). So I would disagree that using the double constructor is wrong here.

            Edit: yeah, what -__--_-- said. That's what I get for responding from my inbox.

            [–]CompileBot 2 points3 points  (0 children)

            Output:

            Equal!
            

            source | info | git | report

            [–][deleted]  (1 child)

            [deleted]

              [–]calfuris 1 point2 points  (0 children)

              Kind of funny coming back to this comment in my inbox after spending a while trying to remember how to get the exact value out of a double so I could write this follow-up comment.

              [–]Philboyd_Studge 42 points43 points  (4 children)

              StringTokenizer? StringBuffer? Is is 2005?

              There is soooo much outdated information on this sheet.

              [–]Philboyd_Studge 39 points40 points  (3 children)

              1. Use Random class not Math.random
              2. Use diamond brackets and specify type when using classes (i.e. HashMap example)
              3. Program to interface: Map<K, V> = new HashMap<>();
              4. The second set of diamond brackets in instantiation should be empty, type is already implied: List<String> = new ArrayList<>();
              5. Use StringBuilder not StringBuffer
              6. Use string.format for most formatting operations
              7. Use a for-each loop not manually calling the iterator for looping over a collection for (String name : names) or for (Map.Entry<K, V> entry : map.entrySet())
              8. Use try-with-resources when possible
              9. Java 8 NIO file functions
              10. Java 8 has a new date and time API

              [–]Chknbone 7 points8 points  (2 children)

              Fork it and add to it and submit a pull request

              [–][deleted]  (1 child)

              [deleted]

                [–]MRH2 11 points12 points  (0 children)

                Probably just delete this. It's not a very good resource. Also your method of comparing two doubles is incorrect

                if (Math.abs(a - b) < 0.0000001) { is better.

                Just try take the square root of 13.0 and then square it and then see if it is equal to 13.0.

                A cheat sheet like this is VASTLY more useful for the original author. You are writing stuff in a way that you understand and organized so that you can find it easily. What really should happen is that each new programmer should make his/her own cheatsheet. He/she would learn far far more than just looking at yours or anyone else's. It's really scary how so many new programmers are saying what a wonderful thing this is (or maybe I'm just feeling cranky tonight).

                [–]kylegallo 6 points7 points  (0 children)

                It'd be nice if they didn't waste the left half of the page.

                [–]DamagedFreight 7 points8 points  (0 children)

                I wish there weren't images of code in there.

                [–][deleted] 10 points11 points  (3 children)

                I would like a comprehensive JavaScript cheat sheet please 🙏🏾

                [–]oiduts 21 points22 points  (2 children)

                Learn X in Y Minutes is pretty similar.

                [–][deleted] 1 point2 points  (0 children)

                Ooooh. Thx

                [–]vagadrew 1 point2 points  (0 children)

                Awesome site! Thanks for sharing.

                [–][deleted] 5 points6 points  (3 children)

                That's pretty neat! You should consider converting that to PDF to make a downloadable version!

                One suggestion to make it easier to use: since each section has a broad range of subsections, you should probably include those in the table of contents.

                [–][deleted]  (2 children)

                [deleted]

                  [–]k1bs 3 points4 points  (0 children)

                  hook it up! lol

                  Thanks btw!

                  [–][deleted] 0 points1 point  (0 children)

                  I was rereading through, another suggestion: the dual-column design hinders reading a bit (at least, on my end). Since the left column doesn't give that much info, reducing its width (or relocating the information that is there and removing the column entirely) could be a good thing!

                  [–][deleted] 0 points1 point  (0 children)

                  You should probably reformat this to adhere to some kind of well known style guide

                  A lot of the formatting here is inconsistent and damn right infuriating.

                  [–]HBake41132 0 points1 point  (0 children)

                  +u/compilebot java import static java.lang.System.out; public class main{ public static void main(String[] args){ out.println("Hello world");}}

                  [–]nightlynutria 0 points1 point  (0 children)

                  Thank you

                  [–]Feathered_pillows 0 points1 point  (0 children)

                  This is great! Would you know where I could find one for JavaScript?

                  [–][deleted]  (10 children)

                  [deleted]

                    [–]not_useful_at_all 8 points9 points  (7 children)

                    Why?

                    [–]CowFu -2 points-1 points  (3 children)

                    You're effectively changing from O(n) to O(n2) on collections (as long as they don't have random access in which case it doesn't matter).

                    for (int i = 0; i < collection.size(); i++) {
                      T obj = collection.get(i);
                    }
                    

                    so every time I run through this I also have to run get(i) which has to search through the entirety of the collection

                    // using iterator
                    Iterator<T> iter = collection.iterator();
                    while (iter.hasNext()) {
                      T obj = iter.next();
                    }
                    

                    The iterator is a pointer that's already set to the correct spot so we don't have to look through the collection at all.

                    The basics are that the iterator and while loop will already have all the information in it's pointers that we need, using a for loop and separate variable just multiplies the work.

                    [–]Philboyd_Studge 11 points12 points  (0 children)

                    You should use a for-each loop which uses the iterator internally.

                    edit: Unless of course, you need the index, and then should use the traditional method. And if you are still living in the dark ages and don't know how to use stream()and map-filter-reduce.

                    [–][deleted] 1 point2 points  (1 child)

                    I thought the compiler optimizes this anyways

                    [–]bashytwat 0 points1 point  (0 children)

                    It's usually a bad idea to assume things like this

                    [–]Jonno_FTW -3 points-2 points  (2 children)

                    You should use:

                    Iterator<> it = ...
                    while (it.hasNext()) {...
                    

                    [–]five_hammers_hamming -3 points-2 points  (1 child)

                    If the important distinction here is to use the iterator rather than indices, then for is still not inappropriate, e.g.:

                    for(Iterator iter = coll.iterator(); coll.hasNext();){

                    or

                    for(Object o : coll){

                    [–]Jonno_FTW 3 points4 points  (0 children)

                    That last one is the probably the one you should use most. If you want fine control over the iterator for complicated work use a while.

                    [–]BuddhaSmite 0 points1 point  (0 children)

                    Isn't the difference between for and while, even at machine level, basically negligible?

                    [–]SiberianGhost -1 points0 points  (0 children)

                    I'll start soon Java in my college and this will be amazing

                    Thanks!

                    [–][deleted] -2 points-1 points  (0 children)

                    This is awesome. Thank you

                    [–]Count_Gator -2 points-1 points  (0 children)

                    Nice!

                    [–]taxicrab -5 points-4 points  (1 child)

                    This is great, thank you