DEV Community

Discussion on: Learning Algorithms with JS, Python and Java 9: Printing Steps

Collapse
 
arminaskatilius profile image
Arminas Katilius • Edited

Actually for these kind of tasks, you could mostly used same code as for Java as in Javascript :) Not complaining, but there are a lot of outdated examples on the internet.
For example, there is no need to use String builder, string concetanation works fine. Also Java has ternary operator. And if you would use Java 10, it has var keyword that allows almost copy Javascript sample you were using.

Collapse
 
tommy3 profile image
tommy-3

Thanks for the comment.

I know I can do without StringBuilders, but I make it a rule to use them for performance.

Using the iterative Java code above, it took 14 seconds when the parameter is 10000.

With this code:

static void stepsWithoutStringBuilder(int n) {
    for (int row = 0; row < n; row++) {
        String stair = "";
        for (int column = 0; column < n; column++) {
            if (column <= row) {
                stair += "#";
            } else {
                stair += " ";
            }
        }
        System.out.println(stair);
    }
}

it took 243 seconds for 10,000 steps!

I've always used Java 8 and I like Java for its strong typing, so I'm surprised to learn about the "var" in Java 10. I'm not sure if I'll like it or not, but anyway thank you for the information!