Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use arithmetic expressions in java apache velocity with Example
35748 Views
Arithmetic Expressions in VTL using #set 
#set method is used to evaluate the expressions in VTL.

Example
#set ($c = $a + $b)
ExpressionInVTLExample
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class ExpressionInVTLExample {
    public static void main(String args[]){
        VelocityEngine ve = new VelocityEngine();
        ve.init();
         
        Template t = ve.getTemplate("velocitytemplate.vm");
         
        VelocityContext vc = new VelocityContext();
        vc.put("a", 30);
        vc.put("b", 20);
        
        StringWriter sw = new StringWriter();
        t.merge(vc, sw);
         
        System.out.println(sw);
    }
}
Velocitytemplate.vm 
Arithmetic Expressions in VTL
A = $a
B = $b

#set ($sum = $a + $b)
Sum = $sum

#set ($min = $a - $b)
Minus = $min

#set ($mul = $a * $b)
Multiply = $mul

#set ($div = $a / $b)
Division = $div

#set ($mod = $a % $b)
Modules = $mod
Output 
Arithmetic Expressions in VTL
A = 30
B = 20

Sum = 50

Minus = 10

Multiply = 600

Division = 1

Modules = 10
Best Lessons of "Java Apache Velocity Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details