7 new features of Java 7

Source: Internet
Author: User

1. Language support for collection classes;

2. Automatic resource management;

3. Improved generic instance creation type inference;

4. Digital literal underline support;

Use string in 5.switch;

6. Binary literals;

7. Simplify variable parameter method invocation.

====================== Gorgeous split-line ======================

1. Language support for collection classes

Java will contain first-class language support for the creation of collection classes. This means that the collection class can be created like Ruby and Perl.

What was needed:

1          list<string> List = new arraylist<string> ();
2 List.add ("item");
3 String item = list.get (0);
4
5 set<string> Set = new hashset<string> ();
6 Set.add ("item");
7 map<string, integer> Map = new hashmap<string, integer> ();
8 map.put ("key", 1);
9

Now it's just this: (These collections are immutable ...) )

1          list<string> List = ["Item"];
2 String item = list[0];
3
4 set<string> Set = {"Item"};
5
6 map<string, integer> Map = {"Key": 1};
7

====================== Gorgeous split-line ======================

2. Automatic resource Management

Some resources in Java need to be closed manually, such as Inputstream,writes,sockets,sql classes. This new language feature allows the try statement itself to request additional resources that act on the try block and automatically close.

The previous wording:

1          bufferedreader br = new BufferedReader (new FileReader (path));
2 try {
3 return Br.readline ();
4 } finally {
5 br.close ();
6

Now you can: (a bit like C #)

1          Try (bufferedreader br = new BufferedReader (new FileReader (path)) {
2 return Br.readline ();
3

====================== Gorgeous split-line ======================

3. Improved generic instance creation type inference;

Type inference is a special annoyance, such as the following code:

By type inference becomes:

1 map<string, list<string>> anagrams = new hashmap<> ();

Note: This <> is called the diamond operator, and after Java 7 This operator infers the type from the referenced declaration.

====================== Gorgeous split-line ======================

4. Digital literal underline support

Long numbers are not readable, and in Java 7 You can use underscores to separate the long int from the longer. Such as:

int one_million = 1_000_000;

It's a shame to be like this ... But the readability is good indeed.

====================== Gorgeous split-line ======================

Use string in 5.switch

This is one of the reasons I dislike switch in Java, where I used to use only number or enum in switch. Now you can use a string, Haha, good, praise!

1          String s = ...
2 switch (s) {
3 Case "Quux":
4 Processquux (s);
5 //Fall-through
6 Case "foo":
7 Case "Bar":
8 Processfooorbar (s);
9 Break ;
Ten case "Baz":
Processbaz (s);
/ /Fall-through
Default:
Processdefault (s);
Break ;
16

====================== Gorgeous split-line ======================

6. Binary literals

Because of the C language, Java code traditionally forces programmers to use only decimal, octal, or hexadecimal notation (numbers).

Because few domains are bit-oriented, this limitation can lead to errors. You can now create binary literals using the 0b prefix:

Now you can use this representation of binary literals, and with very short code, you can convert binary characters to data types, such as in byte or shorter.

1 byte abyte = (byte) 0b001;    
2 Short ashort = (short) 0b010;

====================== Gorgeous split-line ======================

7. Simplify variable parameter method invocation.

When a programmer tries to use a mutable parameter that is not materialized and calls a *varargs* (mutable) method, the editor generates a warning that is not safe to operate.
JDK 7 moves the warning from call to the method declaration (Methord declaration) in the process. This allows the API designer to use VARARG because the number of warnings is greatly reduced.

=======================================

JAVA5:
1. Generic type generics:
After referencing generics, it allows you to specify the type of elements in the collection, eliminating coercion of type conversions, and the benefit of type checking at compile time. Parameterized type as a parameter and return value, generic is the cornerstone of vararg, annotation, enumeration, and collection.

A, type safety

Discard list, Map, use list<t>, map<k,v> to add elements to them or use iterator<t> traversal, compile time can give you to check out the type error

B, the method parameter and the return value are added with the type

Discard list, Map, use list<t>, map<k,v>

C, no type conversions required

List<string> list=new arraylist<string> ();

String Str=list.get (i);

D, type wildcard "?"

Assuming a method of printing elements in a list<t> printlist, we want list<t> of any type T to be printed:

Code:

public void Printlist (list<?> list,printstream out) throws ioexception{

For (iterator<?> i=list.iterator (); I.hasnext ();) {

System.out.println (I.next.tostring ());

}

}

What if a wildcard character? To make our parameter types too broad, we can change list<?>, iterator<?> to

list<? Extends number>, iterator<? Extends number> limit it.

2. Enumeration Type enumeration:

3, automatic packing and unpacking (automatic type packaging and unpacking) Autoboxing & unboxing:

Simply put, the type is automatically converted.

Auto-pack: Basic type automatically turns into wrapper class (Int--integer)

Automatic Unpacking: Wrapper classes automatically switch to basic type (Integer--int)

4. Variable parameter varargs (varargs number of arguments)

The same parameter types combine overloaded functions together.

such as: public void Test (object ... objs) {

for (Object Obj:objs) {

System.out.println (obj);

}

}

5. Annotations It is a metadata in Java

A, three predefined standard annotation in tiger

A, Override

Point out that a method covers the methods of superclass when you want to overwrite the spelling of the way name does not compile

B, Deprecated

Indicates that the use of a method or element type is blocked and the subclass will not be able to overwrite it

C, supresswarnings

Turn off compile-time warnings for class, method, field, variable initialization, such as: list does not use Generic, then @suppresswarnings ("unchecked") removes compile-time warnings.

B, custom annotation

Public @interface marked{}

C, Meta-annotation

or annotation's annotation.

All four of the standard meta-annotation are defined in the Java.lang.annotaion package:
A, Target
Specifies which program units the defined annotation can be used on
If target is not specified, it means that the annotation can be used on any program unit
Code
1. @Target ({elementtype.annotation_type,
2. Elementtype.constructor,
3. Elementtype.field,
4. Elementtype.local_variable,
5. Elementtype.method,
6. Elementtype.package,
7. Elementtype.parameter,
8. Elementtype.type})
9. Public @interface TODO {}

B, Retention
Indicates how the Java compilation period treats annotation
Annotation can be discarded at compile time or kept in a compiled class file
When annotation is reserved, it also specifies whether to read the annotation when the JVM loads the class
Code
1. @Retention (retentionpolicy.source)//annotation will be discarded at compile time
2. Public @interface TODO1 {}
3. @Retention (Retentionpolicy.class)//annotation remain in the CLASS file, but are ignored by the JVM
4. Public @interface TODO2 {}
5. @Retention (retentionpolicy.runtime)//annotation remain in the class file and will be read by the JVM
6. Public @interface TODO3 {}


C, documented
Indicates that the defined annotation is considered one of the public APIs of the familiar program unit
Annotation that are labeled by @documented are displayed in Javadoc, which works when the elements that are labeled by the annotation are affected by the client.
D, inherited
The meta-annotation is applied to the annotation type with the target class, and the class labeled by this annotattion automatically inherits the annotation of the parent class.

D, the reflection of the annotation
We found that Java.lang.Class has many methods related to annotation's reflection, such as Getannotations, isannotationpresent
We can use annotation reflection to do many things, such as customizing annotation to do model object validation
Code
1. @Retention (Retentionpolicy.runtime)
2. @Target ({Elementtype.field, elementtype.method})
3. Public @interface Rejectempty {
4./** hint title used in error message */
5. String value () default "";
6.}
7.
8. @Retention (Retentionpolicy.runtime)
9. @Target ({Elementtype.field, elementtype.method})
Public @interface Acceptint {
one. int min () default integer.min_value;
int max () default integer.max_value;
String hint () default "";
14.}
Use @rejectempty and @acceptint to annotate the field of our model and then use reflection to do model validation

6. New iteration statements (for (int n:numbers))

7, static import (import static)

8. New Format method (Java.util.Formatter)

Formatter.format ("Remaining account balance: $%.2f", balance);

9. New threading model and concurrency library thread Framework

Replacement of HashMap Concurrenthashmap and ArrayList copyonwritearraylist
The use of some classes in the Java.util.concurrent package when reading large concurrency will make everyone satisfied blockingqueue, callable, Executor, Semaphore ...

JAVA6:

1, introduced a new framework supporting the scripting engine

2. UI Enhancements

3. Enhancements to WebService support (jax-ws2.0 and JAXB2.0)

4, a series of new security-related enhancements

5, JDBC4.0

6. Compiler API

7, the general annotations support

JAVA7:

You can use a string in 1,switch
String s = "Test";
Switch (s) {
Case "Test":
SYSTEM.OUT.PRINTLN ("test");
Case "Test1":
System.out.println ("Test1");
break;
Default:
System.out.println ("break");
break;
}

2. Use list<string> templist = new arraylist<> (); That is, the generic instantiation type is auto-inferred

3. The collection is syntactically supported, not necessarily an array

Final list<integer> pidigits = [1,2,3,4,5,8];
4. New tools to access environmental information

File System.getjavaiotempdir ()//IO Temp folder

File System.getjavahomedir ()//JRE installation directory

File System.getuserhomedir ()//Current User Directory

File System.getuserdir ()//directory where the Java process was started 5

5.Boolean type reversal, NULL pointer safe, participation bit operation

Boolean Booleans.negate (Boolean booleanobj)

true = False, False = = true, NULL = NULL

Boolean Booleans.and (boolean[] array)

Boolean booleans.or (boolean[] array)

Boolean Booleans.xor (boolean[] array)

Boolean Booleans.and (boolean[] array)

Boolean booleans.or (boolean[] array)

Boolean Booleans.xor (boolean[] array)

6. Equals between two Char
Boolean character.equalsignorecase (char ch1, char CH2)

7. Subtraction of safety
int Math.safetoint (Long value)

int math.safenegate (int value)

Long Math.safesubtract (long value1, int value2)

Long Math.safesubtract (long value1, long value2)

int math.safemultiply (int value1, int value2)

Long math.safemultiply (long value1, int value2)

Long math.safemultiply (long value1, long value2)

Long math.safenegate (Long value)

int math.safeadd (int value1, int value2)

Long Math.safeadd (long value1, int value2)

Long Math.safeadd (long value1, long value2)

int math.safesubtract (int value1, int value2)

The 8.map collection supports concurrent requests and can be written as map map = {name: "xxx", age:18};

7 new features of Java 7

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.