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

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 .

[Snippet] CSS - Child element overlap parent

I searched from somewhere and found that a lot of people says a basic concept for implementing this feature looks like below: HTML code: <div id="parent">  <div id="child">  </div> </div> And, CSS: #parent{   position: relative;   overflow:hidden; } #child{   position: absolute;   top: -1;   right: -1px; } However, I had a lot of grand-parents in my case and the above code didn't work. Therefore, I needed an alternative. I presumed that my app uses Boostrap and AngularJs, maybe some CSS from them affects mine. I didn't know exactly the problem, but I believed when all CSS is loaded into my browser, I could completely handle it. www.tom-collinson.com I tried to create an example to investigated this problem by Fiddle . Accidentally, I just changed: position: parent; to position: static; for one of parents -> the problem is solved. Look at my code: <div class="modal-body dn-placeholder-parent-positi...

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 = ...

Styling Sort Icons Using Font Awesome for Primefaces' Data Table

So far, Primefaces has used image sprites for displaying the sort icons. This leads to a problem if we want to make a different style for these icons; for example, I would make the icon "arrow up" more blurry at the first time the table loading because I want to highlight the icon "arrow down". I found a way that I can replace these icons with Font Awesome icons. We will use "CSS Pseudo-classes" to achieve it. The hardest thing here is that we should handle displaying icons in different cases. There is a case both "arrow up" and "arrow down" showing and other case is only one of these icons is shown. .ui-sortable-column-icon.ui-icon.ui-icon-carat-2-n-s { background-image: none; margin-left: 5px; font-size: 1.1666em; position: relative; } .ui-sortable-column-icon.ui-icon.ui-icon-carat-2-n-s:not(.ui-icon-triangle-1-s)::before { content: "\f106"; font-family: "FontAwesome"; position: ...

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 ...