Skip to main content

Small Changes to Java 7 via Project Coin and Why They are Useful


Did you know how new features were added into Java 7? The following are functionalities that can be considered.
Source: [1]
Project Coin is all about the changes in the range from syntactic sugar to new language feature. This is what we're talking about today.

Since Java 7 is the first version developed in an open source manner, there is an amount of actions that must be performed for any changes as follows:
  • Update the Java Language Specification (JSL)
  • Implement a prototype in the source compiler
  • Add library support essential for the change
  • Write tests and examples
  • Update document
  • Etc, ...
Project Coin has submitted a lot of proposals (almost 70) but only some of them are chosen to Java 7. Why? Briefly, Java is a rich static type system and it has a lot of possible interaction points between different bits of it. Making changes to this type system is prone to creating unexpected surprises.

Wow! It is tough, right? Let's take a look what features Project Coin brought to Java 7.

Strings in switch statement

Question: Why do we need "switch"? (already supported by prior Java 7)
Answer: To avoid lots of ugly nested "ifs".
Question: Why do we need "string" in "switch"?
Answer: Just to make life in Java 7 a little bit easier. Agree?

Enhanced syntax for numeric literals

Underscores in numbers to improve readability.
E.g: 100_000_000 and 10_000_000 are much more readable than 100000000 and 10000000.

Improved exception handling

- Multicatch: it groups a family of exceptions into one catch statement; this feature can reduce code duplication.
- Final rethrow: it won't force to declare the exception signature. For example, my IDE complains of the block below with Java 6 compiler, but Java 7.

However, the issue here is the real dynamic type of the exception has been swallowed if we declare the exception signature.
And, the change in Java 7 is just simple as follows:

try {
  doSomethingWhichMightThrowIOException();
  doSomethingElseWhichMightThrowSQLException();
} catch (final Exception e) {
  //...
  throw e;
}

Why is final keyword useful? Because it provides a new semantics of catch and rethrow. The appearance of the final keyword indicates that the type that’s actually thrown is the runtime type of the exception that was encountered.

Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final.

Try-with-resources

#Funfact: Virtually no one gets manual resource closing 100 percent right.
Therefore, using try-with-resources to eliminate unnecessary bugs from your codebase.

try(OutputStream out = new FileOutputStream(file);
InputStream is = url.openStream()){
 byte[] buf = new byte[4096];
 int len;
 while ((len = is.read(buf)) > 0) {
  out.write(buf, 0, len);
 }
}

Diamond syntax

To avoid the definition and setup of instances can be really verbose.
#Funfact: Why "diamond syntax" name? Because original name, ITIGIC (Improved Type Inference for Generic Instance Creation), is a very long(stupid) name and the shortened type information looks like a diamond.

Simplified varagrs method invocation

What is it? It just moves a warning about type information for a very specific case where varargs combines with generics in a method signature.

An admitted weaknesses of Java’s generics—you aren’t normally allowed to create an array of a known generic type. For example, this won't compile:

HashMap<String, String>[] arrayHm = new HashMap<>[2];

So when it runs into this circumstance, the compiler cheats and breaks its own rule about the forbidden array of generic type. It throws the warning "unchecked" which is darkly meaning. Oops! Then, dummy developers want to know why their methods are "unchecked"? They need an explanation.

To make things easier for developers and by annotating the method with "@SafeVarargs", the developer essentially asserts that method doesn't perform any unsafe operations. Known issue! ;)

Reference:



[1]. Benjamin J. Evans and Martijn Verburg, “The Well-Grounded Java Developer: Vital techniques of Java 7 and polyglot programming"

Comments

Popular posts from this blog

Make simple music program with beep(freq, duration) with Pascal

Pascal is my first programing language when I have studied in high school. It was really exciting for me. :) The Pascal programming language was created by Niklaus Wirth in 1970. It was named after Blaise Pascal, a famous French Mathematician. It was made as a language to teach programming and to be reliable and efficient. Pascal has since become more than just an academic language and is now used commercially . I tried to make a simple music program by using Lazarus IDE on MS Window 7, 64-bit. It frustrated me a few times how difficulty to use Sound command to make a sound. Sound did not work on my compiler and my platform anymore. So far, I just could use beep(freq, duration) from window unit to implement my work. Here is my code. ;) program mysong; uses Windows, crt; const C: Integer = 512; { x = A * EXP(LN(2)/12)} C_: Integer = 542; D: Integer = 574; D_: Integer = 608; E: Integer = 644; F: Integer = 682; F_: Integer = 723; G: Integer = ...

BIRT - Fix the size of an image

I use a dynamic image as a logo my report in pdf. At the beginning, I use table to align the logo in left or right. I meet a problem with some images with a large width or height. My customer requires that the logo should be displayed in original size. These following steps solves my problem: 1. Use Grid instead of Table 2. Set Grid "Height" is 100%  and "Width" is blank 3. Set "Fit to container" for images are "true". Download the the template here .

Monday vhandit #2

  Introduction to OpenLDAP directory service "A directory is a specialized database specially designed for searching and browsing, in addition to supporting basic lookup and update functions" A directory service can be local, providing a restricted context; or global, providing service to a much broader context. Curlie is a good example of a directory service. LDAP (Lightweight Directory Access Protocol) is a protocol for accessing directory services , specifically X.500-based directory services. OpenLDAP is an open-source implementation of LDAP. Writing system software: code comments I have read Clean Code (by Uncle Bob) and I thought that I should void comments since the code it explains its implementation itself. That is right but not always true. In this post, the author categorized the comments into 9 types. Only "trivial comments" and "backup comments" are the ones that should be avoided. I myself agree with "writing good comments is harder tha...

Coding Exercise, Episode 1

I have received the following exercise from an interviewer, he didn't give the name of the problem. Honestly, I have no idea how to solve this problem even I have tried to read it three times before. Since I used to be a person who always tells myself "I am not the one good at algorithms", but giving up something too soon which I feel that I didn't spend enough effort to overcome is not my way. Then, I have sticked on it for 24 hours. According to the given image on the problem, I tried to get more clues by searching. Thanks to Google, I found a similar problem on Hackerrank (attached link below). My target here was trying my best to just understand the problem and was trying to solve it accordingly by the Editorial on Hackerrank. Due to this circumstance, it turns me to love solving algorithms from now on (laugh). Check it out! Problem You are given a very organized square of size N (1-based index) and a list of S commands The i th command will follow t...

How to convert time between timezone in Java, Primefaces?

I use the calendar Primefaces component with timeOnly and timeZone attributes for using only hour format (HH:mm). Like this: <p:calendar id="xabsOvertimeTimeFrom" pattern="HH:mm" timeOnly="true" value="#{data.dateFrom}" timeZone="#{data.timeZone}"/> We can convert the value of #{data.dateFrom} from GMT/UTC time zone to local, conversely, from local time zone to GMT/UTC time zone. Here is my functions: package vn.nvanhuong.timezoneconverter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class TimeZoneConverter { /** * convert a date with hour format (HH:mm) from local time zone to UTC time zone */ public static Date convertHourToUTCTimeZone(Date inputDate) throws ParseException { if(inputDate == null){ return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(inputDate); int ...