Category: Java 5 features

Java 5: Annotations

Annotations are introduced in Java 5 to provide a mechanism that allows you to write info about your code directly in the code. You can use annotations  within packages, classes, methods, variables and parameters. Annotations syntaxes and elements The character @ is used as prefix of the annotation name. In that way you indicate the […]

Java 5: Generics

The generics is introduced in Java 5 to provide a type-safety at compile time and to avoid the ClassCastException at runtime. By using generics for example you can prevent adding an Integer to a Java collection of Strings. Generic wildcards. The Unknown Wildcard List<?> means the list type is unknown. This could be a List<Integer>, […]

Java 5: Enum types

The enum type is a new feature in Java 5. Whenever you have a fixed set of constants you can use the enum type. An example is the seasons of the year, the days of the week and the planets of the solar system. We use the uppercase letters for the names of an enum […]

Java 5: Autoboxing and unboxing

The Conversion between the primitive data types and their corresponding object wrappers directly is a new feature in Java 5. The conversion from primitive data types to their object wrappers is called autoboxing, but converting of the other way around is called unboxing. For more info click here to read Oracle’s explanation. Example 1: Autoboxing and unboxing […]

Java 5: Static import

To access a static member in earlier Java versions we needed to write the class name first followd by the name of the static member. For example to access the static method max of the class Math, we wrote the statement as follows: Math.max(3, 6). The static import allows you to access the method max […]

Java 5: Varargs

Varargs allows you to avoid writing a method several times for multiple arguments. Before this feature, the solution was overloading methods. If the number of the arguments is unknown, you can use Varargs as shown in the exercise below. For more info click here to read Oracle’s explanation. Note: By applying this feature to different types of […]

Java 5: Enhanced for loops

Enhanced for loops is introduced in Java 5. This feature allows you to handle loops in a simple. In the example below we compare the new for loop with the older one! For more info click here to read Oracle’s explanation. Example 1: Enhanced for loops code What is the output of the following code? Author: Sar […]