function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Heiner GoehlmannHeiner Goehlmann 

system.debug in for loop: does it work only on very last loop?

Hello Dev Community,

within "Developer Trail - Beginner" Module "Apex Basics & Database" I have started step "Getting Started with Apex".
From topic "Apex Collections: List" I try to execute some commands of that example as static method. This is the coding of my very first apex program:

User-added image

Now I am stuck with this: only the last System.debug statement for color "blue" is executed:
User-added image

May I ask for some help, please:
How (if ever) can I get all 3 colors shown in debug log?
How should I code this program more professionally?
Best Answer chosen by Heiner Goehlmann
pconpcon
It is odd that you are only getting one, however you would be getting at most two anyways.  Since you are going from 0 - 1 since you minus'd the size of the array (3) and are using less than instead of less than or equals.  If you want to debug this more, I would add a System.debug of i out before writing out your color.

I would say that I would rewrite this method as follows:
 
public static void buildList() {
    List<String> colors = new List<String>{
        'red',
        'green',
        'blue'
    };

    for (Integer i = 0; i < colors.size(); i++) {
        System.debug(colors.get(i));
    }
}

or even better
 
public static void buildList() {
    List<String> colors = new List<String>{
        'red',
        'green',
        'blue'
    };

    for (String color : colors) {
        System.debug(color);
    }
}

All Answers

pconpcon
It is odd that you are only getting one, however you would be getting at most two anyways.  Since you are going from 0 - 1 since you minus'd the size of the array (3) and are using less than instead of less than or equals.  If you want to debug this more, I would add a System.debug of i out before writing out your color.

I would say that I would rewrite this method as follows:
 
public static void buildList() {
    List<String> colors = new List<String>{
        'red',
        'green',
        'blue'
    };

    for (Integer i = 0; i < colors.size(); i++) {
        System.debug(colors.get(i));
    }
}

or even better
 
public static void buildList() {
    List<String> colors = new List<String>{
        'red',
        'green',
        'blue'
    };

    for (String color : colors) {
        System.debug(color);
    }
}
This was selected as the best answer
Heiner GoehlmannHeiner Goehlmann
Hi pcon,

thank you for your help. This was exactly what I was waiting for. It has helped me to develop some understanding for Apex.