Java Enhanced for loop

Source: Internet
Author: User

Java enhanced for Loop

Java5 introduces an enhanced for loop that is primarily used for arrays .

The Java enhanced for loop syntax format is as follows :

( in simple terms, the elements in the array are sequentially output )

for ( declaration statement : expression )

{

code sentences

}

declaration statement: declares a new local variable that must have a type that matches the type of the array element. Its scope is scoped to the Loop statement block, whose value is equal to the value of the array element at this time.

expression : The expression is the name of the array to access, or is the method that returns the value to the group.

Instance:

Public class Test1 {

Public Static void Main (string[] args) {

int [] numbers={10,20,30,40,50};// defines an array

for (int x:numbers) {// enhanced for Loop, which sequentially outputs the elements in the array

System. out. Print (x);

System. out. Print (",");

}

System. out. Print ("\ n");

String[] names={"James", "Larry", "Tom", "Lacy"};// definition array

for (String name:names) {// enhanced for Loop, which sequentially outputs the elements in the array

System. out. Print (name);

System. out. Print (",");

}

}

}

Java Enhanced for loop

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.