Hacker News new | past | comments | ask | show | jobs | submit login
Java 7 is now available (oracle.com)
341 points by Mitt on July 28, 2011 | hide | past | web | favorite | 204 comments



You can now finally use a string in a switch statement, hurray (it's the little things that make me happy)!

http://download.oracle.com/javase/7/docs/technotes/guides/la...


God, I seriously hope string-switching doesn't catch on.

In a prev job, I saw this block of code -

-------

public int getDaysInMonth( String month ) {

  if( month.equalsIgnoreCase("january")) return 31;

  else if( month.equalsIgnoreCase("february")) return 28;

  else if( month.equalsIgnoreCase("march")) return 31;

  else if( month.equalsIgnoreCase("april")) return 30;

 ...
}

-------

My eyes bled. I said folks, just map the month to an int M in range [1..12] and simply write 1 line of code

return 30+((M+Math.floor(M/8))%2;

( except for 2, which is 28 or 29 depending on a leap year)

I was overruled. "We are programmers, not mathematicians" was the response!!!

Now they'll happily use this string-switch to do

---------

switch( month.toLowerCase() ) {

  case "january" return 31;

  case "february" return 28;

  case "march" return 31;

  case "april" return 30;
...

  default : return -1;
}

-------

which is an even nastier abomination :(


Using a contrived formula that's difficult to understand or quickly check for correctness to solve a problem whose answer doesn't come from anything mathematical (i.e., the number of days in each month were arrived at arbitrarily, not via any formula) and just happens to work is NOT good style. At best it's cute and irrelevant (and doesn't even work for all of the twelve cases...). Wow.

Edit: also, if you're mapping the month string to an integer anyway, I don't see how you're going to do that without doing basically the same thing as the switches you posted anyway.


I have to say, I think it's easier to verify the correctness of

    [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30,  31, 31, 30, 31, 30, 31][M-1]
than your formula. Even a dictionary wouldn't be bad. And if it were wrong, it would be easier to fix it.


Correctness should be verified by tests not 'looking at the code'.

The aforementioned code can never be verified as correct because February requires a year to be present to know the number of days.

Doesn't java have a massive calendar library to address exactly these sorts of human questions?

I mean sure you'd still be looking at code like:

  public int getDaysInMonth(DateTime date) throws
    CalendarFactoryFactorException,
    DateOutOfRangeException,
    ArrayOutOfBoundsException 
  {
    CalendarFactoryFactory factoryMaker = new CalendarFactoryFactory("Western");
    GregorianCalendarFactory gregFactory = factoryMaker.getGregorianFactory();
    Calendar c = gregFactory.createCalendar(new DateTime());
    return c.getDaysInMonth();
  }


> Correctness should be verified by tests not 'looking at the code'.

Tests can prove the presence of bugs, but they are (in general) hopelessly inadequate to prove their absence; and once a test finds a bug, you still have to be able to understand what the code is doing in order to fix the bug.

In practice, code inspections and tests find quite distinct sets of bugs with some overlap, so it's valuable to do both of them. That's why all decent programming processes require both.

(This is probably one of the few cases where you could in fact verify that the code is correct by exhaustive testing — but only by comparing it against a known-correct implementation.)


Yes, something like that. But better use joda time because the standard API sucks. joda: new DateTime().monthOfYear().getMaximumValue()


Your one-liner is more difficult to understand. The string switch is very explicit and understandable.


To be honest your one liner takes me a while to parse and you forgot to close a parenthesis. OTOH It is really hard to read or write that switch incorrectly.


Are you serious? An "abomination"? The switch statement is fine, and using an array [31, 30, 31 ...] would be fine as well. Your 1 line isn't really 1 line because you have to convert the month to an integer anyway, and then the array lookup is even shorter than your solution.


Why did you need string-switching? You could have created a Map<String, Integer> lookup table.


I have to admit - I never even thought that there would be an easier math-formula way to calculate it. Though I would have written the switch:

  case "september":
  case "april":
  case "june":
  case "november": return 30;
It's sad, but still need to go through the poem in my head to remember most of the time.



Hope I never have to maintain pseudo-mathematical code like the one you were (thankfully) asked to revert.


This one is easier to understand imho: 30+(1&(5546>>M)) (also except for M=2)


Well done! Could you elaborate on how you came up with 5546 ? Perhaps there's a simpler technique than the one I describe below. btw, this was the technique that I learnt in school -

1. You have 12 months. Ignore February. Then you have 11.

2. The remaining 11 map to either 30 days or 31 days . ie. 30+0, or 30+1.

3. So the object is to write a many-to-one function that maps some members of the set to 0, rest to 1. Add 30 and you get the right answer ie. number of days in that month.

4. So you want to map {1,3,5,7,8,10,12} to 1, and {4,6,9,11} to 0.

5. Write down a 13 bit number. If you rightshift x times and AND it with unity, you get 1.

6. So then, x belongs to {1,3,5,7,8,10,12}.

7. That means the bit in each of those locations must be on. The rest of the bits must be off. That gives you the number 1010110101010, which is simply 5546 in decimal.

8. So that's ((5546>>M)&1)+30, except for M==2.


IntelliJ IDEA strongly suggests to turn those Strings into constants. And then to turn those constants into an Enum. Oh wait, we could also switch() on Enum values!

I'm sure this is useful in some cases though :-)


Wouldn't it be better to configure the switch options in an xml configuration file?


I would like to vote you up for the chuckle, but this being Java, I can't tell for sure if you're joking...


InvokeDynamic is a pretty awesome new feature in JDK7 and will likely be tranformative for dyanmic languages on the JVM. For my mustache.java templating solution it increased performance on an integration benchmark by 25%.

http://groups.google.com/group/mustachejava/browse_thread/th...


Did they always have this clause in the Java license, or is it new to Oracle's release?

"These Supplemental License Terms add to or modify the terms of the Binary Code License Agreement....

A. COMMERCIAL FEATURES. You may not use the Commercial Features for running Programs, Java applets or applications in your internal business operations or for any commercial or production purpose, or for any purpose other than as set forth in Sections B, C, D and E of these Supplemental Terms. If You want to use the Commercial Features for any purpose other than as permitted in this Agreement, You must obtain a separate license from Oracle."

Sections mentioned are: B. SOFTWARE INTERNAL USE FOR DEVELOPMENT LICENSE GRANT. ... Oracle grants you a non-exclusive, non-transferable, limited license without fees to reproduce internally and use internally the Software complete and unmodified for the purpose of designing, developing, and testing your Programs.

C. LICENSE TO DISTRIBUTE SOFTWARE. ... Oracle grants you a non-exclusive, non-transferable, limited license without fees to reproduce and distribute the Software, provided that (i) you distribute the Software complete and unmodified and only bundled as part of, and for the sole purpose of running, your Programs, (ii) the Programs add significant and primary functionality to the Software, (iii) you do not distribute additional software intended to replace any component(s) of the Software, (iv) you do not remove or alter any proprietary legends or notices contained in the Software, (v) you only distribute the Software subject to a license agreement that: (a) is a complete, unmodified reproduction of this Agreement; or (b) protects Oracle's interests consistent with the terms contained in this Agreement and that includes the notice ...

D. LICENSE TO DISTRIBUTE REDISTRIBUTABLES. ... Oracle grants you a non-exclusive, non-transferable, limited license without fees to reproduce and distribute those files specifically identified as redistributable in the README File ("Redistributables") ...

E. DISTRIBUTION BY PUBLISHERS. This section pertains to your distribution of the JavaTM SE Development Kit Software with your printed book or magazine ....

Maybe I'm reading too much into it, because of the Android lawsuit?


The licence has always had similar terms.

Specific to (A), that is regarding the JDK (as opposed to the JRE). As mentioned elsewhere, you can't redistribute tools.jar, and I think the compiler itself is a problem too.


Without the definitions (especially of "Commercial Features", this doesn't really mean much. I'm sure restrictions and rules on distribution have always existed, since we ran into issues with redistributing tools.jar back in 1999/2000.


Meh. The world turns. I spent a decade developing primarily in Java, and the last few years were really disappointing. The community splintered, the language and platform really lost any ability to maintain momentum. I might have been stoked about Java 7 three years ago (when it should have come out).


I don't know if I agree. The Java language has floundered (I've been stuck coding in it for the last couple of years), but I think the platform/JVM has started becoming used more and more often for new + exciting language options. The new release should make implementing dynamic languages on top of the JVM easiser, and could open the doors for a lot of interesting options.


I don't think I would say it's floundered. I came back to Java last year after 10 years of C++, and was really pleasantly surprised: Programming in Java now is a nice experience. I would say it has matured, not floundered.


You're comparing one circle of hell to a deeper circle of hell, though.

The comparison isn't Java to C++. It's Java to C#, Scala, even Python or Ruby. And against C# and Scala in particular, Java does very poorly.


By very poorly I would guess it would depend on how your comparing them. In my experience working with Java, C#, Scala, Python and Ruby all of them were fantastic. The only time I have ever considered a language a "deeper circle of hell" was with (large team) php and perl projects.


I think it depends on the time frame you look at. I started in Java back w/ some of the pre 1.0 releases. Between then and now, it's come a really long way.

Maybe I'm biased due to other new(er) languages becoming mainstream. But it feels like Java (as a language) has fallen behind as other Languages adopt new features that cater to different/modern techniques.

Java won't ever be cutting edge (and given the types of applications that are built with it, some stability/maturity makes a lot of sense), but look at the advances that C# has made since 1.5/1.6 has been out.

It wasn't like C++ pre C+11 -it didn't take a decade or soto catch up with the rest of the programming world, but you can see the its size slowing its advancement down.

I want to like programming in Java again (I'm not saying it's bad, or it's a mistake) - for a long time it was my go-to language for when I play with ideas. But for now it's just a way to pay the bills while I try to figure out what I want to do/make/build.


You must be coming from a different C++ background. I had to program in Java for a couple years after 10 years of C++/Qt and was unpleasantly surprised. Java manages to be slower and more verbose/less powerful than C++.


I went from a games programming (C++) career, to Android, to enterprise Java. I admit that enterprise Java can be pretty hideous, but I think in most cases the bloat/slowness isn't caused by the language there. As far as Android is concerned, I co-wrote and optimised a skinning animation system in Java. The bottleneck ended up being things like fill-rates and GPU calculations, not Java.


> The community splintered, the language and platform really lost any ability to maintain momentum.

This is the mindset I've never understood.

Do you stop using a hammer to bang in nails because the hammer "community" has splintered, or the development of hammers has stagnated? No, you still use it to fulfill a job it solves.


I don't think this is a valid analogy. The language/tools/support/ability-to-hire-developers are all a fluid ever-changing thing. Hammers aren't. Take this post.. people are excited about updates. I'm just saying the updates are kind of too little too late for me.


Well, people want different things. I just want the hammer.

New language features are all fun, but unless they actually result in faster execution, or allow you to do things you could not do before, they're only use is to make some developers happy, which I don't think is particularly important.

It looks like there's some real solid good APIs here though which is great to see.

At first thought I imagined it'd just be useless pandering to developers like "You can now do closures or first class functions" or something equally useless.


Come on, let's get honest. The ecosystem matters. A lot. The community, and level of interest and delight in using the language matters.. Yes, even to you. It determines what third party tools are available, how easy it is to hire developers, and what machines the platform actually runs on. Your argument suggests you'd be just as happy and productive developing today in Pascal.

"You can now do closures or first class functions" or something equally useless.

Flamebait, but I'll take it. I think the dust-up over the possibility of this being added to Java really seemed to contribute to the decline and apparent disinterest of a lot of folks (I'd really be interested in Bob Lee's opinions here, since he was someone who's ideas I was particularly aligned with at the time and has since gone pretty quiet).. That said, lack of first class functions in Java isn't a trifle. It's why Java isn't all that much fun to program in compared to more expressive languages... and a bigger problem is that more than any other language I'm familiar with Java suffers from the problem of not being able to see enough ideas in a given amount of source code. I'm explaining that terribly, but I just mean that Java code is at least 60% scaffolding that isn't material to the author's intent.

Closures, or first class functions done nicely would be a big step in alleviating that issue, IMHO.


> and a bigger problem is that more than any other language I'm familiar with Java suffers from the problem of not being able to see enough ideas in a given amount of source code.

This is not an issue with Java. It's an issue with the programmer. How are you going to cope with assembly language listings? Blame assembly language?


> New language features are all fun, but unless they actually result in faster execution, or allow you to do things you could not do before, they're only use is to make some developers happy, which I don't think is particularly important.

I think you don't appreciate how some language features can help you reduce the size and complexity of your code. Those are the kind of features that are sorely lacking in Java, and that means huge, bloated code bases.

I'm tired of visually parsing 20 lines of a Java method and filtering out all the boilerplate iteration junk just to find the one or two lines that actually do something. Often this kind of thing can be reduced to a few simple, relevant lines when you have closures, for example.


> Those are the kind of features that are sorely lacking in Java, and that means huge, bloated code bases.

No, it doesn't. If you can't write concise Java, you're doing something wrong. And if you can't read code well, go practice some more.

Disclaimer: I'm an outlier. I rarely use 3rd party libs, rarely write with anyone else, etc.


> And if you can't read code well, go practice some more.

Actually, let's not. To paraphrase a minor celebrity of programming, life is too long to be good at reading every variation of boilerplate. Java is essentially hostile to small functions and parametrization, as having any semblance of inner or anonymous functions will require you to define a class at least, or an interface somewhere else, scattering your code unnecessarily, and you'll probably just end up repeating the code because it's just not worth the effort to do it. Don't believe me? Why do you always have to .open() and .close() your any port-like thing manually? That's a solved problem, you know?


> To paraphrase a minor celebrity of programming, life is too long to be good at reading every variation of boilerplate.

Learning to read code is just like learning to read English. You can guess most of the words meaning once you know some of them. Personally, I think being able to read code is the best skill you can have as a programmer. Just as a good musician is able to listen to music properly. (I mean 'listen' as in analyze, understand, notate and copy).

The other point IMHO is that scattering your code with anonymous functions points to bad design and is as bad as scattering "GOTO" everywhere in BASIC code. It leads to spaghetti code which is an unmaintainable mess.


> Learning to read code is just like learning to read English. You can guess most of the words meaning once you know some of them. Personally, I think being able to read code is the best skill you can have as a programmer. Just as a good musician is able to listen to music properly. (I mean 'listen' as in analyze, understand, notate and copy).

Yes, that's very true, but it's also a red herring. Not all code is worth to read, nor is it worth to write. Certainly not either the copy+pasted mess that would result of not using first-class functions, or all the _noise_ introduced by their half assed expression using classes.

> The other point IMHO is that scattering your code with anonymous functions points to bad design and is as bad as scattering "GOTO" everywhere in BASIC code. It leads to spaghetti code which is an unmaintainable mess.

Spaghetti? Really? As in flow of control? You _really_ don't know what you are talking about. Sure, it does enable some trickery, like Continuation Passing Style, but if you are arguing that such a technique is a 'con' for the existence of what amounts to just both functions and lexical scope, you are grasping straws.

On the other hand, you have simple abstractions that are enabled by first-class functions, like map or the folds, and you won't have to hear of silliness like the 'Command Pattern' or the 'Strategy Pattern' to work around the restrictions that make them necessary. And the subsequent explosion in code, to be found later shoved in other classes and packages. They make dispatch tables easy, they give you a simple way to make asynchronous code, they allow wrappers for guarded code, they...

Do yourself a favour and take a good look to the first two chapters of SICP (http://mitpress.mit.edu/sicp/), most of their charm is displayed there.


@felipemnoa: Downvotes are presumably for snarky 'You must suck and reading/writing code then' comments. Isn't a positive contribution to the discussion.

Also, 'making the difference' and 'being totally irrelevant' are two very different things. Programming languages matter. I'd be surprised if Mr. Spolsky disagrees.


I think it is. If people haven't learnt yet that the single most important skill you need as a programmer is being able to read any code, in any language, and take a good guess at what it does, be able to hold abstract programming concepts in your head, and match them up to random code listings you have never seen before....

Before you can write code, you need to know how to read it.


I recently had the great displeasure of working on a 20,000 odd line class. You cannot keep 20,000 lines in your head, it's an extreme challenge.

Each method only had tiny differences but spotting them, as pivo's original comment argues, is a total nightmare.

Refactoring brought it in at 1,500 lines. Now you can glance at any method and see the actual difference to the default that they do.

Are you seriously suggesting there's little difference between a programming language that encourages 20,000 line behemoths filled with dross compared to a concise 1,500 line program. That there's not a massive mental overhead to reading through what is essentially a book compared to a short essay?

As that's what's being discussed, but you don't seem to get it.

There's reading code, and there's reading pointless code.


Java does no such thing as "encourages 20,000 line behemoths filled with dross". Bad programmers do.

If you're creating several methods that only differ a little bit, you're doing something stupid. In any language.

Bad programmers create bad code. The language is totally irrelevant.


It's really not irrelevant.

There's a reason that people aren't programming in COBOL or BASIC.


Yes, the reason is the runtimes for them suck, or aren't needed.

If there was a decent runtime for BASIC or COBOL, which gave real world advantages over everything else, I'd switch to BASIC or COBOL in a heart beat.

I'm a programmer. The language I use is pretty irrelevant. If It starts looking ugly, I'd just write a cross compiler. This is not rocket science.


I'm sure no one is disagreeing with the importance of knowing how to read code. I'm just saying that Java makes it harder than it needs to be. If your argument is that that's a good thing, then where does that argument end?

(Probably with Perl, I guess...)

...sorry Perl guys. Couldn't resist.


Maybe you couldn't resist because you're nostalgic? Read-only Perl went out with the 1990's, unless you're talking about golf (which FYI is done for the challenge of it - it's not for production).


You want to have a look at the APL / J / K family, where functions like |/0(0|+)\ that compute the maximum-consecutive-sum (honest!) are the norm.


There are many real-world, practical examples of code that is a huge clanking mess of boilerplate in Java but yet just a few lines in a more expressive language like Ruby, Python, or C#.


>>No, it doesn't. If you can't write concise Java, you're doing something wrong. And if you can't read code well, go practice some more.

Don't know why you are getting down voted. Even Joel Spolsky says that what really makes the difference is the programmer, not the language. If you suck in Java you will probably suck in other languages.


Then why did he wrote his own language for his product? Oh right, because languages do matter.

Sure, what makes one a great programmer is language independent, but that doesn't mean you can have the same code quality in every language. There's a reason why professionals in every field buy top quality tools and not cheap disposable crap.


>>There's a reason why professionals in every field buy top quality tools and not cheap disposable crap.

Agree But Java is not cheap disposable crap. At this point it is more a matter of taste. You don't like Java fine, but other people are able to be just as productive as you using Java and probably more depending on the programmer itself. At the end of the day it is the programmer that makes the difference.


I would strongly contest the assertion that there is someone of equivalent programming aptitude and experience who will be as productive in Java as I would be in Scala or Clojure or C#.

Boilerplate kills. It kills again when you have to go back and try to re-read code slathered in it.


I know why he gets downvoted: There's a lot of kids on hacker news that only use ruby and/or javascript and they really don't want to hear about them being bad at something. hell they wrote a WEB APPLICATION. Now ain't that something.


That's just foolish. I write Java daily for a very large web company, and I downvoted him. Because his claim is nonsensical. I downvoted you too, because your claim is trollish and wrong.

I have been writing Java since I was 13. I am 23 now. I have been paid for code written in C#, Java, JavaScript, PHP, F#, and Python. My personal projects are written in Scala, C#, C++, and JavaScript. I emphatically do not use Ruby for personal or professional projects (unless forced, with regards to the latter). From this reasonably broad body of experience, I am quite certain that I would be vastly more productive if the language wasn't consistently getting in my way. As it is, I have an unhealthy number of vim macros to deal with all the boilerplate that Java foists upon a developer. It is insufficiently expressive without them, and once those macros are applied the resultant boilerplate code (method objects, for example) greatly decrease readability and increase potential failures, due to more difficulty in conceptualizing and reviewing the code.

His posts also belie a lack of perspective. He doesn't "write with anyone else," yet I would venture to guess that the primary use case of Java, today, is in environments with more than one developer. He doesn't "use 3rd party libs", which suggests a lack of familiarity with his own ecosystem of tools, let alone those that provide these features that others (including myself) have indicated are part of what makes Java unpleasant to use. (Seriously--if you're not using Apache Commons at the very least, there is a credible argument that you're probably reinventing wheels and Doing It Wrong.) And he has a critical lack of perspective about what are generally considered basic programming constructs: if you think closures and first-class functions exist to "make some developers happy," you are ignorant of why they exist in the first place. Do you think that now-very-standard tools like map, fold, etc. would be generally adopted if the only way to use them was Java-boilerplate code-vomit?

.

pivo said it nicely upthread: "I'm tired of visually parsing 20 lines of a Java method and filtering out all the boilerplate iteration junk just to find the one or two lines that actually do something. Often this kind of thing can be reduced to a few simple, relevant lines when you have closures, for example." And he is right. Because this is what Java makes you do. In 2011, it has been surpassed in terms of flexibility, expressiveness, and utility by other JVM languages that allow you to pull in Java objects and work with them, but write your code in a way that is much more pleasant.

.

But no--clearly we're all kids, writing Ruby and JavaScript. Except that this kid almost certainly writes more, better Java than you do, and still finds it a regular source of frustration simply because it isn't good enough.

Perhaps you should be less upset when people demonstrate that you are lacking in perspective about your favorite toys.


As it is, I have an unhealthy number of vim macros to deal with all the boilerplate that Java foists upon a developer.

I hate to bring up the editor wars thang, but knowing a lot of very skilled people in the Java world, I will say this: it's rare for a "best in class" Java developer to use anything but a full fledged Java IDE (not unheard of, but rare). If you're not using one of these (IntelliJ, Eclipse, or Netbeans, in my personal order of preference), you're really missing out on almost everything good that Java has to offer over other languages, as far as boilerplate-simplifying, integration, and bug-hunting. IMO, unless you're using a good Java IDE and have used it long enough to know it well, you are not actually coding Java, you're coding some shitty worst-of-all-worlds version of Java, and it's no surprise that you hate it. I don't know how I could possibly code Java and remain sane without the ten-times-a-minute ctrl-space auto-complete/lookup routine (along with all the other time saving macros and shortcuts that a good IDE will give you)...

FWIW, I say this as a die-hard emacs user (bite me, vim :) ) that uses it for damn near every "I have to edit some text" task that he comes across, so this is not an issue of me not understanding what a good text editor is capable of. Ruby, JS, PHP, Clojure, Python, and the like are in emacs territory for me, but when it comes to Java, the tools really do counteract many of the language's failures (and let's be honest, the number one offender is the lack of closures, with the annoyingly explicit static typing coming a close second), and I'll be honest, I miss the IDE features when I code dynamic languages - it sucks to have to resort to textual searches instead of actually walking the parse tree, even if it can get you 80% of the way there most of the time.

Honestly, I've always personally thought that AS3 had a lot of potential, as a mostly-statically-typed-but-dynamic-if-you-need-it version of Javascript, but even there the IDEs aren't quite up to the Java standard (mostly due to apathy, as far as I can tell, there's nothing about the language that would make any of the features common to Java IDEs any more difficult to implement in AS3 ones), so the benefits of the default static typing are somewhat muted...


Sorry, I should have been more specific--I use Eclim to bring gvim inside the Eclipse environment, or I use Netbeans with a set of macros that parallel my vim ones. I find the built-in "boilerplate simplification" nonsense to be a patch over the fact that Java itself is no better than mediocre, and should not be considered a valid defense of Java as a tool.

And the reason? Because even with all these tools that have grown up around Java to address its shortcomings, it completely sucks. Absolutely sucks. Miserable to write and--more importantly--miserable to read. Meanwhile, I can comfortably write idiomatic Scala in Netbeans (the Eclipse plugin is shaky) with the editor's only help being Intellisense, idiomatic Scala that another programmer can read easily without trouble, because the language is geared toward actually being descriptive rather than covered in boilerplate.

And Scala is not a dynamically typed language, but shows that a static language can actually act very similarly to one. And you still get all those features that you miss. It's sort of what you're talking about re: AS3, but it's here now and works.

.

I wasn't joking earlier when I said that the best Java "tool" is a Scala compiler. It's not perfect (hello, long compile times), but I can do anything that I do in Java faster and with more readable and therefore reliable code in Scala. The reverse is not true, because to get around Java's inherent lack of expressivity you are forced to create new points of failure for yourself.

That's not good. It's not necessary. But it's defended to the death by people who--not you, but some of the other posters on this thread--really do truly think in Blub and don't understand why these things are bad.


> I have been writing Java since I was 13. I am 23 now. I have been paid for code written in C#, Java, JavaScript, PHP, F#, and Python.

Woah! You're 23? I bow down to your knowledge and wisdom ;) (I started programming before you were born).

> I am quite certain that I would be vastly more productive if the language wasn't consistently getting in my way

Again, then you're doing something seriously wrong. If you're spending more than 25% of your time typing out code, you're doing something very very wrong.

If your bottleneck is the language, there's something seriously fucked up with the way you program. As a programmer you should be primarily using your brain, to solve problems. Then you take a few minutes to splurge that all out by pressing some keys on a computer.


Yes, you started writing Blub before I was born. Good for you. It's very unfortunate that you haven't progressed past that point.

That you have openly admitted that you do not understand the productivity and code quality benefits of closures, etc. is so very much not my problem. Massive switch statements and needless object subclassing to get around Java's inefficiencies--be my guest. Enjoy your spaghetti.

I have demonstrated, to my own satisfaction and really that's all I give a damn about, that I am considerably more productive using Scala (you do know what Scala is, right?) on the JVM, consuming Java libraries, than I am Java. The language is a roadblock, regardless of how your 90's sensibilities feel about the issue.

(Seriously, whoever decided a function object pattern was a suitable alternative to a delegate or closure should be barred from programming, ever again.)


That's great that you've discovered you're less productive in Java than Scala. Hopefully you can improve that deficiency in your programming at some point.


You are basically saying that people cannot write good code in Java. You are generalizing and that makes you sound like and troll even though I know that is not your intention. You can write good or bad code in Java. I personally have never really had an issue with Java so I don't really understand the hate.

Yes, there are sucky frameworks out there but you do know that you don't have to use them? Either I'm writing really simple code that Java never gets in the way, Java is not really a problem, or I'm a super programmer. I don't think I writing simple code, I don't think I'm a super programming, so it has to be that Java is not really a problem for me. And I write similar code in Objective-C, C++/C, JavaScript and even had to write a lot of code in VBA. Had even to write code in PL-SQL several years ago.

Every language has its own nuances, you just find the best way to work with them, ignore the junk, and adapt. Which is why I really don't get where all this hate is coming from. You never hear this for C++ and it can also be a pain in the ass but you do hear it for Java.

Is almost like it is cool to hate on Java.


You know, I was thinking the same about Java. That's when I posted this question. http://news.ycombinator.com/item?id=2094274 ; It got front page, and one (that's 1) pointer to good Java code.

For whatever reason, whether it is merit or culture, Java programmers tend to write horrible code. I'm sure there's some nice Java code out there, that is not 20 times longer than it should be. But I have not yet seen evidence, even though I've been searching for it for a while.


You can certainly write good code in Java. Totally doable, never said it wasn't. But I'd agree with you that Java programmers tend to write horrible code.

I linked the essay by pg (which I'm sure our upset friends did not read) that suggests a decent reason why: I tend to find that in the Java world there's a lack of awareness of the proper (and I do mean proper) way of writing a lot of more advanced, more indirected code. (This is the "thinking in Blub" you see from pg or Joel Spolsky.) I have a hunch that this lack of higher-level awareness results in weird kluges and hacks that don't even really match the "canonical" design patterns and idioms of what you or I might call "good" Java.

I feel pretty confident in saying that people who are fully comfortable with a more expressive tool (C#, Scala, even dynamic languages like Python or JavaScript) will write better Java than someone who is inculcated into Java first and Java only. It's easy, if unpleasant, to move "down" the continuum that pg references--it's not so easy to move "up", especially when you don't see a reason to (as these posters clearly demonstrate that they do not).



>> You are basically saying that people cannot write good code in Java.

Wrong. I would not say that, because I do it. I am saying that it is vastly more difficult than it needs to be to write good code in Java because it is insufficiently expressive.

I will say that I am suspicious of the ability to write good code of people to whom Java is not a poor development choice, because I suspect brain damage, but a decent programmer can write fine Java. It just sucks to do it.

.

>> You are generalizing and that makes you sound like and troll even though I know that is not your intention.

I am doing no such thing. You are misunderstanding me, but it's pretty clear from the upvotes that you're the only one.

.

>> I personally have never really had an issue with Java so I don't really understand the hate.

It is likely because you think in Blub. Read pg's article regarding Blub, Beating the Averages:

http://www.paulgraham.com/avg.html

He makes the contention that Lisp is at the apex of the pyramid of software development tools. I disagree, for a number of reasons, but the contention of the article is correct at its core: once you have the perspective of a decent set of other tools, you realize that regardless of your tools of choice, Blub languages rank very low on the scale of expressivity--and thus, in power and ease-of-use. (And everyone should learn Lisp, anyway. Even if they don't write code in it. I think in Lisp when writing Java, and aside from Java's miserable boilerplate, my Lisp-in-Java is better than your average Java programmer's Java-in-Java.)

And I would submit that Java is one of the most Blub languages in common use. You have no basis for understanding why others would have an issue, because you are looking up the continuum without insight into what is above.

.

>> Yes, there are sucky frameworks out there but you do know that you don't have to use them?

Meaningless statement. At my current employer, we are forced to use a legacy servlet infrastructure, but my own Java (and Scala) code uses Play! and other frameworks and libraries that at least attempt, if not always successfully, to drag Java reluctantly into some semblance of modernity.

Writing Java still sucks.

.

>> Either I'm writing really simple code that Java never gets in the way, Java is not really a problem, or I'm a super programmer.

Or you are insufficiently experienced with better tools to be able to reliably determine whether it is done better elsewhere. One who does not know any better may be happy with Blub, but one who has used better is not. This seems eminently straightforward.

.

>> And I write similar code in Objective-C, C++/C, JavaScript and even had to write a lot of code in VBA.

I'm beginning to see your problem. With the exception of JavaScript, you do work in Blub. And I'd bet that you write Blub in JavaScript, too, instead of JavaScript in JavaScript.

.

>> Every language has its own nuances, you just find the best way to work with them, ignore the junk, and adapt. Which is why I really don't get where all this hate is coming from.

Nonsense and worse words. The best way to "adapt to Java" is to download a Scala compiler. Spend a few weeks using the JVM with something modern like Scala or Clojure and you will get where the antipathy towards Java comes from.

Java commits the ultimate sin a programming language can commit: it wastes my time. It is a language designed by committee that does nothing excellently. Its successors on its own platform do not commit the same sin and I am more productive for it--they are better for it.

.

>> You never hear this for C++ and it can also be a pain in the ass

This is blatantly untrue, in my own experience. I can rant on about C++ quite successfully and at great length, because C++ has its own share of problems. Where it differs is in much, much greater expressivity--that C++ is capable of supporting Boost is a perfect example of this expressivity. It is by no means perfect, but it is certainly a smaller problem than Java.

And unlike Java 7, C++0x actually fixes (most of--templated lambdas are unavailable for what I consider fairly stupid reasons) the problems that. Oracle decided to push anything useful out until Java 8, and I'm skeptical it'll actually keep the promise of "next year."

.

>> Is almost like it is cool to hate on Java.

You lack the breadth of experience to make this claim.


Well, lets agree to disagree. Maybe I am a dum*bass and too dumb to realize it. Ho well.. C'est la vie


"Agree to disagree" is a polite way of saying "you're wrong."

Are you incapable of substantiating your position?


Yes, you are right. I'm politely telling you that I respect your opinion but I disagree.

>>Are you incapable of substantiating your position?

The thing is that a lot of the arguments we are making are just our own opinions and hence anecdotal. Really what we need here is scientific research measuring what difference does the programming language make when working on coding projects

A couple of examples that I've worked on are the following:

A Java to Objective-C transcoder

C to Java transcoder

Physics Engine

Collision Engine

Symbolic Math Engine

Game Engine (includes the Physics Engine and Collision Engine along with the rendering and animation code)

And some things I'm currently working on:

Java to C++ transcoder

Java to JavaScript transcoder

What I've noticed is that the coding takes very little time, the figuring out part, the design, architecture, debugging, that takes most of the time.

I'm not really sure whether one of the most modern languages would really make much of a difference if at all. I believe it won't really make much of a difference. Coding is the easy part.

Use the language that makes you comfortable, definitely.

Now, tools are a different story. I would hate to have to code in a simple text editor. IDEs make my life extremely easy and actually make me a faster coder. I love the Eclipse IDE. XCode would be my second choice and Visual Studio 3rd.


Upvoted for "coding takes very little time" ! Most often, you are making 100s of small but significant decisions of algorithms, runtimes, libraries, memory footprints etc that the actual coding part ends up being the less significant aspect.

Also, I really admire the polite but confident way you responded to eropple's borderline trolling. Good show !


> You lack the breadth of experience to make this claim.

Wake up. You're 23. You're a kid. You've just started programming and think you know everything. You don't.


I'm well aware that I don't know everything--but, with what little respect is due a troll like yourself, apparently I know more than you. :-) After all, I'm not the one saying "you don't need that" because I don't understand it; on the contrary--I am saying that these tools greatly empower a programmer to write better code. Because they do. You can certainly write "good" Java, but it will not be in the same ballpark as "good" Scala or "good" C# or "good" any-other-remotely-modern-language. The effort expended to write "good" Java is much greater, and as such it is a worse tool.

As for your ad hominem: I've been doing this at some level for ten years, thanks. I've been getting paid to do this stuff for about six. I didn't "just" start programming. I work in a fairly high-level, demanding environment with plenty of hard problems and a lot of code smell that can be directly attributed to poor Java expressivity.

That you can only fall back on "you're a kid" as a way to attack claims says much, much more about you than I.

You are describing to a T the sort of Blub programmer that is referred to in the Graham article I linked upthread, but I won't bother advising you to read it--you won't recognize yourself. Have a nice day. :)


You'll look back at these comments you're making in 10 years and be embarrassed. Hopefully by then you will have learnt a bit more about being a productive programmer.

The language doesn't matter. Repeat after me...

A good programmer can make good stuff in ANY language. A bad programmer can only make good stuff in their favorite language.

You should stand up, be confident, and realize that it is the programmer that creates awesome software. Not the language.


I think you're misunderstanding the point here. It is perfectly possible to write awesome software in Java. With the amount of software out there, it would be completely insane for anyone to say that you can't do awesome things in Java.

> You should stand up, be confident, and realize that it is the programmer that creates awesome software. Not the language.

This highlights the misunderstanding. You're right. We should be spending our time making awesome software, not typing letters and building boilerplate code.

Full disclosure: I work with eropple on a fairly regular basis, I favor C#, I write C++ at my day job. I spent a few months doing Java, was able to do what I wanted to with it, but missed a lot of features from more featureful languages.


There is more to awesome software than typing.

(Note this point stands compatible with the entirely orthogonal point about expressiveness and concision of a language.)

For me (at least due to client demands ..) awesome software, in part, posits the requirement of economically maintainable artifact.

PG's writings on Blub languages is imo addressed to a narrow audience of readers as it does not in anyway address maintenance and extensions to systems by non-elite development teams. Even elite teams, if tasked with delivery of products to non-elite consumers, must factor in the economic equation of the cost proposal.

To wit:

Having a bench of solid OCaml/Scala developers is a viable economic proposition for Wall Street and rich hedge funds; starry start-ups; and possibly elite teams in major media; a hacker community project. It is insanely difficult enough to find competent help in Blub-land, much less competent Scala programmers.

And, of course, the majority of software is developed/internally-consumed precisely by shops that must staff from blub-land. And surely you are aware that a big chunk of "programmers" out there are just recent graduates of some web-app vocational CS education.

Software language economy is not simply about lines of code. The economic cost equation of a language is definitely a critical factor if positioned as a general use language.

Java is unsurpassed in terms of the balance it brings to the economic equation: it is effectively powerful enough to allow serious developers to create "awesome" software, and approachable enough for blubland coders to crank out (yes) meh code that gets the (business) job done.

This fact was recognized by all entities chasing development dollars out there, including IBM, Oracle, and in its own cute way, via Google (Android).

Tell me: why isn't Android dev done with Scala or Clojure? My answer: Because Google management is not stupid.


I'm embarrassed for both of you. Will you please stop baiting one another?


I think an example is in order. I'm going to code up a simple event dispatching algorithm in three languages. They'll have the same functionality. I consider myself fluent in all three, and I'll write them in the most consise and style-respecting way I can.

C++:

    #include <vector>
    #include <string>
    #include <iostream>
    typedef void (*hndlr)(std::string);

    class Event {
      private:
        std::vector<hndlr> handlers;
      public:
        void Listen(hndlr handler) {
          handlers.push_back(handler);
        }
        void trigger(string arg) {
          for (std::vector<hndlr>::iterator i = handlers.begin(); 
              i != handlers.end(); i++) {
            (*i)(arg);
          }
        }
    };
    
    void h1(std::string arg) { 
      std::cout << "First handler got " << arg << std::endl;
    }
    void h2(std::string arg) { 
      std::cout << "Second handler got " << arg << std::endl;
    }
    
    void main() {
      Event event;
      event.Listen(h1);
      event.Listen(h2);
      event.Trigger("something happened!");
    }
Lua:

    event = {listeners = {}}

    function event.listen(self, handler) 
      if (type(handler) ~= "function") return end
      table.insert(self.listeners, handler) 
    end
    
    function event.trigger(self, arg) 
      for handler in self.listeners do handler(arg) end
    end
    
    event:listen(function(text) print("First handler got "..text) end)
    event:listen(function(text) print("Second handler got "..text) end)
    event:trigger("something happened!")
    
C#:

    using System;
    public delegate void HandlerDelegate(string arg);

    class Main {
      static event HandlerDelegate Event;
      static void Main() {
        Event += (arg) => { Console.WriteLine("First handler got" + arg); };
        Event += (arg) => { Console.WriteLine("Second handler got" + arg); };
        Event("something happened!");
      }
    }
    
    
Now, go ahead and say that choice of language doesn't matter. You might not need lambdas, or first-class functions, or event handlers, and a good programmer can make the same algorithm "work" in any language. But by choosing a more powerful and expressive language, you can get those algorithms done in a way that's more readable, maintainable, and faster to code, which in the end is what really matters.


Also fun: The only one of these that works when a callback removes itself from the event list in its own callback routine is C#. You get a hanging iterator in C++, and removing items from a table mid-iteration in Lua is undefined (though in practice usually works).

To make this case work properly, the place I work for has a 335 line C++ template class. This is all time that the developer could have spent actually building our product.


The C++ version could be greatly simplified by using boost::bind. It'd still be shorter and clearer than a Java equivalent that had to bung in anonymous classes and other crap to create a proper dispatch.

Your point, however, totally stands.


You don't seem to understand something that I guess I feel is rather basic: I don't have a "favorite" language. I have tools that are expressive and thus more useful because I spend more time in the problem space than I do in the language space. I also have Java.

Objects are a powerful concept because they allow a programmer to more easily map a problem to the available solution space. This is good. Java, however, fails to take the next step to enable even better mapping of a problem by creating a more flexible solution space. The other languages cited in this thread do create that more flexible solution space, and thus make getting a job done more easily and more cleanly a viable possibility.

.

A good programmer can make good stuff in any language. You are correct about this. Where you are wrong is in your inability to understand that a good programmer can make good stuff quicker and more easily in an environment that minimizes the distance between the problem and solution set.

But I rather get the impression that you don't know enough about what exists outside of your "box" to be as authoritative as you'd like to sound. You seem fundamentally uninterested in understanding the benefits that these constructs, and these simplified syntaxes (note: these are two separate points, but you seem to miss them both) provide to a developer. I don't think there's a lot of value in continuing this with you. Unless you bring forward salient points instead of petulant defenses based on fundamental ignorance, I won't reply to you again.


You ignorance is so painful embarrassing, it almost hurts to read your non-sense.


At first thought I imagined it'd just be useless pandering to developers like "You can now do closures or first class functions" or something equally useless.

Congratulations, you've found your Blub. (Mine is Python; I'm still not clear on what monads would do for me in practice).


And all just because the metaphor lacks (here more than elsewhere). Using a tool also means becoming more proficient in it and this is similar to an investment. If you don't expect anything of significance to come out of the movement associated with your language it is hard for the working programmer to enjoy developing in it any more. Here the fundamental difference to hammers becomes clear: Hammers don't evolve and have no complex ecosystem associated while programming languages do.


That's true. Unless someone builds a lighter, more accurate hammer in the meantime.


In certain situations, professional carpenters have found nail guns more effective.

They require more resources to run, but they tend to get the job done a lot faster.


Depends. What if your nails required newer hammers? Would you rather wait for a newer hammer from a company that hasn't been meeting needs for years, or buy one from the store that had them when the nails came out?

Perhaps a better analogy is a screwdriver. Apple came out with their "pentalobe" security screws a while back - is it reasonable to buy one of the screwdrivers that is made for it that are available now if you needed to (un)screw one? The other options are to use a philips and damage the screw and suffer a lot of frustration, or to wait until Craftsman makes one (probably never).


There really is not much you can do to a language to make you code faster. I guess people just like the novelty of a new language.


If you mean that time spent actually coding a program is a rounding error of the time spent conceiving it, then that's an interesting point.

That said..

1. OF COURSE you can make languages that are faster or slower to write code in.

2. Trivializing anyone who jumps ship on a language as being enchanted with the 'novelty of a new language' is obnoxious and arrogant.


Yes, it is harder to come up with the actual design, architecture, algorithms, testing of your program than the actual coding. You should definitely use what makes you more comfortable but criticizing/hating a language because it is not adding whatever is currently hot under the Sun is also obnoxious and arrogant. C++ is a lot older than Java and can be also a pain to write programs in and yet for whatever reason people love to hate Java because it is not keeping up with the times. There really is not much you can do to Java at this point. The tools on the other hand, do make a huge difference. Eclipse is a really time saver and actually makes you a more efficient coder.


I don't hate Java. The language is good and the JVM is great.. but I became increasingly displeased with the fact that the evolution of the language seemed to become slow and aimless. Couple that with where the tools were going, and I felt like it was getting harder and less fun to write applications in Java.. so I kind of bailed.

There really is not much you can do to Java at this point

Because it's basically perfect? Okay.

At any rate, really my point was not "Java sucks, I'm over it"... my point was that I think the community of programmers that surround a language are for better or worse stewards of the direction, best-practices, idioms, and common ideologies that affect my experience developing in it. Jim's arguing that he's not like that.. fine, but most of the rest of us are. We use libraries written by other developers, work with other developers... the community matters and shapes our experiences as a [Insert Language] Programmer. I'm just saying that for me, that community was thriving at one point, and then around when Java 5 came out fragments started showing.. things got worse, and now I don't really see much to get excited about. The frameworks are ridiculously heavy, I hope I never accidentally figure out what an Enterprise Service Bus is for, and generally I just feel like the direction of the language (and probably the platform) seems rather driftless.


>The frameworks are ridiculously heavy... I agree with you on this part. I kept scratching my head when I was first introduced to Enterprise java beans. It all smelled like BS to me but because more experienced people than me and with more status were evangelizing about it I couldn't really call them on it. In the end I just ignored all of that and used the pieces that I like. Kept everything as simple as possible. I'm not directing this at you but just in general: Nothing wrong with moving to knew languages but criticizing any language because it is missing some simple feature like X and claiming that without it you just cannot work seems to me lazy and full of BS. All languages have issues. The difference is made by the programmer.


Keep in mind this is JDK 7 (the JVM, libraries, tools), it's not only a Java The Language update.


Looks like this version is not open source. Is there an open-source version of Java 7? Edit: Yes! http://openjdk.java.net/ has an announcement at http://mail.openjdk.java.net/pipermail/announce/2011-July/00.... So why would anybody "accept the Oracle Binary Code License Agreement for Java SE"?


> So why would anybody "accept the Oracle Binary Code License Agreement for Java SE"?

Anybody who wants Oracle commercial support:

http://www.oracle.com/technetwork/java/javase/community/open...

Oracle's Commercial Distribution of the JDK

People who want the benefits of commercial support and predictability can choose to use Oracle's commercial distribution of the Java SE JDK or JRE. Oracle's commercial JDK releases will be built from the open-source code, for the most part. Since there's some encumbered code in the JDK, Oracle will continue to use that code in commercial releases until it is replaced by fully-functional open-source alternatives. To learn more about development and deployment support options, visit the Java Support site.


The OpenJDK may have more bugs. Check out [http://stackoverflow.com/questions/1977238/why-should-i-use-...].


In my experience, OpenJDK has fewer bugs - at least the ones I care about. Like Swing making bad assumptions about the WM, including that only a small fixed number of window managers are tiling (OpenJDK works on XMonad, Java 6u21 does not).


FUD. They're pretty much the same code base. Also "Moving to OpenJDK as the official Java SE 7 Reference Implementation": http://blogs.oracle.com/henrik/entry/moving_to_openjdk_as_th...


It is called openjdk: http://openjdk.java.net/


Wait, so it's possible to not have to bow the knee to Oracle and still use Java? I am very pleased by this and feel as though my best language hasn't been lost forever by them.


There is a good amount of stuff to get excited about in this release.

  - Try-with-resources-Catch-Block [0]
  - Fork/Join libraries from Doug Lea (author of Executor framework) [1]
  - Inferred/Simpler generics in declarations (should have been in Java 5)
  - NIO2, brand new/robust filesystem APIs [2]
  - NIO2, treat ZIP/JAR files like directories of files for R/W [3]
  - SDP support [4]
  - String-in-switch (NOTE: check on performance implications of this for tight loops)
    NOTE: Read through "COMPILATION" section here for details [6]
  - Elliptic curve cryptography (when normal curves just don't cut it)
  - Underscores in numbers (e.g. int million = 1_000_000;)
  - XRender pipeline on Linux (Swing/Java2D rendering get a big boost)
  - New sound synthesizer (replaces a proprietary lib that wasn't OS)
  - XML stack finally got updated across the board.
  - InvokeDynamic (already talked about numerous times below)
  - Other Swing stuff I'm not all that pumped about.
I think the most exciting items are:

  1. Try-with-resources
  2. NIO2 filesystem API
  3. InvokeDynamic
Features that got pushed to 8 (next year) that will be really exciting:

  - Modular programming (super packages? think OSGi-lite)
  - Syntactic Sugar: Collection literals
    List<String> people = {"Frank", "Mary", "Satan"};
  - Closures
  - Modularization of the JDK (JDK gets broken into core modules)
And one that I can't get confirmation on if it's in 7 or got pushed, index-access for List and Maps [5]:

  - List<String> people = {"Frank", "Mary", "Satan"};
    System.out.println("Hello " + people[0]);
I understand that a lot of people don't find Java sexy any more, that is understandable, it has become a platform for what seems like a lot of next-series of languages.

That being said, I've been working with Java since 1998 and still love it. I know people get a big kick out of writing code with no exception handlers and no curly braces, and programming is a creative/artistic process so you have to do what feels good... but none of that stuff ever bothered me.

I like being a pedantic programmer.

[0] http://www.javacodegeeks.com/2011/07/java-7-try-with-resourc...

[1] http://artisans-serverintellect-com.si-eioswww6.com/default....

[2] http://openjdk.java.net/projects/jdk7/features/#f250

[3] http://openjdk.java.net/projects/jdk7/features/#fa537814

[4] http://openjdk.java.net/projects/jdk7/features/#f639

[5] http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/0...

[6] http://mail.openjdk.java.net/pipermail/coin-dev/2009-Februar...


> And one that I can't get confirmation on if it's in 7 or got pushed, index-access for List and Maps

I just tried it out, it didn't get added to 7.

> String-in-switch (NOTE: check on performance implications of this for tight loops)

I haven't checked the performance, but I tried decompiling a String switch statement:

  String test = "asdf";
  switch (test) {
    case "sss":
      System.out.println("sss");
      break;
    case "asdf":
      System.out.println("asdf");
      break;
  }
That decompiles to:

  switch(test.hashCode()) {
    case 114195:
      if(test.equals("sss"))
        byte0 = 0;
      break;
    case 3003444:
      if(test.equals("asdf"))
      byte0 = 1;
      break;
  }
  switch(byte0) {
    case 0: // '\0'
      System.out.println("sss");
      break;
    case 1: // '\001'
      System.out.println("asdf");
      break;
  }
So it's one switch on the String's hashcode, with calls to equals to verify that the string is a match (and an if/else if/else block if you have multiple strings in the switch that have the same hashcode), assigning the result to a temp variable, and then a switch on a temp variable to execute your code.

It looks like it would be fairly quick.


Really appreciate you going through the trouble to do that and post the results so we don't need any hand-waving.

This looks the same as the original proposal -- using the hashCode and final verification via equals.

So in a typical case scenario you have the 1-time calculation of the String's hashCode (which is then cached by java.lang.String) and the two method calls.

.equals() is the only thing that could get away from you performance wise, because unless string1 == string2 or are different lengths, you fall into a char-by-char comparison loop.

That could be a shitty surprise if you have a bunch of constants like "SAVE, RMVE, DELT, INST, UPDT" and don't realize what you are causing to happen under the covers.

I'd be curious (now) what actually happens with using Enums in switch statements to see what kind of hidden code is actually getting executed.

## ASIDE: An interesting alternative to switch statements with Enums: http://francisoud.blogspot.com/2008/02/better-way-to-use-jav...

Seems really a-typical though.

## UPDATE: It looks like using Enums ends up getting translated to:

  switch(enum.ordinal())
calls followed up goto statements to the case labels. So enums should be practically just as performant as constant numeric values except for the method call.

If the JVM is smart enough to replace the calls to 'ordinal' with the constant return value, then it should be right on par with using numerical constants which would be sweet and make using the strategy outlined in that link possibly a nice performant alternative to normal Enum use.


The .equals() still shouldn't be much of a problem. If you've got a bunch of constants like you gave, they will probably all have different hashcodes so you don't have to compare against all of them.

I checked what happens when you use an enum, and it generates some funky code. It creates an anonymous inner class with a static initializer for an array of ints. It uses the ordinal value to assign a sequential number starting with one. Then the switch statement is on intArray[theEnum.ordinal()], and the case statements start with 1. Here's the code:

  class Test2{
    public static void main(String[] args) {
      MyEnum en = MyEnum.ONE;
      switch (en) {
        case ONE:
          System.out.println("one"); break;
        case TWO:
          System.out.println("two"); break;
        default:
          System.out.println("default");
       }
    }
  }

  enum MyEnum {
    ONE, TWO, THREE;
  }
Decompiled (after being compiled with jdk1.7.0):

    public static void main(String args[])
    {
        MyEnum myenum = MyEnum.ONE;
        static class _cls1
        {

            static final int $SwitchMap$MyEnum[];

            static
            {
                $SwitchMap$MyEnum = new int[MyEnum.values().length];
                try
                {
                    $SwitchMap$MyEnum[MyEnum.ONE.ordinal()] = 1;
                }
                catch(NoSuchFieldError nosuchfielderror) { }
                try
                {
                    $SwitchMap$MyEnum[MyEnum.TWO.ordinal()] = 2;
                }
                catch(NoSuchFieldError nosuchfielderror1) { }
            }
        }

        switch(_cls1.$SwitchMap$MyEnum[myenum.ordinal()])
        {
        case 1: // '\001'
            System.out.println("one");
            break;

        case 2: // '\002'
            System.out.println("two");
            break;

        default:
            System.out.println("default");
            break;
        }
    }
I wonder why it doesn't just switch on the ordinal directly. It's also worth noting that it has to make an array for MyEnum.values().length. This means if you have an enum with a lot of values, you're wasting a lot of memory (especially since it creates this array every class you use a switch in). I tried with an enum with 40 values, and it didn't switch to a map. Maybe there's some higher threshold where it would switch to a map instead (but again, I don't understand why it wouldn't switch on ordinal() directly).


Good point about equals, I'm just thinking in a tight render loop (like in a game engine or something equally as sensitive) even with the diff hash codes you are dropping through to a char-to-char comparison IN the off chance that your two strings are the same length.

I'll be the first to admit those are pretty slim odds, but it's always fun to dig up these little performance things hidden in the JVM and store them away for later use in some interesting project.

Nice decompile with the enums... no idea what's with the array either; another hidden gem to at least be aware of.

This is alot like when autoboxing came out. New Java people thought int i and Integer ii were the same when used in different settings, not realizing that under the covers Integer.valueOf(i) and ii.intValue() are getting generated.

It's great if valueOf is returning a cached value (-127 to 128) but beyond that you are just object-creating all over the place.

Working on SJXP (xml parser layer that sits ontop of Pull Parser to make it like XPath, but super fast) I did some HPROF and found my use of path hashcode lookups in a Map<Integer, String> was generating millions of Objects.

So I moved to an Integer cache that holds the Integer object generated from the hashCode() and re-uses it as needed.

Ended up dropping the overhead (CPU and memory) of the library below everything in native XPP to where it adds almost no overhead.

Anyway -- thanks for diving deep with me on that, we have two new tricks up our sleeves ;)


I wonder why it doesn't just switch on the ordinal directly.

I don't know how JVM bytecode works, or if it's even possible to assign discontiguous ordinal values, but in C compiled to x86 assembly language, a switch statement on (mostly-)contiguous values can be converted into a jump table. If there are large gaps in the switch values, either you have a lot of wasted space in the jump table, you have multiple jump tables, or you fall back to if/elseif/etc-style code.

It would make more sense to me to assign the contiguous integer values during the construction of the Enum, but maybe that doesn't work when Java 7 code tries to use an Enum compiled with Java 6 or earlier.


> I don't know how JVM bytecode works, or if it's even possible to assign discontiguous ordinal values

That was my first thought as well, but I double checked and the ordinal() method is final, so you're guaranteed not to get anything other than continuous values for your enums.

> in C compiled to x86 assembly language, a switch statement on (mostly-)contiguous values can be converted into a jump table

Ah, this is probably the intention. The JVM can probably optimize the switch. I just checked it, and when there are multiple switch statements in a class only using a few values in an enum, it tries to make them all sequential in the switch, that's why it uses the array. I guess it's just a mistake (or lazy coding) that it always makes the array size TheEnum.values().length rather than how many it's actually going to use.


Oh sweet jesus finally collection literals. Why did it take more than 10 years to decide to bring in something so convenient? One reason I sometimes find Java repulsive is the fact that it takes so much redundant code to do something so simple. Why do they hold back on such syntactic sugar?


Oh god. Please no, collection literals are the worst idea ever. Making up special rules for some special classes in a language? What the fuck!?


You must be terrified at the presence of numerals and quotation marks in programming languages.

Here's the doc on Collection Literals, BTW.

https://docs.google.com/Doc?id=ddv8ts74_4cbnn5mhj

Collection Literals are actually better than string literals, because they only enforce an interface, not an implemenation.


Good, about time. If they only get those features slated for Java 8, they'll be at the same level C# was six years ago. :-)


And only if Microsoft would improve their x-platform vm. Oh wait...


they had that, it is called silverlight. People didn't want it all that much.


Silverlight is still limited to Windows and Mac. Moonlight is from a third party and doesn't count toward Microsoft's community altruism score.


> Silverlight is still limited to Windows and Mac

And as a direct consequence of Silverlight not being all that popular, that will not change. Sadly.


For version 8, I think it is a stretch to say that it will support 'closures'. [0]

The closures that are proposed are more like a bolted on psuedo solution, basically syntactic sugar that makes the language more complex. You can only use them in SAM (Single Abstract Method) situations. If only they just added a simple lisp like lambda expression...

[0] http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-3...


I fail to see how the lambdas, when added, will make the language more complex. Here's an example: given a list of persons, we'd like to extract all the adults. Compare the good ol' way of doing things in Java:

List<Person> persons = Humans.list(); List<Person> adults = new ArrayList<Person>(); for(Person p: persons) { if(p.age>=18){ adults.add(p); } }

Notice how the logic (filtering a list) gets drowned in irrelevant details such as creating the result list, iterating over the list, and accumulating the matching elements.

The alternative (the poor man's functional Java) with libs like Google collections would look like:

List<Person> adults = persons.filter(new Filter<Person>() {

@Override public boolean accept(Person t) { return t.age>=18; } });

Notice the noise added by the anonymous inner class.

Now, with lambdas, we end up with (once the collections are augmented methods like filter, map, reduce, etc.):

List<Person> adults = persons.filter(#{p -> p.age >= 18});

A one-liner, where the core logic (comparing the age to 18) clearly stands out.

The auto conversions of lambdas to SAM types is a spark of genius if you ask me. But I'm not happy with the decision of not implementing structural types in Java. IMO, this will lead to a Cambrian explosion in the number of SAM types, types like Mapper<S, T>, Reducer, Folder, Filter or Predicate, plus the custom types added by various frameworks.


One other great feature in JDK8 will be defender methods which will allow interfaces to carry default behavior for methods. This will be the mechanism for adding default behavior in the collection libraries without breaking classes that extend them. It will also have a lot of great use cases in new library development.


I wasn't even aware of that proposal, just found these examples[1] and love the idea.

Sort of in the same vein as static imports (as far as usability) but has a really nice added side effect of exporting a default impl from an interface that can be overridden.

Thanks!

[1] http://www.baptiste-wicht.com/2010/05/java-7-add-public-defe...


Syntactic Sugar: Collection literals List<String> people = {"Frank", "Mary", "Satan"};

I find it breathtaking this isn't core yet. I was writing test fixture support code for 1.4 to easily and DRYly generate lists of up to 10 items, which required 10 copy-paste functions each with a different number of arguments. 1.5 came along and made it possible to easily do it with one function thanks to varargs, but it's 6 years later and still no collection literals!


If you use the Google library [1], this becomes a bit more convenient that the built-in Java way:

   List<String> people = ImmutableList.of("Frank", "Mary", "Bob");
There's also ImmutableSet and many other goodies, to say the least. For instantiation of these generic types, you can do:

   List<String> people = Lists.newArrayList(); 
   Map<String,Integer> scores = Maps.newHashMap();
and so on.

[1] http://code.google.com/p/guava-libraries/


Since 1.5 you can use the `Arrays` built-in [1]:

    List<String> people = Arrays.asList("Frank", "Mary", "Bob");

[1] http://download.oracle.com/javase/1.5.0/docs/api/java/util/A...


I don't think anyone would disagree with you; we definitely went through a stagnation of Java between 6 and 7 where it seemed Sun was trying to find it's footing with Java, trying to not sink the company, trying to be bought up, trying to figure out where Netbeans fit in the scheme of everything, etc. etc.

It is like the Java world hit the 'pause' button on really ambitious stuff for a few years and the only things that got into releases were the laser-sharp-focused features that the teams needed no variation on. They knew exactly what the feature was, where to take it and when to ship it.

I think it was for the better, because now there is all this pent up energy getting reinjected into the platform and we'll see 8 next year with the rest of all these goodies and hopefully 9/10 2 years after that.

Pretty good recovery IMO. At least it didn't languish and die a horrible death or something.


What's wrong with List.of(...)?

I think adding special syntax rules is a pretty bad idea.


> I like being a pedantic programmer.

Try Scala! (So do I ;)


shouldn't that be

Try Scala! (So do I ;))

then?


Just backslash-escape the internal right-paren.

   (So do I ;\))


Indeed!

BTW, this issue with emoticons and parenthesis was also subject of an XKCD comic: http://www.xkcd.com/541/


ECC excites me - no need to have to ship BouncyCastle anymore.


No love for JSR 310?


Ahh, good point. I'll add that to Java 8 hotness list. Thank you.

UPDATE: Couldn't add it to the original post (edit has expired), here is more info about Joda Time for Java 8[1] for folks that are interested.

[1] http://www.jroller.com/scolebourne/entry/what_about_jsr_310


> here is more info about Joda Time for Java 8

JSR 310 is not Joda for Java 8 (or 7). It's by Joda's author and uses a very similar API, but it's a cleanroom implementation and not compatible with Joda: over time, Stephen Colebourne (Joda lead dev) found core issues in Joda, and JSR-310 is the occasion to use the lessons learned from Joda.


True, but the gap is much, much larger between JDK Date/Time classes and Joda vs that between Joda and JSR-310.


So for languages like Clojure,Scala does this offer any new feature for them?


Yes [1]. Invokedynamic (JSR-262). Quote from an older article [2]:

"... enable[s] implementers of compilers for dynamically typed languages, that is, the people who develop compilers for languages such as JRuby and Jython, to generate bytecode that runs extremely fast in the JVM."

[1] http://blogs.oracle.com/jrose/entry/jsr_292_launched_in_java

[2] http://java.sun.com/developer/technicalArticles/DynTypeLang/...


Indeed, As Charles Nutter (JRuby) wrote:

"There’s a very real chance that invokedynamic could improve JRuby performance many times, putting us on par with our statically-typed brothers like Java and Scala. And that means you can write Ruby code without fear. Awesome."

http://www.engineyard.com/blog/2011/jruby-1-6-released-now-w...


So invokedynamic is already wired into JRuby? I can just install the Java 7 runtime and see significant performance improvements?


JRuby 1.7 has the major Invokedynamic changes. You can play with trunk for now.


Whoo-hoo! Time for the Perl port.


Good luck with that wish.


I would have to lookup the serious academic paper that says peel is technically unparsable in the same ways as PL/1. I think to date there have been two aborted perk on java efforts

Not sure if perl6 has the same properties mind.


I think perl6 is meant to have mutiple implementations.


I wish I had checked that over I just saw that my phone mangled perl twice


Yes, Clojure will profit from Fork/Join: http://download.oracle.com/javase/tutorial/essential/concurr...

For example see here, pvec: http://clojure.org/other_libraries

Of course, improvements like the GC1, improvements in HotSpot etc, they all will make Clojure apps run even faster.


Oh nice, I thought F/J got pushed into 8. Glad to see I was wrong.


For dynamic JVM languages, the new invokedynamic bytecode is a huge performance boost.


Probably not. See what Rich Hickey said about this: http://clojure-log.n01se.net/date/2008-09-03.html#09:13a


For clojure no, but jRuby and several similar languages are getting a huge boost.


Have you seen any actual numbers on this? I've googled around a bit and can't seem to find any.


JRuby developer Charles Nutter claims that Java JDK7 gives a performance boost to JRuby, saying "On bench_threaded_reverse, Java 7 is 20% faster than Java 6, and JRuby plus invokedynamic is 20% faster than that".[1]

From http://en.wikipedia.org/wiki/JRuby with the [1] being

https://twitter.com/#!/headius/status/78282122997149696


I'm a little disappointed that people are still talking about tagged ints. There are so many better ways to avoid the overheap of integers being a refrence type (namely type specializing everything under the sun, particularly your JIT'd code and data structures).


Could you please tell me something more about it? Tagged unboxed data seems to be a nice solution for me.


Well, the problem with it is it has a negative performance impact on everything else in your codebase, the first time you see any pointer you need to check if it's tagged or not. The advantages are clear: you don't need to allocate anything on the heap for integers. Which means you're sacrificing performance on everything else, for integers. Solutions such as automatic type-specializing containers don't carry this downside, and carry the same upside. For example at the moment PyPy type-specializes dictionaries. Python has a single `dict` type, which can store anything, but we type specialize and fallback if we get it wrong. Similarly, we're working on type-specializng lists, tuples, and user objects. If there's anything more I can answer let me know.



«JSR TBD: Project Lambda Lambda expressions (informally, "closures") and defender methods for the Java programming language»

Welcome to the sixties, Java!

Sorry, I couldn't help it >:D


That's a deferred feature. It won't make it into Java until version 8.


Oh, in that case, welcome to the 50s ;)


No no, closures (basic) are part of Java 7.


Does it come with more patents? Serious question.

I'm thinking Oracle tried to put a lot more locks on this version of Java, to make it theirs, and not so open source anymore.


Wasn't the feature freeze before Oracle bought Sun?


Ah, but patents, wonderful things that they are, protect implementations more than they protect features. It's very easy to implement the same feature in different ways, ones that are patent protected if you know how.

Having said that, GPL in theory ensures users and even people making derivatives of Java are protected from patent action by Oracle.


Watch out for the Commercial Features as defined in table 1.1 of this document http://www.oracle.com/technetwork/java/javase/documentation/...

Commercial Features appears to be jRockit technology.


Anyone know why an OS X release is not on the list?



Apple manage their own java builds, and they usually lag way behind the sun/oracle releases.

With java "deprecated" in lion, who knows how long it will take this time.


It's not just Apple anymore.

Apple and Oracle will be working together to create an OpenJDK for Macs.

http://www.macstories.net/news/apple-and-oracle-announce-ope...


Not anymore.


Apple has always handled the Java releases for Mac.. they usually come later.. often much later.



Apple maintain their own release of the JVM for OS X.


No, this has changed. With the start of Lion Apple is no longer the gatekeeper and as was previously reported they are working with Oracle to create new releases of OpenJDK which is why people like myself are wondering where the release is since Apple was stepping away from being the gatekeeper.


Apple is still the gatekeeper in Lion: there are a ton of hooks that auto-install Apple Java via Software Update when it feels you need Java, like running into an applet or invoking the java command line binary.

In the future, they plan on placing Oracle in that role, I guess, but it hasn't happened yet. All Lion does is change it from shipped with the OS to not.


It also seems to remeove the java coocoa bindings and a few other things necessary for some software to work (eg: Juniper SSLVPN JSAM) - it's not clear whether this will be supported through a separate api Juniper needs to use, or whether the bindings needed are just not there. Funnily enough one must also use safari505 and not 6.whatever in this scenario as well.


I'm glad to see it's finally available.

I'm especially happy to see some of the language syntax that makes your standard try/catch/finally blocks a little cleaner and less error prone.


I don't see a "What's new in Java 7" in the above link. Where can a read about it? thanks



Too little to show for 5 years.


yeah but Sun was sold, and other stuff happened. I think it's already great that there is a release with some syntax features that are useful and other nice to have things too. I think Java 8 will come fast there are plenty of new langs now they can't miss the point otherwise companies will continue to migrate to faster evolving languages with faster developing times.


     otherwise companies will continue to migrate to faster 
     evolving languages
That still use the patent-encumbered JVM.


>>faster evolving languages with faster developing times.

Could you provide citations of any studies done please. i.e. How development times differ for small projects and large projects. For small projects I could see other languages being faster, what about large project or really large projects?


I cannot, and I think no one can. There is simply not enough data about it, this could easly become a Masters thesis and I would love to read it. This is just my feeling about Java comparing to some of the new and not so new languages that are evolving in months while java takes years. I am a Java programmer that likes to experience with other langs so don't get me wrong java is an awesome tool and I love working with it, but I think there are other very good tools emerging and getting more and more reliable.


"The company went through massive changes" might work as an _explanation_, and perhaps absolve particular individuals of responsibility, but it doesn't change the reality. Programming doesn't just wait for Sun/Oracle/Java or any other company/language to get its act together any more than any other industry holds steady until one of the participants wakes up.


Would you say the same about C? More is not always better, esp. when it comes to languages.


Having created several "enterprise" systems in Java, I'm now looking into Mono, because there are some aspects of Java that I'm simply tired of having to deal with again and again. So far it looks very interesting and it works really well on Linux and OS X. Anyone here got experience with using Mono (and possibly Fluent NHibernate, WCF, ASP.NET MVC, etc) in the "enterprise" environment?


Does anyone have a link to the changelog?



That image confuses me..

Edid: You change the link didnt you? Im talking about the image from here: http://blogs.oracle.com/theplanetarium/entry/summarizing_jav...


http://mail-archives.apache.org/mod_mbox/lucene-java-user/20...

that worried me little bit. what do you think ?


Making sure that the people excited about Java 7 wait until this gets patched http://news.ycombinator.com/item?id=2820204


Good for Oracle. There are (reasonable) concerns about their ownership of Java, but at least it's moving forward again.


A great release (professionally handled by Oracle), but still I am waiting for Java 8 (esp. closures + modules)


Have anyone done any performance comparison with the openjdk yet? GC related tests would be of high interest :)


Pity though that Swing didn't get much love in this release. But I guess that's the course of things.


Awesome IO stuff - finally we have great cross platform file handling.


Awesome, so java finally has closures & lambdas?


closures yet?


Not yet. Closures and other features were delayed to get Java 7 out sooner.

http://openjdk.java.net/projects/jdk7/features/



oh man, can't wait to use closures in my Java code


Unfortunately, you'll have to wait (until Java 8).


Excellent. Looking forward to the memory enhancements that should help make Minecraft servers less of a hog :)


Too little, too late.


Perfect summation of everything java.


That's quite incorrect, Java is very good about allocating memory, it's often too much, too early.




Registration is open for Startup School 2019. Classes start July 22nd.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: