Bootstrap FreeKB - Java - Looping over an array
Java - Looping over an array

Updated:   |  Java articles

Here is a basic example of how to create an array in Java and to then loop through the items in the array.

public class Main {
    public static void main(String[] args) {

      String[] fruit = {"apple", "banana", "grapes", "orange"};
								
      for (String item : fruit) {
          System.out.println(item);
      }

   }
}

 

Or, as a bit of a more practical example, let's say you have a Java app that will be exported as a runable JAR. In this example, args can be passed into the main method.

public class Main {
    public static void main(String[] args) {
        for (String server : args) {
            System.out.println(server);
        }
    }
}

 

In Eclipse, you can export the project as a Runable JAR file and then place the JAR file on a Linux system, and use the java command to run the JAR file.

~]# java -classpath my.jar Main server1.example.com
server1.example.com

 

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 134713 in the box below so that we can be sure you are a human.