From Java 9 to Java 14, What’s new? (Part 3)

Advertisements

Java used to have a new version every 3 to 4 years until Java 9 release. After Java 9 we have a 6 months cadence for releasing a new Java version. Since September 2017 until now, we have had 6 different Java versions, with an LTS version (Java 11). At this moment, the latest Java 14 is the latest version. So, it’s not easy to keep in mind all the new features that are being added to Java with every release. The goal of this article is to provide a summary of the main features that a Java Developer should keep in mind from Java 9 to Java 14.

In order to organize better all this information, this post will be split into 3 parts:
Part 1 (Java 9 to Java 11)
Part 2 (Java 12 to Java 14)
– Part 3 (A comparison between Java 8 code to Java 14).

So, finally it’s time to see how the code has changed with the features the we have reviewed in the previous parts. Let’s start with some code that should be familiar for people that knows Java 8.

public class Java8Code {
 	public static void main(String [] args){
      
        //Creates a List of Users
        List<User> userList = new ArrayList<>();
        userList.add(new User(1l,"Peter"));
        userList.add(new User(2l, "Jackson"));
        userList.add(new User(3l, "John"));
      
        //Creates a JSON array string from User Objects
        //It assigns an age for each user
        String jsonString =  userList.stream().map(u -> {
            int age = 0;
            switch(u.getName()){
              case "Peter" : 
                 age = 30;
                 break;
              case "Jackson" :
                age = 24;
                break;
              case "John" : 
                age = 33;
                break;
            }
          String template = "{\n"+
                  "\"name\" : \"%s\",\n"+
                  "\"age\" : %d \n"+
                  "}";
          return String.format(template, u.getName(), age);
        }).collect( Collectors.joining( ",", "[", "]" ) );
          
        //Sends the Json to an API
        URL obj = new URL("https://mydomain.com/api/users");
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("POST");
		con.setDoOutput(true);
		OutputStream os = con.getOutputStream();
		os.write(jsonString.getBytes());
		os.flush();
		os.close();

		BufferedReader in = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
		String inputLine;
		StringBuilder response = new StringBuilder();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

        //Writes the API's response into a File
        try (FileWriter writer = new FileWriter(File.createTempFile("test", ".txt"))){ 
	      writer.write(response.toString()););
        }
    }
}

public class User {
 	 private Long id;
     private String name;
  
     public User(long id, String name){ 
       this.id =  id;
       this.name = name;
     }
  
     public Long getId(){
       return this.id;
     }
     public void setId(Long id){
     	this.id = id;
     }
     public String getName(){
       return this.name;
     }
     public void setName(String name){
     	this.name = name;
     }
  
     public boolean equals(Object obj){
       if(obj != null && obj instanceof User){
         User temp = (User) obj;
         return obj.getId() != null && obj.getId().equals(this.id);
       }
       return false;
     }
  
     public int hashCode(){
       return 42;//Implement something better here
     }
  
     public String toString(){
       return "[id="+id+", name="+name+"]";
     }
}

Now, it’s time to see the same functionality but using new features present in Java 14.

Advertisements
public class Java14Code {
 	public static void main(String [] args){
      //Creates a List of Users
      var userList = List.of(new User(1l, "Peter"), 
                             new User(2l, "Jackson"),
                             new User(3l, "John"));
      
      //Creates a JSON array string from User Objects
      //It assigns an age for each user
      var jsonString = userList.stream().map(u -> {
      		var age = switch(u.name()){
                case "Peter" -> 30;
                case "Jackson" -> 24;
                case "John" -> 33;
                default -> 0;
        	}
        	return """{
                       "name" : "%s",
                       "age" : %d ,
                      }"""".formatted(u.name, age);
        }).collect( Collectors.joining( ",", "[", "]" ) );
        
        //Sends the Json to an API
        var httpClient = HttpClient.newBuilder().build();
        var request = HttpRequest.newBuilder()
            .uri(URI.create("https://mydomain.com/api/users"))
            .POST(HttpRequest.BodyPublishers.ofString(jsonString))
            .build();
      
        var response = httpClient.send(request,
                HttpResponse.BodyHandlers.ofString());

        //Writes the API's response into a File
        Files.writeString(Files.createTempFile("test", ".txt"), 
                          response.body);
    }
}

public record User(Long id, String name){}

As we can noticed we have reduced a lot of the code, more than 50%, and this new code does the same. In addition to that, the code is more readable and for sure it will be simpler to mantain.

Conclusion

Java is a programming language that is evolving constantly, as we can see It has added very nice features in the last releases, reducing the amount of code we need to implement the same. Next releases will be implementing a lot more of features that we are looking forward to see them.

Even though some people have been telling that Java is death and other languages like Kotlin, Python and Java Script (Node JS) will become the #1 in the industry, and also that Java is death because is simplet to code in other languages, we can say that for sure Java is more alive than ever.

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *