Welcome to Java7 Quick tour
Hi,
While browsing some information about Java 7, I came across a very nice blog covering few major changes in Java 7. Would like to share with all my blog users. Here it goes..
The first example will show switch with String, previously this functionality was only possible with Enums and integer values. In actual fact the JDK retrieves the hashcode for the String which is an integer. Below is an example of this feature.
|
String drink=”coffee”;
switch (drink){
case “coffee”:
System.out.println(“So you need milk”);
break;
case “juice”:
System.out.println(“So you need sugar”);
break;
case “refrigerate”:
System.out.println(“So you need ice”);
break;
default:
System.out.println(“unknown drink “);
break;
}
|
I will now show you the ARM, Automatic Resource management, you don’t need to concern yourself with the resources that will be used in your program because it will automatically close when it exits the Try block. For this just implement the interface java.lang.AutoCloseable, the only method is the Close, The AutoCloseable is the better option than Closeable because an exception is not thrown when you close the resource, in the second picture we can see this.
|
public void copyFile(File original, File copy) throws FileNotFoundException, IOException {
try (
InputStream in = new FileInputStream(original);
OutputStream out = new FileOutputStream(copy)) {
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}// it is automatically close
}
|
The multi-try, for some people is the most important feature in this version, it now allows many exceptions inside the catch block just separate with a “|” pipe.
|
ExemploARM arm=new ExemploARM();
try {
arm.copyFile(origem, destino);
} catch (FileNotFoundException | IOException ex) {
ex.printStackTrace();
System.out.println(“It’s can’t copy file”);
}
|
using multy-try
In Java 7 there are some improvements to Generics and collections making it easy to make this type Object. Now it is possible to make generic collections easily with the diamond operator “<>”
|
List<Object> diamond=new ArrayList<>(); // diamond
List<Drink> Drinks;
Map<String, List<Drink>> maps=new HashMap<>();
maps.put(“diamond”, drinks=new ArrayList<>() );
maps.put(“other example”, new ArrayList<Bebida>() );
maps.put(“erro”, new ArrayList<>() );
[/code] Picture 4: diamond
|
Talking more about generic collections there is the annotation @SafeVarargs for ensuring this method is safe.
Applying this annotation to a method or constructor suppresses unchecked warnings about a non-reifiable variable-arity (vararg) type and suppresses unchecked warnings about parameterized array creation at call sites.
|
@SafeVarargs
static List asList (T… elements) {
System.out.println(elements);
return null;
}
@SafeVarargs
static void varags(List… stringLists) {
Object[] array = stringLists;
List tmpList = Arrays.asList(42);
array[0] = tmpList; //run with warning
String s = stringLists[0].get(0); // ClassCastException
}
|
@SafeVarargs
The digit separator allows for good understand when writing big numbers in java code, the only rule is you can’t separate the last and the first number, now you can write separator numbers with the character “_” it is also possible to write Double values and Float values, for example, for the JDK is equals 22 and 2_2. There is also literal in binary, which is most important when programming in embedding devices, just put “ob” (zero and b) in front of a number, this Features can also use the separator.
|
long longPrimitive=9_999_999_99;
Long longObjete=9__3234_300l;
double doublePrimitive=232_32.32_12d;
Double doubleObjeto=88_32.32_12d;
int binA=0b01_01;
int binB=0b0101_0111;
if(2222==22_22){
System.out.println(“equals values”);
}
if(binA==5){
System.out.println(“equals binary values”);
}
|
picture 5: using separator and literal binary.
Other feature interesting is try with resource now it possible instantiate one variable if it does not generate an exception.
|
BufferedWriter writer=null;
try {
writer = Files.newBufferedWriter(arquivo, charset);
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format(“IOException: %s%n”, x);
}
|
Picture 6: before was necessary create the variable
|
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format(“IOException: %s%n”, x);
}
|
Picture 7: after using try with resource in java 7
Some more features..
- The new java.util.Objects class provides some nice static convenience methods as described in my blog post JDK 7: The New Objects Class.
- Three new convenience methods have been added to the already useful Collections class:Collections.emptyIterator(), Collections.emptyListIterator(), andCollections.emptyEnumeration().
- New static methods for comparing primitives [similar to the already existingDouble.compare(double,double) and Float.compare(float,float)] are now available for additional numeric/boolean types: Byte.compare(byte, byte), Integer.compare(int,int),Long.compare(long,long), Short.compare(short,short), andBoolean.compare(boolean,boolean).
- Calendar gets some Java 7 attention (even if it’s not the overhaul many of us had hoped for): Calendar.isWeekDateSupported(), Calendar.getWeekYear(),Calendar.setWeekDate(int,int,int), and Calendar.getWeeksInWeekYear(). TheTimeZone.observesDaylightTime() method has also been added. The implementation of this interface that most of us use, GregorianCalendar, has these methods implemented now.
- There are several changes related to Java reflection:
- The java.lang.reflect.Modifier class has new static methods: classModifiers(),interfaceModifiers(), constructorModifiers(), methodModifiers(), andfieldModifiers().
- I have written a more detailed blog post on the new ReflectionOperationExceptionclass.
- ConcurrentLinkedDeque and LinkedTransferQueue are now available.
- The java.util.ConcurrentModificationException has two new constructors that each accept acause and one of them accepts a detailed message as well.
- The java.net.ProtocolFamily interface is new as is the enum StandardProtocolFamily that implements this interface.
- The class InetAddress has a new method called getLoopbackAddress(). The methodInetAddress.isLoopbackAddress() has been available since JDK 1.4.
- ProcessBuilder gets a new nested class called Redirect, which itself contains a nested Typeenum.
- The Character class now contains a nested UnicodeScript enum.
- BitSet.valueOf(long[])
- Multiple JDBC enhancements:
- The Statement interface prescribes two new methods: closeOnCompletion() andisCloseOnCompletion().
- The java.sql.DatabaseMetaData interface has two new methods:getPseudoColumns() and generatedKeyAlwaysReturned().
- JDBC’s CallableStatement gets two new overloaded getObject() methods that get an object based on provided name or index along with the expected object’s class type.
- The Driver class got a new method Driver.getParentLogger() that returns ajava.util.logging.Logger. CommonDataSource gets the same new method.
- File.toPath() provides a java.nio.file.Path.
- There are several new classes and interfaces related to security:
- The new java.security.AlgorithmConstraints interface “specifies constraints for cryptographic algorithms, keys (key sizes), and other algorithm parameters.”
- The new CertificateRevokedException ”indicates an X.509 certificate is revoked.”
- CertPathValidatorException got a new constructor that accepts an implementation of the new nested CertPathValidatorException.Reason interface as a parameter and there is a method to get this reason. The newCertPathValidatorException.BasicReason enum implements theCertPathValidatorException.Reason interface and “enumerates the potential reasons that a certification path of any type may be invalid.”
- The new invokedynamic feature requires new support:
- The new java.dyn.InvokeDynamicBootstrapError is thrown “to indicate that aninvokedynamic instruction” has had some sort of problem (not found or other problem). The MethodHandle class and related functionality are further described in A glimpse at MethodHandle and its usage.
- There is a new reflection exception called WrongMethodTypeException.
- Two new methods have been added to Throwable to support the new try-with-resourcesfeature: addSuppressed(Throwable) and getSuppressed(). Because both Exception andError extend
Throwable, all exceptions and errors can support providing the suppressed exceptions as appropriate. - AssertionError has a new constructor accepting a cause.
- Numerous Swing/AWT-related changes.
- Numerous NIO-related changes (NIO.2).
- Applet even gets something in Java 7: Applet.isValidateRoot().
- New JMX features include the PlatformManagedObject interface and theManagementFactory.getAllPlatformMXBeanInterfaces() method, both of which I discussed in my blog post JDK 7 JMX Platform Management Beans: A First Peek.
- There are numerous new concurrency support constructs coming to JDK 7 above and beyond some I highlighted above.
- The Locale class documentation mentions “1.7″ sixteen times! The 1.7 changes to the class are called out in the class’s main description. One significant method is toLanguageTag()that provides “a well-formed IETF BCP 47 language tag representing this locale.” The static method forLanguageTag(String) provides an instance of Locale corresponding to the provided String representing the “specified IETF BCP 47 language tag.” The very extensive documentation for this method points out an important caveat: “there is no guarantee that toLanguageTag and forLanguageTag will round-trip.” The Java Tutorials’ Creating a Localeis already updated to reflect using Java 7 features of this class. Among other things, it highlights the new nested Locale.Builder class and the new nested Locale.Category enum.
[Source]
http://weblogs.java.net/blog/otaviojava/archive/2011/08/21/welcome-java-7-part-2-jsr-334-coin-0
http://marxsoftware.blogspot.com/2011/03/jdk-7-new-interfaces-classes-enums-and.html
–
Thanks
R Vashi
Categories: Core Java
Welcome to Java7 Quick tour
Recent Comments