Write an Apex Class to perform addition, subtraction and Multiplication

In this Salesforce tutorial, we are going to write an Apex Class to perform addition, subtraction and multiplication based on the button we clicked. And also we learn how to call Apex method in a Visualforce page.

How to write an Apex Class?

Apex class is a collection of data members and methods. Let us learn how to write an Apex Class. To write an Apex class navigate to Developer Console | File | New | Apex Class.

Apex Class

ADVERTISEMENT

Write an <a href=Apex Class to perform addition, subtraction and Multiplication" width="1264" height="616" />

How to call the Apex methods in a Visualforce page.

Apex class

public Class Demo < public pageReference Show() < return null; >>

Visualforce page

Apex Class to perform addition, subtraction and Multiplication.

In our previous Salesforce tutorial, we have learned about Apex Setter method and Getter method. We can also define Setter and getter methods in a single line.

Apex Class.

public class subtraction < public Integer xvalue public Integer yvalue public Integer result public string operation public pagereference sub() < result = xvalue-yvalue; operation = 'Subtraction'; return null; >public pagereference add() < result = xvalue+yvalue; operation = 'Addition'; return null; >public pagereference mul() < result = xvalue*yvalue; operation = 'Multiplication'; return null; >>

As shown above, we have named the Apex class as Subtraction.

Visualforce page

     Enter X value "/> Enter Y value "/> Result "/>  You have performed of and .  "/> "/> "/>    

In the above Visualforce page, we have added some Visualforce components like , , , , . All these components are for Styling, adding buttons like Salesforce Salesforce buttons.

Output

As shown above example, enter X value and Y value then click on Addition or Subtraction or Multiplication button. Suppose when we click on Multiplication, the result will be displayed in Result section.