1. New features of Java JDK1.5
1. Generics:
List<String> strs = new ArrayList<String>();//Specify the storage type for the collection. When storing data in the above collection, the data of String must be stored, otherwise the compiler will report an error
2.for-each
For example, we can traverse the above collection through for-each, which makes it easier and clearer
for(String s: strs){System.out.println(s);}Note: When using for-each to traverse a collection, the collection to traverse must implement the Iterator interface
3. Automatic unboxing and packing functions
The code copy is as follows:
What does it mean?
JDK1.5 defines an encapsulation class for each basic data type. Make the basic data types in java also have their own objects, for example: int -->Integer,
double --> Double,
long --> Long,
char --> Character,
float --> Float,
boolean --> boolean,
short --> Short,
byte --> Byte
Automatic packaging: convert basic types into objects, for example: int --> Integer
Automatic unpacking: convert objects into basic data types, for example: Integer --> int
The problem that the collection could not store basic data types before JDK1.5 can now be solved.
4. Enumeration:
Enumeration is a comparative feature introduced by JDK1.5. The keyword is enum
For example: define an enumeration representing a traffic light
public enum MyEnum{ RED,GREEN,YELLOW }5. Variable parameters
What does it mean? Let me give you an example: Before JDK1.5, when we wanted to pass multiple parameters of the same type to a method, we had two methods to solve it, 1. Directly pass an array, 2. Pass as many parameters as there are.
For example:
public void printColor(String red,String green,String yellow){ } or
public void printColor(String[] colors){} Although writing method parameters in this way can achieve the effect we want, isn't this a bit troublesome? Furthermore, what should we do if the number of parameters is uncertain? The variable parameters provided by Java JDK1.5 can perfectly solve this problem, for example:
public void printColor(String... colors){ }
It can be defined like this, what does it mean? If the parameters are of the same type, you can use the form "type + three points, followed by a parameter name". The advantage of this is that as long as the parameter types are the same, there is no limit to the number of parameters passed: the variable parameter must be the last item in the parameter list (this feature applies to both object and basic data types)
6. Static import
Advantages: Using static import can make all static variables and static methods of the imported class directly visible in the current class. Using these static members does not need to give their class names.
Disadvantages: Overuse will reduce the readability of the code
7. Thread concurrency library
Thread concurrency library is an advanced feature of multithreading proposed by Java 1.5. It is located in the package: java.util.concurrent
include
1. Thread mutex tool class description: Lock, RedWriteLock
2. Thread communication description: Condition
3. Thread pool
ExecutorService
3. Synchronize the queue
ArrayBlockingQueue
4. Synchronize collections
ConcurrentHashMap, CopyOnWriteArrayList
5. Thread synchronization tool
Semaphore
There are still many (very important) contents about thread concurrency libraries, so I won't list them one by one here. Interested friends can check out the help documents.
2. New features of JDK1.6
1.Desktop class and SystemTray class
The former can be used to open the system default browser to browse the specified URL, open the system default email client to send emails to the specified email address, use the default application to open or edit files (for example, use notepad to open a file with txt as the suffix), and use the system default printer to print documents; the latter can be used to create a tray program in the system tray area.
2. Use JAXB2 to implement mapping between objects and XML
JAXB is the abbreviation of Java Architecture for XML Binding, which can convert a Java object into XML format and vice versa.
We call the mapping between objects and relational databases ORM, and in fact, the mapping between objects and XML can also be called OXM (Object XML Mapping). It turns out that JAXB is part of Java EE. In JDK1.6, SUN puts it in Java SE, which is also SUN's usual practice. The JAXB version that comes with JDK1.6 is 2.0. Compared with 1.0 (JSR 31), JAXB2 (JSR 222) uses the new JDK5 feature Annotation to identify the classes and attributes to be bound, which greatly simplifies the development workload. In fact, in Java EE 5.0, EJB and Web Services also simplify development through Annotation. In addition, JAXB2 uses StAX (JSR 173) to process XML documents at the bottom.
In addition to JAXB, we can also achieve the same functions through XMLBeans and Castor, etc.
3. Understand StAX
StAX (JSR 173) is another API for processing XML documents in JDK1.6.0 in addition to DOM and SAX.
Origin of StAX: There are two ways to process XML documents in JAXP1.3 (JSR 206): DOM (Document Object Model) and SAX (Simple API for XML).
Since JAXB2 (JSR 222) and JAX-WS 2.0 (JSR 224) in JDK1.6.0 use StAX, Sun decided to add StAX to the JAXP family and upgrade the JAXP version to 1.4 (JAXP1.4 is the maintenance version of JAXP1.3). The JAXP version in JDK1.6 is 1.4. StAX is The Streaming API for The abbreviation of XML, an API that uses pull-parsing XML documents. StAX provides an API based on an event iterator to let programmers control the parsing process of xml document. The program traverses this event iterator to process each parsing event. The parsing event can be regarded as being pulled out by the program, that is, the program prompts the parser to generate a parsing event and then handles the event, and then causes the parser to generate the next parsing event. This loops until the document ending character is encountered. SAX also processes xml documents based on events, but uses push mode to parsing. After the parser parses the complete xml document, it only generates parsing events, and then pushes them to the program to process these events. The DOM adopts the method to map the entire xml document to a memory tree, so that the data of the parent node, child node and brother nodes can be easily obtained, but if the document is large, it will seriously affect performance.
4. Use Compiler API
Now we can use the Compiler API of JDK1.6 (JSR 199) to dynamically compile Java source files. The Compiler API combines reflection function to achieve dynamic generation of Java code and compile and execute these codes, which is a bit of a dynamic language feature.
This feature is very useful for some applications that require dynamic compilation, such as JSP Web Server. When we manually modify JSP, we do not want to restart the Web Server to see the effect. At this time, we can use the Compiler API to implement dynamic compilation of JSP files. Of course, the current JSP Web Server also supports JSP hot deployment. The current JSP Web Server calls javac through Runtime.exec or ProcessBuilder to compile code during operation. This method requires us to generate another process to do compilation, which is not elegant enough and is easy to make the code depend on a specific operating system. The Compiler API provides a richer way to do dynamic compilation through a set of easy-to-use standard APIs, and it is cross-platform.
5. Lightweight Http Server API
JDK1.6 provides a simple Http Server API. According to this, we can build our own embedded Http Server, which supports the Http and Https protocols and provides part of the implementation of HTTP1.1. The part that is not implemented can be implemented by extending the existing Http Server API. Programmers must implement the HttpHandler interface by themselves. HttpServer will call the callback method of the HttpHandler implementation class to handle client requests. Here, we call an Http request and its response an exchange, which is wrapped into an HttpExchange class. HttpServer is responsible for passing HttpExchange to the callback method of the HttpHandler implementation class.
6. Pluggable Annotation Processing API (Pluggable Annotation Processing API)
The plug-in annotation processing API (JSR 269) provides a standard API to handle Annotations (JSR 175)
In fact, JSR 269 is not only used to deal with Annotation. I think the more powerful function is that it establishes a model of the Java language itself. It maps Java language elements such as method, package, constructor, type, variable, enum, annotation into Types and Elements (what is the difference between the two?), thereby mapping the semantics of the Java language into objects. We can see these classes under the javax.lang.model package. So we can use the API provided by JSR 269 to build a feature-rich metaprogramming environment. JSR 269 uses Annotation Processor to process Annotation during compilation rather than during operation. Annotation Processor is equivalent to a plug-in of the compiler, so it is called insertion annotation processing. If new Java code is generated when Annotation Processor processes Annotation (executing the process method), the compiler will call Annotation Processor again. If new code is generated for the second processing, it will then call Annotation Processor until no new code is generated. Each time the process() method is executed, it is called a "round", so that the entire Annotation processing process can be regarded as a round sequence.
JSR 269 is mainly designed as an API for Tools or containers. For example, we want to establish an Annotation-based unit testing framework (such as TestNG) to use Annotation to identify the test methods that need to be executed during the test.
7. Use Console to develop console programs
JDK1.6 provides the java.io.Console class specifically used to access character-based console devices. If your program wants to interact with cmd under Windows or Terminal under Linux, you can use the Console class to do it. But we don't always get the available Console, whether a JVM has available Console depends on the underlying platform and how the JVM is called. If the JVM is started on an interactive command line (such as Windows cmd) and the input and output are not redirected elsewhere, then you can get an available Console instance.
8. Support for scripting languages
Such as: ruby, groovy, javascript.
9.Common Annotations
Common annotations were originally part of the Java EE 5.0 (JSR 244) specification, and now SUN puts part of it in Java SE 6.0.
With the addition of Annotation metadata function (JSR 175) to Java SE 5.0, many Java technologies (such as EJB and Web Services) will use Annotation part to replace XML files to configure running parameters (or support declarative programming, such as EJB's declarative transactions). If these technologies define their own otations separately for general purposes, it is obviously a bit duplicate construction. Therefore, it is valuable to define a set of public Annotation for other related Java technologies. It can avoid duplicate construction while also ensuring the consistency of various technologies of Java SE and Java EE.
The following lists 10 Annotations Common Annotations Annotation Retention Target Description Generated SourceANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE. The source code generated by the annotation is used to label the resource generated. The container injects external resource dependencies according to this. There are two methods: field-based injection and setter-based injection. Resources Runtime. TYPE labels multiple external dependencies at the same time. The container will inject all these external dependencies into PostConstructRuntime METHOD. The method runs after the container injects all dependencies to perform initialization work after dependency injection. Only one method can be labeled PostConstruct PreDestroy Runtime METHOD. Before the object instance is about to be deleted from the container, the callback method to be executed must be labeled as PreDestroy RunAs Runtime TYPE is used to label what security role to execute the method of the labeled class. This security role must be consistent with the Security role of the Container. RolesAllowed Runtime TYPE, METHOD is used to label security roles that allow the execution of labeled classes or methods. This security role must be consistent with the Container Security role. METHOD allows all roles to execute labeled classes or methods. DenyAll Runtime TYPE. METHOD does not allow any role to execute labeled classes or methods, indicating that the class or methods cannot run in the Java EE container. DeclareRoles Runtime TYPE is used to define security roles that can be tested by the application. It is usually used to use isUserInRole to verify security roles.
Notice:
1. RolesAllowed, PermitAll, and DenyAll cannot be applied to a class or method's RolesAllowed, PermitAll, and DenyAll labeled on the class will overwrite RolesAllowed, PermitAll, DenyAllRunAs, RolesAllowed, PermitAll, DenyAll and DeclareRoles not added to Java SE 6.0 to handle the above Annotations work is done by the Java EE container. Java SE6.0 only contains the definition classes of the first five Annotations in the above table, and does not contain the engine for handling these Annotations. This work can be done by the Pluggable Annotation Processing API (JSR 269).
Compared with the new features of 1.6, the new features of 1.7 make us more excited because it is something we have been looking forward to and visible and tangible.
3. New features of JDK1.7
1. Binary face value
In Java7, the value of the type of shaping (byte, short, int, long) can be represented by binary types. When using binary values, ob or oB need to be added in front of it, for example:
int a =0b01111_00000_11111_00000_10101_01010_10; short b = (short)0b01100_00000_11111_0; byte c = (byte)0B00000_0001;
2. Support of digital variables for sliding lines
JDK1.7 can add a slide line to a variable of numeric type.
But there are a few places that cannot be added
1. The beginning and end of the number
2. Before and after the decimal point
3. Before F or L, for example:
int num = 1234_5678_9;
float num2 = 222_33F;
long num3 = 123_000_111L;
3. Switch's support for String
Have you always had a question mark before? Why is C# available in Java but not? Ha, but Java is also OK after JDK1.7, for example:
String status = "orderState"; switch (status) { case "ordercancel": System.out.println("Order cancellation"); break; case "orderSuccess": System.out.println("Subscription successful"); break; default: System.out.println("Status unknown"); }4.try-with-resource
try-with-resources is a try declaration that defines one or more resources. This resource refers to the object that the program needs to close after it has processed. try-with-resources Ensure that every resource is closed after processing is completed.
Resources that can use try-with-resources are:
Any object that implements the java.lang.AutoCloseable interface java.io.Closeable interface.
For example:
public static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } }
In Java 7 and later versions, BufferedReader implements the java.lang.AutoCloseable interface.
Since the BufferedReader is defined in the try-with-resources declaration, it will automatically be turned off regardless of whether the try statement is normal or abnormal. Before Java7, you need to use finally blocks to close this object.
5. Catch multiple exceptions and re-throw the exception with improved type checking
For example:
public static void first(){ try { BufferedReader reader = new BufferedReader(new FileReader("")); Connection con = null; Statement stmt = con.createStatement(); } catch (IOException | SQLException e) { //Catch multiple exceptions, e is the final type e.printStackTrace(); } }Advantages: Using one catch to handle multiple exceptions is smaller and more efficient than using multiple catches to handle one exception to the bytecode generated by processing one exception.
6. Type inference when creating generics
As long as the compiler can infer type parameters from the context, you can replace generic parameters with a pair of empty angle brackets <>. This pair of brackets is privately called diamonds. Before Java SE 7, you should do this when declaring a generic object
List<String> list = new ArrayList<String>();
And after Java SE7, you can do this
List<String> list = new ArrayList<>();
Because the compiler can infer type parameters from the previous (List), you can no longer write generic parameters after the subsequent ArrayList, just use a pair of empty angle brackets. Of course, you must carry a "diamond"<>, otherwise there will be a warning.
Java SE7 only supports limited type inference: You can only use type inference if the constructor's parameterized type is significantly declared in the context, otherwise it will not work.
List<String> list = new ArrayList<>(); list.add("A"); //This does not work list.addAll(new ArrayList<>()); //This can be List<? extends String> list2 = new ArrayList<>(); list.addAll(list2);
7. (None)
8. Add some new tools and methods to obtain environmental information
For example:
File System.getUserHomeDir() // Current user directory File System.getUserDir() // Directory where you are when starting the java process 5 File System.getJavaIoTempDir() // IO temporary folder File System.getJavaHomeDir() // JRE installation directory
9. Safe addition, subtraction, multiplication and division
For example:
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)
Well, so much has been sorted out so far. I will add it later.
It should be noted that if you are not sure about your previous jdk version, don't use new features, otherwise there may be problems of this or that.