DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Java 7: Project Coin in code examples

Java 7: Project Coin in code examples

Niklas Schlimm user avatar by
Niklas Schlimm
·
Dec. 05, 11 · Interview
Like (0)
Save
Tweet
Share
11.11K Views

Join the DZone community and get the full member experience.

Join For Free

This blog introduces - by code examples - some new Java 7 features summarized under the term Project Coin. The goal of Project Coin is to add a set of small language changes to JDK 7. These changes do simplify the Java language syntax. Less typing, cleaner code, happy developer ;-) Let's look into that.


Prerequisites

Install Java 7 SDK on your machine
Install Eclipse Indigo 3.7.1

You need to look out for the correct bundles for your operating system.

In your Eclipse workspace you need to define the installed Java 7 JDK in your runtime. In the Workbench go to Window > Preferences > Java > Installed JREs and add your Java 7 home directory.


Next you need to set the compiler level to 1.7 in Java > Compiler.


Project Coin

Improved literals

A literal is the source code representation of a fixed value.

"In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you to separate groups of digits in numeric literals, which can improve the readability of your code." (from the Java Tutorials)
public class LiteralsExample {

 public static void main(String[] args) {
  System.out.println("With underscores: ");
  
  long creditCardNumber = 1234_5678_9012_3456L;
  long bytes = 0b11010010_01101001_10010100_10010010;
  
  System.out.println(creditCardNumber);
  System.out.println(bytes);
  
  System.out.println("Without underscores: ");
  
  creditCardNumber = 1234567890123456L;
  bytes = 0b11010010011010011001010010010010;
  
  System.out.println(creditCardNumber);
  System.out.println(bytes);
  
 }
}

Notice the underscores in the literals (e.g. 1234_5678_9012_3456L). Results written to the console:

With underscores: 
1234567890123456
-764832622
Without underscores: 
1234567890123456
-764832622

As you can see, the underscores do not make a difference to the values. They are just used to make the code more readible.

SafeVarargs

Pre-JDK 7, you always got an unchecked warning when calling certain varargs library methods. Without the new @SafeVarargs annotation this example would create unchecked warnings.

public class SafeVarargsExample {

 @SafeVarargs
 static void m(List<string>... stringLists) {
  Object[] array = stringLists;
  List<integer> tmpList = Arrays.asList(42);
  array[0] = tmpList; // compiles without warnings
  String s = stringLists[0].get(0); // ClassCastException at runtime
 }

 public static void main(String[] args) {
  m(new ArrayList<string>());
 }
 
}

 


The new annotation in line 3 does not help to get around the annoying ClassCastException at runtime. Also, it can only be applied to static and final methods. Therefore, I believe it will not be a great help. Future versions of Java will have compile time errors for unsafe code like the one in the example above.

Diamond

In Java 6 it required some patience to create, say, list of maps. Look at this example:

public class DiamondJava7Example {
   public static void main(String[] args) {
      List<Map<Date, String>> listOfMaps = new ArrayList<>(); // type information once!
      HashMap<Date, String> aMap = new HashMap<>(); // type information once!
      aMap.put(new Date(), "Hello");
      listOfMaps.add(aMap);
      System.out.println(listOfMaps);
   }
}

Multicatch

In Java 7 you do not need a catch clause for every single exception, you can catch multiple exceptions in one clause. You remember code like this:

public class HandleExceptionsJava6Example {
 public static void main(String[] args) {
  Class string;
  try {
   string = Class.forName("java.lang.String");
   string.getMethod("length").invoke("test");
  } catch (ClassNotFoundException e) {
   // do something
  } catch (IllegalAccessException e) {
   // do the same !!
  } catch (IllegalArgumentException e) {
   // do the same !!
  } catch (InvocationTargetException e) {
   // yeah, well, again: do the same!
  } catch (NoSuchMethodException e) {
   // ...
  } catch (SecurityException e) {
   // ...
  }
 }
}

Since Java 7 you can write it like this, which makes our lives a lot easier:

public class HandleExceptionsJava7ExampleMultiCatch {
 public static void main(String[] args) {
  try {
   Class string = Class.forName("java.lang.String");
   string.getMethod("length").invoke("test");
  } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
   // do something, and only write it once!!!
  }
 }
}


String in switch statements

Since Java 7 one can use string variables in switch clauses. Here is an example

public class StringInSwitch {
 public void printMonth(String month) {
  switch (month) {
  case "April":
  case "June":
  case "September":
  case "November":
  case "January":
  case "March":
  case "May":
  case "July":
  case "August":
  case "December":
  default:
   System.out.println("done!");
  }
 }
}

Try-with-resource

This feature really helps in terms of reducing unexpected runtime execptions. In Java 7 you can use the so called try-with-resource clause that automatically closes all open resources if an exception occurs. Look at the example:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class TryWithResourceExample {

 public static void main(String[] args) throws FileNotFoundException {
  
  // Java 7 try-with-resource
  
  String file1 = "TryWithResourceFile.out";
  try (OutputStream out = new FileOutputStream(file1)) {
   out.write("Some silly file content ...".getBytes());
   ":-p".charAt(3);
  } catch (StringIndexOutOfBoundsException | IOException e) {
   System.out.println("Exception on operating file " + file1 + ": " + e.getMessage());
  }
  
  // Java 6 style
  
  String file2 = "WithoutTryWithResource.out";
  OutputStream out = new FileOutputStream(file2);
  try {
   out.write("Some silly file content ...".getBytes());
   ":-p".charAt(3);
  } catch (StringIndexOutOfBoundsException | IOException e) {
   System.out.println("Exception on operating file " + file2 + ": " + e.getMessage());
  }

  // Let's try to operate on the resources
  
  File f1 = new File(file1);
  if (f1.delete())
   System.out.println("Successfully deleted: " + file1);
  else
   System.out.println("Problems deleting: " + file1);

  File f2 = new File(file2);
  if (f2.delete())
   System.out.println("Successfully deleted: " + file2);
  else
   System.out.println("Problems deleting: " + file2);
  
 }
}

 In line 14 the try-with-resource clause is used to open a file that we want to operate on. Then line 16 generates a runtime exception. Notice that I do not explicitly close the resource. This is done automatically when you use try-with-resource. It *isn't* when you use the Java 6 equivalent shown in lines 21-30.

The code will write the following result to the console:

Exception on operating file TryWithResourceFile.out: String index out of range: 3
Exception on operating file WithoutTryWithResource.out: String index out of range: 3
Successfully deleted: TryWithResourceFile.out
Problems deleting: WithoutTryWithResource.out

 

That's it in terms of Project Coin. Very useful stuff in my eyes. 

From http://niklasschlimm.blogspot.com/2011/12/java-7-project-coin-in-code-examples.html

Java (programming language) COinS

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • NoSQL vs SQL: What, Where, and How
  • Spring Boot, Quarkus, or Micronaut?
  • mTLS Everywere
  • Introduction to Container Orchestration

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: