Category: Java
Added: 13th of November 2021
Viewed: 2,005 times
Related Tips & Tutorials
➔
How to compile your Java code using the terminal in Linux, Learning Java➔
Install Bluej on Ubuntu, Java Development Environment for beginners➔
Printing to console in Java using the System.out.println command➔
Reading user input and outputting the results to console in Java using Scanner class
Simple for loop in Java. Print the numbers 1 to 10 in the console
What does the code do?
The java code below prints the numbers 1 to 10 in the console / terminal
public class forLoop {
public static void main(String args[]) {
int counter;
for (counter=1; counter<=10; counter++) {
System.out.println(counter);
}
}
}
Create a new file then copy and paste the code above
Save the file as
forLoop.java
Next open the terminal, and enter the following command to compile the file
javac forLoop.java
A new file named
forLoop.class will be created
To execute the code enter the following command
java forLoop
As I'm learning Java, I will try my best to explain what's going on in the code. Getting the terminology right is sometimes harder than the actual coding itself.
To start with we create a new variable. As we are dealing with whole numbers we set variable counter as an integer
int counter
If we want to repeat a specific block of code (x) number of times we use a for loop.
for (start; condition; increment)
We want to print the numbers 1 to 10 in the console. We set the variable counter=1 followed by counter<=10, less than or equal to 10
We also need to add 1 to variable counter after each loop, so we use counter++;.
counter++ is also the same counter=counter+1
We then use System.out.println(counter) to print out the variable
The for loop ends, once the variable int counter reaches 10