We're not used to new Java 8 features yet, but we received already some information about the next Java release. Until they are confirmed, we can sit down and talk about what we already have. Today I want to tell you about the best Java features of all time. Don't take it too seriously - this is just my opinion based on what I use for work and what I like most.
![]() |
| Image from: http://www.gopixpic.com |
Generics are one of the most important things in such a strong object-oriented programming language like Java, because they allow to use generic algorithms in the code. There is a stronger type checking during the compilation time (which allows you to fix errors during the compilation time instead of runtime, where they can be harder to find). Additional benefits are elimination of cast, and code reuse even for different input types. Let's see an example below:
public class SomeGeneric<T> {
private T value;
public SomeGeneric() {
value = null;
}
public SomeGeneric(final T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(final T value) {
this.value = value;
}
And possible way to use it:
SomeGeneric<String> strGeneric = new SomeGeneric<>("How to noob in Java");
SomeGeneric<Integer> intGeneric = new SomeGeneric<>(1);
Advantages over raw types:
SomeGeneric rawType = new SomeGeneric(1); Integer number = (Integer) rawType.getValue(); SomeGeneric<Integer> intGeneric = new SomeGeneric<>(1); number = intGeneric.getValue();
2. Enhanced for loop (since 1.5)
Enhanced loop statement is used to make your loops more compact and easier to read. It's not something big, but if you have a lot of collections to check, you'll be glad it exists. Example below shows the standard and enhanced loops:
final List<SomeGeneric<String>> list = new ArrayList<>();
list.add(new SomeGeneric<>("How to noob in Java"));
list.add(new SomeGeneric<>("enhanted"));
list.add(new SomeGeneric<>("loop"));
for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getValue());
}
for(final SomeGeneric<String> gen : list) {
System.out.println(gen.getValue());
}
3. Diamond operators (since 1.7)
The diamond operators are created to simplify instantiation of generic objects. Many people don't like the way it's done in Java 7. However this was the only way to preserve compatibility with the old Java code (before Java 1.5, when there were no generics at all, just raw types). Let's see an example of diamond operators (there are few above too):
final Map<SomeGeneric<String>, List<SomeGeneric<String>>> genericMap = new HashMap<SomeGeneric<String>, List<SomeGeneric<String>>>();
And with diamonds:
final Map<SomeGeneric<String>, List<SomeGeneric<String>>> diamondMap = new HashMap<>();
I don't know how you feel about that but I really enjoy not having to rewrite types again.
4. Annotations (since 1.5)
Annotation is a form of metadata, providing data about a program that is not part of the program itself. Nowadays it's hard to imagine Java world without annotation. However the basic use of annotations it's not currently the way how we love to use it. We will see it in the next chapter. Let's write our own annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
boolean isInherited() default true;
String someAction() default "How to noob in Java";
}
As you can see it's almost like an interface, but you don't have to implement annotation method in class which you marked with this Annotation. You can see that I marked this annotation as a type annotation (so it will be used to mark the classes/enums/interfaces) with Runtime retention, which allows us to use it while the program is running. Let's see the difference between annotation and standard implementation of the interface:
@MyAnnotation
public class AnnotationClass {
}
public class AnnotationClass implements MyAnnotation {
@Override
public Class<? extends Annotation> annotationType() {
return MyAnnotation.class;
}
@Override
public boolean isInherited() {
return true;
}
@Override
public String someAction() {
return "How to noob in Java";
}
}
5. Reflection mechanism (since 1.1)
"Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible."
So this is what Oracle said about reflection. Currently, the most common usage of reflection is scanning classes for annotations by class loaders. Spring is one of the frameworks which strongly use reflection. Spring provides us features like Dependency Injection (DI) or model-view-controller pattern by annotations, which is easier and faster (in my opinion). Of course it's not only a Spring, at this time a lot of frameworks do the same. To be honest I'm not a fan of programming by reflection, however there are plenty of situations where this feature is just awesome (changing behavior of existing libraries, annotations + reflection, debugging and so on). Let's try reflection with created by us annotation (in this case I just created main method in AnnotationClass marked by @MyAnnotation):
public static void main(final String[] args) {
final Class<AnnotationClass> aClass = AnnotationClass.class;
final Annotation[] annotations = aClass.getAnnotations();
for(final Annotation annotation : annotations) {
if(annotation instanceof MyAnnotation) {
final MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("Welcome to: " + myAnnotation.someAction());
}
}
}
As you can notice I scan our AnnotationClass to find all existing annotations and after that if it was MyAnnotation type, I called its method someAction to the standard output. More information about the Reflection API you can find here.
6. Streams (since 1.8)
I have talked about the Streams here, but I will say it once again - they are awesome (and less readable, not reusable and supports chained calls...). No more loops and conditions checking:
public static List<Integer> roll(final Integer dice, final Integer rollNumber) {
final Random random = new Random();
final IntStream intStream = random.ints(Const.I_1, dice + Const.I_1);
return intStream.limit(rollNumber).boxed().collect(Collectors.toList());
}
As you can see, this method uses new Random mechanism, predefined IntStream object, and it methods + Collectors to return us a list of random generated int values based on given dice (like in RPG games dice x) and number of rolls. Before Java 8 we had to prepare method like this:
public static List<Integer> roll(final Integer dice, final Integer rollNumber) {
final Random random = new Random();
final List<Integer> list = new ArrayList<>(rollNumber);
for(int i = 0; i < rollNumber; i++) {
list.add(random.nextInt(dice) + Const.I_1);
}
return list;
}
7. Optional objects (since 1.8)
I believe this is Oracle's answer to programmers who are not enough motivated to use default objects in Java. There is a design pattern called Null Object, which allows us to use this default object instead of null checking. Of course each action on the default object has no result. It's transparent for the program. However programmers don't use this design pattern so often. Mostly because they have to work with old code, which needs a lot of time to refactor (and of course we have not enough time for this). These kind of situations lead us to creating conditional checking like here:
public static void someAction(final SomeGeneric<String> generic) {
if(generic != null) {
final String value = generic.getValue();
// ... Something more here.
}
}
Since Java 8, we can do the same with:
public static void someOptionalAction(final SomeGeneric<String> generic) {
final Optional<SomeGeneric<String>> opt = Optional.ofNullable(generic);
opt.ifPresent(/* some lambda expression here*/);
}
To make this example work, you can use lambda expression below:
x -> System.out.println(generic.getValue())
And check the result with this two calls:
SomeGeneric.someOptionalAction(null);
SomeGeneric.someOptionalAction(new SomeGeneric<>("How to noob in Java"));
Of course Optional is much more powerful, for example it allows to define alternatives if there is no value in Object which is wrapped by Optional (so to define default behavior without modifying wrapped object).
public static String someOtherOptionalAction(final SomeGeneric<String> generic) {
final Optional<SomeGeneric<String>> opt = Optional.ofNullable(generic);
return opt.map(SomeGeneric<String>::getValue).orElse("Nothing here");
}
You can try it with:
System.out.println(SomeGeneric.someOtherOptionalAction(new SomeGeneric<>("How to noob in Java")));
System.out.println(SomeGeneric.someOtherOptionalAction(null));
For more information about Optional
Conclusion
In this article I have shown some of the features of Java language which I like most. I also believe that each of these chapters is a great material for a separate article. I'm quite sure that your experiences could be different than mine, so maybe you have your own favorites features, which aren't mentioned here. I'm waiting for your opinions and I wish you a happy New Year.







0 komentarze:
Post a Comment