15 ms·
Everything about Java 8
- krg 14y agoThis looks very thorough. I appreciate the detailed coverage of lambdas as well-- this is already helping my understanding.
- bhauer 14y agoI'm excited by Java 8 moreso than at least several of the previous versions. Java 7 was especially underwhelming. The lambdas are the new hotness that everyone is aware of. But the work done on streams is almost equally impressive. There are several other small additions and reductions in pain that, when taken as a whole, make this update significant. For example, we finally will have a native JodaTime-like replacement for Calendar, Date, and the supporting utilities. I've long considered the need to enforce external thread safety on DateFormatters to be one of the silliest design failures in Java. Disclosure: this summary was written by a colleague of mine.
- lmfao 14y agoI am hacking a while now with java 8 and can say that one of the most appreciated features in my stack are lambdas. as soon as you are used to them (had the first introduction to lambda-style programming with Blocks in ObjC) you miss them so badly when they are not there (C for example).
- ShabbyDoo 14y agoA year or so ago, I wrote what was effectively a small subset of the JDK8 streams stuff. Incredibly useful, but hard to get right. It's good the core APIs will be part of the JDK so that, like the collections API, they may be adopted with some trust that others will do the same.
- pfalls 14y agoStreams, lambdas and the new time API are wonderful additions to Java.
- j-m-o 14y agoAs a daytime Java developer who dabbles in Scala on the side, these changes look great. The inclusion of a Joda Time style time library is long overdue as well. I just wonder how many years before there's adoption from the general Java community.
- jfb 14y agoIncomplete lambda forms? Facepalm.
- quatrevingts 14y agoIncomplete how exactly?
- smrtinsert 14y agoLanguage and api wise these are nice additions, but all I can think about these days is emscripten. The JVM should support the client side out of the box, why oh why didn't Google buy Java?
- krg 14y agoI'm not sure what you mean exactly, but as mentioned in the article they've built a new JavaScript engine (to replace Rhino) to be included in Java8: http://openjdk.java.net/jeps/174 http://openjdk.java.net/jeps/174
- smrtinsert 14y agoJust that an entire revolution is happening in the browser itself, I'd really like to be able to code Java directly with something GWT. I read recently that GWT has support for the latest html5 stuff, but complaints about compile time and lack of performance after compilation turn me off...
- johnyzee 14y agoYou should give GWT a go. Compile time is a valid complaint, though it can be mitigated by only producing a single permutation (browser specific output) while in development, rather than the default five-six. Also note that during development you usually don't compile but run in "dev mode", a browser plugin that runs against your actual Java code. Performance after compilation is certainly not a problem, on the contrary the GWT output is very tight, especially with full obfuscation (aggressive optimizations, inlining etc.). (I've written a complete HTML5 game engine in GWT: http://www.webworks.dk/enginetest http://www.webworks.dk/enginetest)
- dougk16 14y agoAnother valid complaint is that dev mode runs quite slow, particularly if you're developing something like a game. I read an article about how they are addressing this so that dev mode runs almost as fast as the compiled result, but can't find the link now. Maybe it's already live? Been half a year since I've used GWT. But I second the recommendation overall. One thing I learned the hard way though, is that their widget library is pretty constraining, and a very leaky abstraction. I would consistently run up against walls using a particular widget, bang my head against it for a day or two, then scrap everything and roll my own solution. Eventually, I just used GWT to compile the core business logic of my app (which would have been a nightmare to do in JS), and did UI with the standard HTML/CSS/JS flow. Doing UI in Java is too clunky for me no matter what library I'm using though, so YMMV.
- stack0v3erfl0w 14y agoI recently started developing in Java and the thing I find most irritating is the lack of operators overload.
- pcote 14y agoWhy? Sure, overloading a "+" operator can be elegant looking. But the aesthetic gain vs. maintainability doesn't seem to be worth the tradeoff 99% of the time. I certainly wouldn't want to be the one who has to debug the thing because someone accidentally side effected one of the "operands".
- shin_lao 14y agoWithout operator overloading you cannot write an EDSL.
- stelonix 14y agoNonsense. To paraphrase myself from a similar discussion on reddit: "List.add(otherList) <-- what does this do? Why, compared to operators, would a function name be any better than an operator? Mathematics are part of computer science, and denying basic operators for a reason like "because someone might misuse them" is like denying functions because someone may implement a sum() and call it lcm() (and then we're back to goto land). You're confusing a programmer's error (bad choice of a name/operator function) with a language feature. Just because people can write bad code it does not mean we should disallow them to write great code." Honestly, it's about time the Java crowd stops with the mantra and starts thinking from themselves. Or at least, learn why the reason you hate operator overloading is fallacious.
- miloshadzic 14y agoThe only thing I wish made it in for 8 was coroutines(MLVM project).
- spullara 14y agoI'm definitely pushing for this to be added ASAP — probably won't be before 10 though. In the meantime, it would be awesome if they could get it into OpenJDK behind a flag...
- karianna 14y agoThere's no real work being done on this at the moment (I was involved with trying to kick start a small team with the original patch authors). We've started discussing it again, but it's looking like a case of "Real Life" getting in the way :-|. Will see if I can get the broader Adopt OpenJDK programme to take it on board.
- gjulianm 14y agoAs a C# developer now experimenting with Java, I still miss some things even from Java 8. Probably some have technical reasons behind, but... - Getters and setters, C# style. That is, instead of private int foo; public int getFoo() { return foo; } public void setFoo(int value) { foo = value; } write this: public int Foo { get; set; } which is both easier to write and makes code more readable and understandable. - Mandatory exception declarations in methods. I still don't understand why this is necessary. It ends up either leading to stupid errors (see the following example from the article) void appendAll(Iterable<String> values, Appendable out) throws IOException { // doesn't help with the error values.forEach(s -> { out.append(s); // error: can't throw IOException here // Consumer.accept(T) doesn't allow it }); } , or to lots of methods just throwing Exception (bad practice, I know, but it's easy to fall in), or to useless empty try-catch on methods that won't throw an exception (because you've checked it) and don't want to add the throw declaration. - Modifying external variables in a lambda expression. Just as everyone is used to in Javascript, Ruby, C#... It's pretty useful, even more when you're using lamdbas for common operations such as forEach. - Operator overloading. When you're using data classes (for example, models from a database) where different instances actually point to the same object, overriding == it's more comfortable than foo.equals(bar). Also, the downside of using .equals is that, if foo is null, you will end up with a nice NullPointerException out of nowhere. - Events! I'm amazed how easy is to do events in C# versus how hard (and bloated) in Java. Take this as an example: http://scatteredcode.wordpress.com/2011/11/24/from-c-to-java-events/ http://scatteredcode.wordpress.com/2011/11/24/from-c-to-java... - Pass by reference. Just as if you were passing a pointer in C. I find it surprising how few languages implement this feature, which is pretty useful... And I'm sure I'm missing something... Edit: added three bullet points.
- bhauer 14y agoAt least with respect to checked exceptions, my read of modern popular convention is simply to avoid using checked exceptions unless there is a very strong use-case. In our own code, we have transitioned to using predominantly unchecked exceptions with no decrease in code quality that we have yet perceived. Agreed on assuming the trivial getters and setters if they are not expressly defined. That would be nice. As for modifying variables in lambdas, you need to have a final reference available, meaning you can't modify a primitive. However, you can accomplish roughly the same thing by using a final reference to a boxed (or if parallel, atomic) primitive.
- davesims 14y agoWith the ability to add static methods and default implementations to an interface, what is now the practical difference between that and an abstract class?
- logn 14y agomultiple inheritance?
- alrex021 14y agoInterfaces with the addition of default methods, in contrast to abstract classes, provide the inheritance of behaviour (but not state) from multiple sources.
- danieldk 14y ago- A class can only inherit from one abstract class, but can implement multiple interfaces. - An interface cannot have member variables.
- twic 14y agoAlso, an abstract class can have a constructor (and instance initializers, and initialization expressions for its fields), which an interface can't. That means an abstract class can do work when it is created. Although it's probably a good idea not to do too much work - a factory method would be better for that.
- iso8859-1 14y agoDid you read the article? Try again, search for "Why abstract classes can't be instantiated using a lambda".
- scanr 14y agoJava 8 looks good enough to make Java a reasonable candidate for Java.Next. Especially given that there doesn't appear to be a clear winner between the alternatives (Scala, Groovy, Clojure, Kotlin etc.). Java 8 seems to have borrowed a lot from Guava (Optional, Function, Predicate, Supplier etc.). Extension methods as well as default methods on interfaces would have been nice.
- swift 14y agoMixins would be great too.
- notimetorelax 14y agoOr something similar to Clojure protocols.
- tomjen3 14y agoDefault methods in interfaces makes them mixins.
- spartango 14y agoWoah, that streaming abstraction looks really slick, especially given that it can be automatically parallelized. The idea of doing a one-line parallel map-reduce that is collection.stream().parallel().map(operation1).reduce(operation2); is surprisingly cool imo. And the availability of streams across the collections framework allows that they can be used in routine programming.
- eranation 14y agoYep, Java 8 starts to look a lot like Scala
- pfalls 14y agoAll I ever heard about with Java 8 was lambdas (which is understandably the big name new feature), but streams, in my opinion, are just as exciting. Unlike lambdas and they're new syntax, streams seem like something any developer can quickly pick up and start taking advantage of.
- kainsavage 14y agoI think it gets even easier than that since stream/parallel are the basic calls: collection.parallel().map(operation1).reduce(operation2);
- martinced 14y ago"Interfaces can now define static methods. " Twenty years for that one ; ) zomg. Another one debated at length through flamewars on Usenet and ##java. And now it's here. Feeling good : )
- ShabbyDoo 14y agoThe number of times I've implemented something by convention due to the lack of this construct... One common use case is that I like "value objects" -- an AccountId class vs. just a String or an Integer. I usually implement them using some sort of internment internally -- WeakHashmap, Guava Interner, etc. When reading from a wire format and using value objects, one must presume the existence of a fromString(String key), fromInt, etc. method. I'd love to state explicitly that all ValueObjects have particular, generic-ified static constructors. Much cleaner. And, it avoids the cliche Java programmer shame of implementing AbstractValueObjectFactory, etc. Some static state, if isolated and properly managed, makes life easier.
- RyanZAG 14y agoMassive issue here for many when it comes to Java 8 - what about Android ? Android's dalvik is based off of Apache Harmony, which doesn't appear to be updating anymore. Does this mean no Java 8 for Android/Dalvik? Seems like it would be a major issue if so.
- pjmlp 14y agoGoogle is yet to even add support for the Java 7 language constructs.
- georgemcbay 14y agoThe lack of any public direction on this from Google to Android developers has been annoying me for a while now. It seems like Android has decided to be stuck on Java 6 forever. I'd love to see them really shake things up in Android by, eg, going with NaCL/PNaCL (or even something like seccomp2, don't really care) to manage sandboxing and exposing an API framework (so apps can present common UI widgets) with a C API (regardless of what it is written in underneath) making it relatively easy to consume from any language. Write your Android app in Go, Python, Java, whatever you want, as long as it has API bindings! But I'm not holding my breath on that.
- DoubleMalt 14y agoCan someone please show the java guys the <Number>.TryParse(String s) from C#? I'm convinced everytime I have to manually write the try catch clause for parse a kitten dies somewhere!
- twic 14y agoAs a Java programmer, i agree that the catch blocks around parsing are annoying, but i'm not sure a method that returns an error code is any better. Wasn't that tried back in the '80s? The way Scala (and probably other functional languages, with which i am not familiar) handle this is with a little bit of polymorphism. Using Java syntax, parsing a string into integer would return a Validation<Integer, Exception>, an abstract type which could be either a Failure<Exception> or Success<Integer>. This then exposes methods like ifSuccess(Consumer<Integer>) (it's called something less obvious in Scala, because that's how Scala works) and ifFailure(Consumer<Exception>), and various other useful things. This seems a bit weird at first glance, but it makes it quite easy to deal specifically with either success or failure, or both, or to defer dealing with them until later (you can put a load of Validation objects in a set and worry about whether they're successful or failed later on). It also makes it impossible to ignore failure - there is no error code to forget to check, and no unchecked exception to forget to write a catch block for.
- MichaelGG 14y agoTryParse returns a boolean. So you use it like this: int res; if int.TryParse(s, out res) { // OK } { else // not ok } You certainly do not need an exception to deal with the simple case of "did this string parse into an int". Edit: A great alternative signature is to use Maybe/Option, so you get Some int or None. match int.TryParse s with | None -> ... | Some i -> ...
- DoubleMalt 14y agoAh apparently I remembered it wrong. I thought it was int res = int.TryParse(s, 0); // 0 as the default if parsing fails Of course if there is no reasonable default you should bubble the thing up anyway or handle it on the spot. But very often for input parsing there is sane default you can choose.
- mark_l_watson 14y agoUnless I am mistaking, Java 8 fails to address the major pain-point I have with Java: hash and array literals. For me, one of the big wins of both Clojure and Scala is being able to handle maps, sequences, etc. conveniently.
- abraininavat 14y agoDon't forget Groovy
- pswenson 14y agojava's main principle: preserving backwards compatibility. this is why the iterations are so small and take so long. java tip: don't look at other languages or you'll get depressed at how easy things could be or even should be
- quatrevingts 14y agoReally? new double[] { 1.0, 2.0 }? Arrays.asList("foo", "bar")? Guava's Map builders? Lambdas are what make operations on data structures convenient in Scala and Clojure, not saving a few characters on the handful of literals in your code.
- peeters 14y agoThe lambda and stream additions are great and long overdue, but I've pretty much adapted to using Guava to fill that gap. So right now the thing I'm most interested in is actually the promise of better type inference. Anyone who has used a rich, type safe DSL like Hamcrest or Guava knows the pain of having to give so many type hints to the compiler, when the context provides all that the compiler should need.
- thecombjelly 14y agoThe inclusion of lambdas is great, but not supporting full closures severely hampers their usefulness. Instead of using lambdas to use patterns like CPS (continuation passing style) or alternative object interfaces, lambdas just save you from typing extra characters. It is always fun to watch other languages continue to implement features that bring them closer to lisp. I wonder how much longer it will be until every language is just a lisp dialect. They are moving in the right direction but very slowly. It is impressive though that they have been able to still innovate without breaking backwards compatibility.
- nollidge 14y ago> It is impressive though that they have been able to still innovate without breaking backwards compatibility. Indeed. The .NET IL compiler actually supports closures by generating a class with the lambda's method body as method on that class. That method takes in as parameters whatever outside variables need to be captured. It also supports iterator continuations (e.g. "yield return") by generating an entire class which inherits off of IEnumerable and wraps your single function with all the necessary trappings to track the continuation state. You can see this stuff by looking at C# assemblies in a free program called ILSpy[0]. Normally it'll reverse-engineer these compiler patterns, but if you uncheck all the "decompile" checkboxes in the options, it'll just straight-up translate the IL to C# and you can see the dirty tricks. [0] http://ilspy.net/ http://ilspy.net/
- thecombjelly 14y agoC# is quite impressive, especially in comparison to Java. If it had been released earlier, wasn't owned solely by Microsoft, and supported all major platforms equally, it could have been huge, even larger than Java. If C# had reversed roles with Java a significant portion of the world would have been more productive.
- trailfox 14y agoC# 1.0 was very close to being an exact copy of Java. To say that if C# had been released before Java it would have been more popular is nonsensical as it started life as copy-cat Java. Without Java there wouldn't be a C#. Later versions of C# added more features much faster than Java. Many Java developers have since moved on to Scala and other JVM languages which are more expressive than C#.
- simpsond 14y agoJava 7 failed to excite me. Java 8 however, has many features that I can use today. Lot's of stuff from guava, cleaner anonymous classes (lamdas), trait-like interfaces, FluentIterable++ (streams)... it's a good time to be a java developer.
- olegp 14y agoI find Nashorn particularly interesting, as well as Node.jar: http://insin-notes.readthedocs.org/en/latest/JavaOne2012/nashorn_node_jpa_persistence_bof.html#node-jar-akhil-arora http://insin-notes.readthedocs.org/en/latest/JavaOne2012/nas... Hopefully Nashorn will give http://ringojs.org http://ringojs.org a boost as well.
- pootch 14y agoWell, this is all nice, except that the JVM cant run with a heap more than 8GB without huge GC pauses. It really doesnt matter what java can do . The JVM is broken and is basically a DOS runtime circa 2013.
- IanDrake 14y ago>Non-final variable capture - If a variable is assigned a new value, it can't be used within a lambda. This code does not compile: So, it sounds like that mean no closures? That's one of my favorite tools in c#.
- quatrevingts 14y agoEveryone gets confused by this it seems. You can mutate fields in the enclosing class. You can read locals. If you really want to, you can box a local, and then mutate it inside the box. You can't mutate locals directly, because that would make lambdas significantly slower for very little benefit. (You would not be able to do stack allocation of locals in frames that contain lambdas (unless you could prove that the lambda does not escape).)
- fierarul 14y agoVery interesting read. So, nothing new on the Swing side?
- sgt 14y agoI can't tell if you are serious or not. Swing is dead, from my point of view. In any case, desktop programs isn't really a strength of Java.
- tomjen3 14y agoActually that is a case where Java really shines, as it is cross-platform
- edwinnathaniel 14y agoOracle seems to move to JavaFX. JavaFX is still at its infancy but it shows some promises: iOS + Android (soon), cross-platform installer on desktop OSes (Windows, Mac AppStore) that doesn't require JVM (JDK/JRE) to be installed first. It's ugly in terms of the UI but the infrastructure is there.
- karianna 14y agoSwing is effectively dead. Oracle will no longer invest in the technology, the preferred way forward is definitely JavaFX (2.0+), it shows a lot of promise for those who still need this type of UI tech.
- zmmmmm 14y agoThese changes are the first since Java5 to make a real difference to how I will program, and thus are pretty nice to see. The sad thing is that a large part of my Java programming will involve Android, and thus I will continue living in Java5/6 land, as will numerous libraries and large parts of the Java ecosystem. I wonder when Google will address the future of Java on Android in a substantial way? Eventually it will not be tenable to stay on a 10 year old version of a language. I hope they will seriously consider either updating their supported syntax to be compatible with Java8 or introducing some other language into the Android SDK (Go go!).
- PySlice 14y agoI remember some years ago when I was glad Java 5 had got some really practical new features. I didn't program in Java back then, but I wanted the language to evolve (maybe I was going to need it in the future). Now I do program in Java 5/6 and it would be really sad if the language was still stuck in the 1.4 days.
- foohbarbaz 14y agoI am not sure I am super excited about Java the language increasing in size. As in, the size of the body of knowledge that need to be committed to one's head to comprehend and write the code. I am actually quite opposed to the syntax sugar features like "getters/setters from C#", "events" and what not. Java the language is already large enough. IDEs do a decent job dealing with boilerplate code. Please, no new kludgy additions to the language. Those people that need functional features could use Scala now. Jython is there for those not liking static typing. Why don't we just leave Java alone?
- svdb 14y agoOne small correction/addition: For Stream.anyMatch(), Stream.findFirst() and Stream.findAny() it is mentioned that these are short-circuiting operations. This is however also true for Stream.allMatch() and Stream.noneMatch().
- mhixson 14y agoYou're right! Thanks, I'll get that fixed up in the next batch of edits.