You need to sign in to do that
Don't have an account?
Apex Beginner
Apex class in anonymous window
Hello,
I am beginner in Salesforce and still in initial steps in understanding the concepts..i tried the below class and the output didnt 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 ..not sure what went wrong here
I am beginner in Salesforce and still in initial steps in understanding the concepts..i tried the below class and the output didnt 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 ..not sure what went wrong here
So you place the logic in Instance initialization code, which is executed each time an object is instantiated from that class. This code runs before the constructor and executed only once
For example, if you declare marks variable with some value like below and if you execute the following code in anonymous window
mytest2 c1 = new mytest2(); you can see the output as
One more thing to remember is that the instance instalization code runs before the constructor. For example if you create a constructor for your test class to take the marks value as an argument, like this
Suppose if you execute the following code in anonymous window, you will get the failed value only.
I think you can use apex class methods to take marks as an argument and return the result as output.
Regards,
Naga
I have provided an example code below for guidance. If you have any questions, please feel free to comment further.
Apex Class Code:
Anonymous Block Code:
public class mytest2
{
public static string result (Integer marks) {
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);
}
}