Dark Horse programmer------jdk1.5 new features in Java

Source: Internet
Author: User

Java Training, Android training, iOS training,. NET training, look forward to communicating with you!

JDK1.5 new Features:

Why new features are present:

New technologies are emerging to address old problems, and the Java language improves developer productivity by improving the technology that has previously been detrimental to productivity.

Static import:

  static import: You can import static methods under a class, and after static import, you can use static methods under this class without writing the class name.

  syntax:import static package name. Class name. static method

code example:

 PackageCom.itheima.day1;/*** Static Import *@authorAdministrator*/Import Staticjava.lang.math.*;//static import of all static methods under the Math classImport Staticjava.lang.system.*; Public classStaticimportdemo {/**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method StubOUT.PRINTLN (Max (1, 6)); OUT.PRINTLN (ABS (3-7)); }}

  Benefits: simplifies code writing by simplifying calls to static properties and methods in a class.

  Cons: If you define a method in your program that has the same name as a static method that is statically imported, the JVM will not understand which one to use, so it is generally not recommended to import statically.

Variable parameters:

The variable parameter appears to solve the problem that a method can accept an indeterminate number of arguments.

For example:

        System.out.println (Add (2,3));        System.out.println (Add (2,3,5));

If you use method overloading to solve, you need to write multiple overloaded methods, you need to accept the number of parameters to change once, you must write another overloaded method, resulting in complex code, using variable parameters, you can avoid this situation.

  Example:

 Public classVariableparametertest { Public Static voidMain (string[] args) {//TODO auto-generated Method StubSystem.out.println (Add (2,3)); System.out.println (Add (2,3,5)); }         Public Static intAddintXint.. args) {        intsum =x;  for(inti=0;i<args.length;i++) {sum= sum+Args[i]; }        returnsum; }}

  The principle of variable parameters:

When you call a method of a mutable parameter, the compiler automatically creates an array to hold the mutable arguments passed to the method.

  Variable parameter characteristics and precautions:

1, the variable parameter can only appear once and can only appear at the end of the parameter list

2. When invoking a variable parameter method, the compiler automatically creates an array to accept the mutable arguments passed in.

3. Variable parameter format: parameter type ... Parameter name, and there are no spaces before and after the ellipsis.

Enhanced for Loop:

  Reasons for introducing an enhanced for loop:

Before the 1.5 version, iterating over the elements in an array or collection requires first getting the length of the array or the iterator of the collection, which is cumbersome.

Because of the addition of a new syntax in version 1.5: Enhanced for loop.

  Syntax format:  

For (modifier variable type variable: Array or collection to iterate over) {}

  code example: 

/*** Java1.5 new feature: Enhanced for loop *@authorAdministrator*/ Public classEnhanceforloop { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        int[] arr =New int[]{3,4,5,6,6,7,4,6,9};  for(intX:arr)        {System.out.println (x); }    }}

Automatic packing and unpacking: 

  Automatic Boxing: The syntax of JDK 1.5 allows developers to assign a basic data type directly to the corresponding wrapper class variable, or to a variable of type Object, which is called automatic boxing.

  Automatic unpacking: automatic unpacking and automatic boxing in contrast, the wrapper class object is assigned directly to a corresponding basic type variable.

  code example:

/*** Java1.5 new features: Automatic packing and unpacking *@authorAdministrator*/ Public classAutobox {/**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method StubInteger i = 3;//Automatic Boxing        intx = i;//Automatic UnpackingSystem.out.println (i+3);//Automatic box packing and unpackingInteger I1= 23; Integer I2= 23; System.out.println ("I1==i2?:" + (i1==i2)); Integer i3= 128; Integer I4= 128; System.out.println ("I3==i4?:" + (i3==I4));     }}

  Program results:

6 i1==i2?:true  i3==i4?:false

It can be seen that I1==i2 and i3==i4 print the same result.

  The reason is because of the byte constant pool.

  BYTE constant pool:

For an integer of these basic data types to be set as an integer object, if this number is a number within 1 bytes ( -128~127), it is deferred to the byte constant pool, and the next time a basic data type integer is wrapped, if this is also within 1 bytes, Then go to this constant pool to find, if found, directly to use, so as to save the memory space, if not, then create a cache pool for the next use.

This is a design pattern: Enjoy meta mode (flyweight)

Enjoy meta mode:

is a lot of small objects, they have many of the same attributes, they are encapsulated into an object, their different properties into the object method of the parameters, called the object's external state; those who have the same properties are called the internal state of the object.

For example, the integer object in the example, an integer object in the -128~127 range, is used more frequently as the same object, so the result is true. Beyond this range is not the same object, so the result is false.

  Enjoy meta-mode applications:

1. The English alphabet in Word.

Each object value is in a different location (coordinate), so an object can be used to call the location of the method.

For example, the letter q:q.zuobiao (int x,int y) is used to encapsulate the letter Q of a highly reusable char type into an object.

2, Icon: window under the folder icon, but the name of this property is different, contains a lot of other same attributes, then you can apply the enjoy meta-mode.

Enumeration:

  Why do I need enumerations?

When an object is initialized, the value it can initialize cannot be arbitrary, but only a value within a limited selection range. such as the day of the week, this number can not be arbitrarily selected, there must be a selection range.

This type of problem can only be resolved with a custom class with enumerations before JDK1.5, and after 1.5, the enumeration is resolved.

After the JDK1.5, a new keyword, enum, is used to define an enumeration class.

  The custom class implements the enumeration function:

1, the need to privatize the construction method.

2. Each member variable is the object of this custom class and is to be publicly and statically decorated.

3. You can customize public non-abstract methods or abstract methods.

  code example:

/** Using a common class simulation enumeration *: Week of the week (for simplification, one week is assumed to be two days)*/ Public classWeekDay1 {PrivateWeekDay1 () {} Public Final StaticWeekDay1 SUN =NewWeekDay1 ();  Public Final StaticWeekDay1 MON =NewWeekDay1 ();  PublicWeekDay NextDay () {if( This= = SUN)returnMON; Else returnSUN; }
PublicString toString () {return This==sun? " SUN ": MON"; }}

In the example above, you can also define NextDay () with an abstract method If...else ... The statement is transferred to a separate object to be implemented.

code example:

/** Use a generic class to simulate enumerations *: Week of the week (for simplification, one week for two days, the other is the same)*/ Public Abstract classWeekDay1 {PrivateWeekDay1 () {} Public Final StaticWeekDay1 SUN =NewWeekDay1 () { PublicWeekDay1 NextDay () {returnMON;    }    };  Public Final StaticWeekDay1 MON =NewWeekDay1 () { PublicWeekDay1 NextDay () {returnSUN;        }    }; /*Public WeekDay NextDay () {if (this = = SUN) return MON;    else return SUN; }*/         Public AbstractWeekDay1 nextday ();  PublicString toString () {return  This==sun? " SUN ": MON"; }}

  Definition of the enumeration: 

code example:

     Public enum weekday{        SUN, mon,tue,wed, Thi,fri,sat;     }

The enumeration class declared in Java is a subclass of Java.lang.Enum, which inherits all the methods in the enum class.

Common methods:

Name ();

Ordinal ();

ValueOf (String name);

VALUES ():

code example:

 Public classEnumtest { Public Static voidMain (string[] args) {WeekDay Day=Weekday.fri; System.out.println ("Day:" +Day ); System.out.println ("Day.name:" +day.name ()); System.out.println ("Day.ordinal:" +day.ordinal ()); WeekDay Day2= Weekday.valueof ("SUN"); System.out.println ("Day2:" +day2); Weekday[] days=weekday.values ();  for(WeekDay day3:days) {System.out.println (DAY3); }    }
}

Implement an enumeration example with a constructor method and an abstract method:

 Public  enumtrafficlamp{GREEN (60) {@Override PublicTrafficlamp Nextlamp () {//TODO auto-generated Method Stub                returnYELLOW; }}, RED (30) {@Override PublicTrafficlamp Nextlamp () {//TODO auto-generated Method Stub                returnGREEN; }}, YELLOW (5) {@Override PublicTrafficlamp Nextlamp () {//TODO auto-generated Method Stub                returnRED;        }        }; Private intTime ; PrivateTrafficlamp (intTime) { This. time=Time ;}  Public AbstractTrafficlamp Nextlamp (); }

 Enumeration Class Summary:

   1, the enumeration class is a special form of Java class.

2. Each enumerated value declared in an enumeration class represents a sample object of this enumeration class.

3. In an enumeration class, you can declare properties, methods, and construction methods. However, the constructor method of the enumeration class must be private decorated.

4. Enumeration classes can also implement interfaces, inheriting abstract classes.

5. When there is only one enumeration value in the enumeration class, it can be used as a singleton pattern.

6. When the enumeration class is loaded, all the enumeration values in the enumeration class are also loaded.

After version 7 and 1.5, the Enum class object can be accepted by the switch statement.

    

  

  

Dark Horse programmer------jdk1.5 new features in Java

Related Article

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.