Python and Java are two of technology’s biggest programming languages, used by millions every day. With these instructions, any level of Python users can begin to apply their skills to Java, learn how to apply their existing code to situations written in other languages, and learn about the structure and meaning of code and loops. In this example, we will take a simple Python for loop through a set range of numbers and guide you through the process of converting it to its Java equivalent. By the end, you will have a functioning Java loop that can run in a Java IDE! Here are some easy steps to jumpstart your journey to learn Java:
You will need:
- A simple text editor to work in while editing your code
- Simple Python for loop code (or follow along with our example code)
- If you would like to test that your code runs, an IDE (Integrated Development Environment, or a space to write and run your code) that runs Java. Some examples are Eclipse, BlueJ, and NetBeans, which are each free and safe to download through the Internet. Warning: do not download any unknown IDE- it may cause damage to your computer!
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Open an empty text file.
Copy in or write a Python for loop. In this example, we are looping through the numbers 1 through 4 (with 5 as our cutoff value) and printing each number.
Add semicolons to the end of all the lines in the loop’s body.
Remove the colon at end of for loop declaration.
Put a beginning bracket where the semicolon used to be (after the loop declaration).
Put an ending bracket at the end of the loop’s body, on the first empty line.
Remove all text between “for i” and beginning bracket, highlighted in image above.
Change “i” to “int i = ?;”, replacing ? with the beginning number of your desired range.
Add “i < ?;”, replacing ? with the cutoff value (not included) of your desired range.
Add “i++” to the end of the loop declaration.
Enclose the loop declaration (everything after for and before bracket) in parentheses.
Convert statements in the loop’s body to Java. In this case, change “print” to “System.out.println”.