Java Beginner: For Each loop

Source: Internet
Author: User

We've already done the basic operation of the array, and now we're going to talk about the for every loop in Java, and remember when I said for the for loop that there was a for every loop, but it wasn't detailed at the time because the For Each loop was for the array.

The For Each loop is a loop that Java Ritter has to access the elements in the array. Unlike the normal for loop access array, the For Each loop does not require an subscript operation. The format for Each loop is as follows:

For (the element type in the array you give a name: array name) {action}

Let's give an example ..., forget it, I'm lazy, just use the last example:

Let's take a look at the last for loop of this program, this is for Each loop, here the element is my own name, the reader can be changed to another name, but note, it is best not to use strange names, such as keywords, do not use the name of the array itself, do not use, wrong naming, do not use.

For Each loop is simple, but there are many limitations, for example, we cannot easily get the subscript of an element, although we can, as shown:

But this is not very convenient, and if we want to manipulate the elements in the array, such as exchanging two elements of an array, or sort of, it would be awkward to use for Each loop. Moreover, the novice vaguely feel that some purposes, for each is not done, but the ordinary for loop is done.

Finally, although the operation of string in Java is somewhat like an array, but the string object is not an array, it is not possible to use the For Each loop to access the string character directly. Unless you first use the Split method to convert a string object to an array of string, this is not the preferred way to access a string object.

Java Beginner: For Each loop

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.