0

I'm studying CS and am still a Java / programming noob, we've got following code in class and have to explain the problems with the following method and are supposed to optimize it:

public static void printData(int[] list) {
   int i = 0;
   do {
       System.out.println(list[i++]);
   } while (i < list.length);
}

So, my first thought is that it's of course possible to use a do-while loop, but that I would have used a for loop such as:

public static void pd(int[] list) {
    for (int i = 0; i < list.length; i++)
        System.out.println(list[i]);
}

for optimization.

Now, the other method is also possible tho and I cannot figure out the problem with it, maybe that it's not too compatible because of the static declaration, but I'm starting to wrap my head around how to deal with calling non-staticmethods from main, if you have any other advice, I've got open ears.

Jérôme Richard
  • 41,678
  • 6
  • 29
  • 59
Reyth
  • 1
  • 1
  • The two will be as fast because such transformation is trivial to do for the JVM. Such micro optimization is pointless nowodays. Not to mention the IOs operations are far more costly that what you could gain if the JVM what not optimizing your code. You should focus first on the *algorithm*. – Jérôme Richard Apr 16 '21 at 10:06

1 Answers1

0

I will not post code here because it sounds like it is a homework. Anyway I'll give you some hints to work on:

  1. What happens in the method provided "printData" if the length of the input array is 0?
  2. What if the list you're getting as input is null?

About the thing with non-static methods, they can only be called upon the instance on the class and not independently. You can find more in this other question on StackOverflow

Best,

  • It's not homework, just refreshing old material for a new class. Anyway, I think I see: ```printData``` will only work *while* i – Reyth Apr 16 '21 at 12:06
  • I'm sorry, you mentioned a class and made an assumption. Anyway, about the Null stuff. You are taking an input without sanitizing it. It means that, were the list to be null, list.length would throw a NullPointerException. To prevent it you might just add a if (list == null) and if true you quit the method. As a rule of thumb you should always sanitize input so you don't incur in exceptions like NullPointers. – Daniele Vasselli Apr 16 '21 at 12:18
  • ah, I see I also think I made a mistake, the for-loop with evaluate the condition before it runs, so it just doesn't run and throw the exception, right? Why exactly does ```printData```still throw an exception, do while-loops not also evaluate before running? I mean, if ```i !< list.length``` because ```i=0``` and ```list.length```is also zero, why is it still executed? – Reyth Apr 16 '21 at 12:22
  • Not sure, are you talking about the NullPointer or regarding the zero-length array? Not sure I understand the question – Daniele Vasselli Apr 16 '21 at 13:03