How to add Python’s Range to Java


Java HelpIn Python you can use range(5) to iterate through to 5. So you can write for a in range(5): print(a), so we will add some code in Java so that you can write similar which is useful if you are porting code.

import java.util.Iterator;

public class Range implements Iterator<Integer>, Iterable<Integer> {

private int start;

private int end;

private int step;

public Range(int start, int end, int step) {

this.start = start;

this.end = end;

this.step = step;


public Range(int end) {

this(0, end, 1);


public Range(int start, int end) {

this(start, end, 1);



public boolean hasNext() {

if (step > 0) return start < end;

return start > end;



public Integer next() {

int ret = start;

start += step;

return ret;



public Iterator<Integer> iterator() {

return this;



public static void main(String[] args) {

for (int a : new Range(5)) {



There are multiple ways of constructing a range, if one parameter is specified, then it is the end, if two are specified then it is the start and the end, and finally if three are specified then then final parameter is the step. This is done by having multiple constructors which forward to the completely specified constructor with default arguments.

To make it so that we can use it in a loop, it needs to implement an iterator and also be iterable. We implement the methods for integer and rely on automatic unboxing to convert to int.

This has been a simple example of an iterator that replicates a feature in Python, it could be extended to provide a list method which would return an array that is already filled out, a size method that would return the number of elements, and a contains method which would return whether the value is inside the range. Writing utility methods / classes like this can help in porting between programming languages, as you can port the code closely to the original before making changes to make it more idiomatic.

If you want to convert a program from one language to another we have experts in multiple languages, who can provide translation services. One main language pair that is often converted is C to assembly language, but also Python to other programming languages since Python is an ideal prototyping language as it has simpler syntax and faster development.

If you have any Java online help that you require we can deliver it for a reasonable price. No matter if you just want some simple code, a RPN calculator, or a full blown GUI implemented using Swing. Of course you may have an assignment that is not based on Java, and rest assured we can handle that too, from Python to C, or SQL or maybe even Javascript on a website.

At Programming Assignment Experts if you want someone to provide online Java help, just visit our site and submit an assignment for a quote.


Please enter your comment!
Please enter your name here