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
SubbuSubbu 

can't have statements like that directly inside a class. Please keep only field declarations inside class and all the other statements inside a method in class. Also the field intitalisations should be inside a constructor.

If  I am writhing the code directly in side the class , getting errors like Right curly brace({) and unexpected token error . Same code when i am writing in side the method i did not get any Error , my code is working fine ,Could you please let me know what is the technical thing here...like oops concept , please i am new for the APEX coding , should not hesitate .
Agustina GarciaAgustina Garcia
Hi,

One of the first rules that you need to keep in mind in Apex is that in a class you can only declare variables, methods or inner classes, but you cannot create for instance a forloop directly in the class, it must be inside a method. In a similar way, if you declare an inner class, a forloop should be also inside of a method. This link (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_HelloWorld.htm) give you some guides about how to start.
 
//Below code gives you errors at comiple time
public class MyFirstClass
{
    Integer counter=0;
    Integer finalNumber = 100;
    
    for(Integer i=0; i<finalNumber; i++)
    {
            counter++;
    }
}

//Below code compiles
public class MyFirstClass
{
    Integer counter=0;
    Integer finalNumber = 100;
    
    public void myFirstMethod()
    {
        for(Integer i=0; i<finalNumber; i++)
        {
            counter++;
        }
    }
}

Hope this helps