0

I am beginner in Salesforce and still in initial steps in understanding the concepts..i tried the below class and the output didn't come as expected

public class mytest2 
{
    Public integer marks;
    Public string result;
        {
        if(marks >= 35 && marks <= 50)
        result = 'passed';
        else if (marks >= 51 && marks <= 70)
        result = 'B';
        else if (marks >= 71)
        result ='A';
        else 
        result = 'failed';
                {
                  system.debug('Your results:' + result);
                }
        }    
}

and executing it in anonymous window

mytest2 c1 = new mytest2();
c1.marks = 55;
system.debug(c1);

Output was

Your results:failed

which seems to be wrong

1 Answer 1

5

You've inadvertently written a fairly rare construct called an instance initialization block:

    {
    if(marks >= 35 && marks <= 50)
    result = 'passed';
    else if (marks >= 51 && marks <= 70)
    result = 'B';
    else if (marks >= 71)
    result ='A';
    else 
    result = 'failed';
            {
              system.debug('Your results:' + result);
            }
    }    

This code runs only at the time the class is instantiated, i.e., new mytest2(). At that point the variable marks has no value and is null.

You will probably want to define a method here instead of your initializer block. This is covered in the documentation linked above. Also consider completing the Apex Basics and Database module on Trailhead.

Additionally, you should always use curly braces to delimit the scope of your control statements (if/else). Doing otherwise leads to difficult-to-interpret logic and inscrutable bugs when the compiler does not group statements as you expect it to.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .