Welcome!

Article

Revisitng Java SE 5 Features! @CloudExpo #Java #Cloud #OpenSource5

A tutorial series on Java as we all eagerly await the official release of Java SE 9

I have provided some of the most important core language enhancements for JDK 5.0, along with code samples. The examples provided below can be directly pasted into your IDE and you may name the class as provided.

Type Safe Enumerations
Enumerations are provided as an easier way to maintain similar values (constants) that can be assigned to a type. The keyword used is enum. You may additionally define constructors. The method ordinal() will return the index of the enum constant and the method name() will return the name of the enum constants. You may also use valueOf() to return the value of a string as an enum constant. You may directly execute the code below in Eclipse to understand better.
 public class jdk5_Enum {  
      public static enum Java {JDK5, JDK6, JDK7, JDK8};  
      public static enum JavaVer {   
           JDK5(5), JDK6(6), JDK7(7), JDK8(8);  
           int x;  
           JavaVer(int x) {  
                this.x = x;  
           }  
      }  
     
      public static void main(String[] args) {  
           Java java = Java.JDK6;  
           System.out.println(Java.JDK5);  
           System.out.println(java);  
           System.out.println(java.ordinal() + ":" + java.name());  
           JavaVer javaVer = JavaVer.JDK7;  
           System.out.println(javaVer.x);  
           System.out.println(javaVer.ordinal() + ":" + javaVer.name());  
           String myJava = "JDK8";  
           System.out.println(Java.valueOf(myJava));  
           JavaVer javaSwitchVer=JavaVer.JDK6;  
           switch(javaSwitchVer) {  
                case JDK5: {System.out.println("5.0"); break;}  
                case JDK6: {System.out.println("6.0"); break;}  
                case JDK7: {System.out.println("7.0"); break;}  
                case JDK8: {System.out.println("8.0"); break;}  
           }  
      }  
 }  


Variable Arguments
Varargs should be provided as the last parameter of any method and can be used to pass zero or more arguments to the method. You may directly execute the code below in Eclipse to understand better.
 public class jdk5_Varargs {  
      public void getData(String...values) {  
           for(String string:values) {  
                System.out.println(string);  
           }  
      }  
     
      public static void main(String[] args) {  
           jdk5_Varargs varargs = new jdk5_Varargs();  
           varargs.getData("Apple","Banana","Cucumber","Radish");       
           String[] vargs = new String[] {"Radia","Cloud","Hewlett","Packard"};  
           varargs.getData(vargs);  
      }  
 }  


Generics
Generics is used to maintain compile-time type safety on code. It follows type erasure and allows to maintain a control over the types that can be maintained in collections. You may also use generics to define method or class 'templates'. You may directly execute the code below in Eclipse to understand better. For more on generics, refer to my article in CodeGuru.
 public class jdk5_Generics {  
      List<String> genericList = new ArrayList<String>();  
   
      public static void main(String[] args) {            
           jdk5_Generics jGenerics = new jdk5_Generics();  
           // generic for type safety  
           List<String> jGenericsList = jGenerics.genericList;  
           jGenericsList.add("Sumith");  
           jGenericsList.add("Kumar");  
           jGenericsList.add("Puri");  
           for(String str:jGenericsList) {  
                System.out.println(str);  
           }  
           // generic variables - class and method generic templates  
           List<? extends Vehicle> jGenericObjList = new ArrayList();  
           Vehicle car = new Car();  
           RentVehicle<Vehicle> rentVehicle = new RentCar<Car>();  
           rentVehicle.rentOut(car);  
      }  
 }  
 class Vehicle {  
      Integer regn;  
      String type;  
      public Integer getRegn() {  
           return regn;  
      }  
      public void setRegn(Integer regn) {  
           this.regn = regn;  
      }  
      public String getType() {  
           return type;  
      }  
      public void setType(String type) {  
           this.type = type;  
      }            
 }  
 class Car extends Vehicle {  
 }  
 interface RentVehicle <T extends Vehicle> {  
      public void rentOut(T vehicle);  
 }  
 class RentCar<Car> implements RentVehicle{  
      public void rentOut(Vehicle vehicle) {            
           System.out.println("Rent Vehicle => Rent Car");  
      }  
 }  


Autoboxing/Unboxing
Autoboxing or Unboxing will allow to convert from primitive types to wrapper types and vice versa. You may directly execute the code below in Eclipse to understand better.
 public class jdk5_Autoboxing {  
      Integer integer = new Integer(50);  
      public void setValue(int integer) {  
      }  
      public Integer getValue() {  
           return integer;  
      }  
      public Float getFloat() {  
           return 6.0f;  
      }  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {            
           jdk5_Autoboxing autoboxing = new jdk5_Autoboxing(); // autounboxing  
           autoboxing.setValue(new Integer(5));  
           int x = autoboxing.getValue();  
           // this is not valid => autounboxing - upcasting - autoboxing  
           // Double y = autoboxing.getFloat();  
      }  
 }  


Enhanced For Loop
Enhanced For Loop allows an easier way to loop through objects of a common super-type. You may directly execute the code below in Eclipse to understand better.
 public class jdk5_EnhancedFor {  
      public static void main(String[] args) {  
           jdk5_EnhancedFor ef = new jdk5_EnhancedFor();  
           List<Animal> animals = new ArrayList();  
           Animal animal = new Animal();  
           animals.add(animal);  
           animal = new Dog();  
           animals.add(animal);  
           animal = new Cat();  
           animals.add(animal);  
           animal = new Dog();  
           animals.add(animal);  
           animal = new Cat();  
           animals.add(animal);  
           animal = new Dog();  
           animals.add(animal);  
           animal = new Animal();  
           animals.add(animal);  
           animal = new Animal();  
           animals.add(animal);  
           for(Animal anim: animals) {  
                anim.print();  
           }  
      }  
 }  
 class Animal {  
      public void print() {  
           System.out.println("Animal");  
      }  
 }  
 class Dog extends Animal {  
      public void print() {  
           System.out.println("Dog");  
      }  
 }  
 class Cat extends Animal {  
      public void print() {  
           System.out.println("Cat");  
      }  
 }  


Static Imports
Static Imports allows you to import static methods and fields from other classes or interfaces, most useful when you to easily refer to static members from other classes without the reference of their class. You may directly execute the code below in Eclipse to understand better. Note that it is a compile-time error to import a type from unnamed or default package.
 import static jdk5.features.jdk5_StaticImport_Source.product;  
 public class jdk5_StaticImport {  
      public static void main(String[] args) {  
           System.out.println(product);  
      }  
 }  
The source for importing the above is the following class which is located under the package 'jdk5.features'

 package jdk5.features;
 public class jdk5_StaticImport_Source {  
      public static final String product = "radia-cloud";  
      public static final String version = "09.20.0000";  
      public static void setup() {  
           System.out.println("Setting up the Radia Server....");  
      }  
      public static void init() {  
           System.out.println("Initializing the Radia Server....");  
      }  
 }  


Annotations
Annotations are way of syntactic meta-data to inform and use that it signifies a specific type of functionality that can be processed using reflection. It can also be used to suppress warnings and inform of errors. The source file below is located under the package 'jdk5.features'
 package jdk5.features;  
 import java.lang.annotation.ElementType;  
 import java.lang.annotation.Retention;  
 import java.lang.annotation.RetentionPolicy;  
 import java.lang.annotation.Target;  
 @Retention(RetentionPolicy.RUNTIME)  
 @Target({ElementType.FIELD,ElementType.METHOD})  
 public @interface jdk5_Annotation_Source {  
 }  

The RetentionPolicy as mentioned can be either of Runtime (Retained by VM), Source (Discarded by Compiler) or Class (Not be Retained by VM). The source below is located under the package 'jdk5.features'
 package jdk5.features;  
 public class jdk5_Annotation_Usage {  
      @jdk5_Annotation_Source  
      public String myMessage;  
      public void annotated() {  
           System.out.println(myMessage);  
      }  
 }  

Now, You may directly execute the code below in Eclipse to understand Annotations better. (Default Package)
 import java.lang.reflect.Field;  
 import jdk5.features.jdk5_Annotation_Source;  
 import jdk5.features.jdk5_Annotation_Usage;  
 
 public class jdk5_AnnotationProcessor {  
      public static void main(String[] args) throws Exception {  
           jdk5_Annotation_Usage message = new jdk5_Annotation_Usage();  
           Field[] method = message.getClass().getDeclaredFields();  
           for(Field methd: method) {  
                jdk5_Annotation_Source annos = methd.getAnnotation(jdk5_Annotation_Source.class);                 
                if(annos != null) {  
                     methd.set(message,"Messenger of God!");  
                     // using reflection & annotations we set the value - check if set                  
                     message.annotated();   
                }  
           }  
      }  
 }  



Happy Coding with JDK 5!

More Stories By Sumith Kumar Puri

Sumith Kumar Puri, an author (Java/JEE) at Packt Publishing, has close to 14 years of experience in entrepreneurship, conceptualization, architecture, design and development of software products and solutions. He also holds multiple certifications in Core Java, JEE, C, C++, Algorithms and Data Structures. He is an open source contributor and likes competitive programming and hackathons. He has 11 publications to his name in international and national conferences, journals and magazines. He is an active member of the IEEE/Computer Society, ACM and CSI.

He holds a Bachelor of Engineering [Information Science and Engineering] from Sri Revana Siddeshwara Institute of Technology, Bangalore, India. He has also completed the Executive Programme [Data Mining and Analytics] from the Indian Institute of Technology, Roorkee, India and the Executive Certificate Programme [Entrepreneurship] from the Indian Institute of Management, Kashipur, India. His current interests are in data mining, machine learning, Big Data and artificial intelligence. He is based out of Bangalore, India.

Latest Stories
"As we've gone out into the public cloud we've seen that over time we may have lost a few things - we've lost control, we've given up cost to a certain extent, and then security, flexibility," explained Steve Conner, VP of Sales at Cloudistics,in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We want to show that our solution is far less expensive with a much better total cost of ownership so we announced several key features. One is called geo-distributed erasure coding, another is support for KVM and we introduced a new capability called Multi-Part," explained Tim Desai, Senior Product Marketing Manager at Hitachi Data Systems, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"With Digital Experience Monitoring what used to be a simple visit to a web page has exploded into app on phones, data from social media feeds, competitive benchmarking - these are all components that are only available because of some type of digital asset," explained Leo Vasiliou, Director of Web Performance Engineering at Catchpoint Systems, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
Kubernetes is an open source system for automating deployment, scaling, and management of containerized applications. Kubernetes was originally built by Google, leveraging years of experience with managing container workloads, and is now a Cloud Native Compute Foundation (CNCF) project. Kubernetes has been widely adopted by the community, supported on all major public and private cloud providers, and is gaining rapid adoption in enterprises. However, Kubernetes may seem intimidating and complex ...
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, has been named "Bronze Sponsor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
"We focus on SAP workloads because they are among the most powerful but somewhat challenging workloads out there to take into public cloud," explained Swen Conrad, CEO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"Outscale was founded in 2010, is based in France, is a strategic partner to Dassault Systémes and has done quite a bit of work with divisions of Dassault," explained Jackie Funk, Digital Marketing exec at Outscale, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"I think DevOps is now a rambunctious teenager – it’s starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We are still a relatively small software house and we are focusing on certain industries like FinTech, med tech, energy and utilities. We help our customers with their digital transformation," noted Piotr Stawinski, Founder and CEO of EARP Integration, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.