Skip to content

Example gallery

The NeoObjectPascal repository includes a collection of ready-to-run examples in NeoObjectPascal/examples/, numbered from 01 to 44. They range from "Hello, World!" to object orientation, tests with mocking, and cloud execution. This page organizes them by theme and shows the code of a few representative ones.

How to run

Run any example by passing the file path to the interpreter JAR:

bash
java -jar neoobjectpascal.jar examples/01-OlaMundo.npas

Test files use the .test.npas extension and run in test mode:

bash
# um arquivo de teste
java -jar neoobjectpascal.jar -t examples/34-TesteSimples.test.npas

# todos os testes de um diretório (recursivo, com cobertura)
java -jar neoobjectpascal.jar --test-all examples/

TIP

The actual JAR name depends on your build (for example, target/neoobjectpascal-*.jar). See the Introduction to generate the interpreter.

Fundamentals

FileDemonstrates
01-OlaMundo.npasThe minimal program: a single WriteLn in the main block
02-Variaveis.npasVariable declaration (String, Integer) and assignment
15-ConcatenacaoStrings.npasString concatenation with + and reading input
16-ExemploOriginal.npasIntroductory example combining several features
npas
begin
  WriteLn("Olá, Mundo!");
end.
Saída
 Olá, Mundo! 

Control flow and functions

FileDemonstrates
03-EstruturasDeControle.npasif ... then and the for i := 1 to N do loop
04-Funcoes.npasFunction declaration and call with return
07-ProgramacaoFuncional.npasChained pipe operator |>
npas
function somar(a, b): Integer;
begin
  return a + b;
end;

var resultado: Integer;

begin
  resultado := somar(20, 22);
  WriteLn("O resultado da soma é: ", resultado);
end.
Saída
 O resultado da soma é: 42 

The pipe operator passes the left-hand value as the first argument of the function on the right:

npas
function dobrar(x: Integer): Integer;
begin
  return x * 2;
end;

function adicionarUm(x: Integer): Integer;
begin
  return x + 1;
end;

begin
  WriteLn("O resultado do pipeline é: ", 5 |> dobrar |> adicionarUm);
end.
Saída
 O resultado do pipeline é: 11 

Data and I/O

FileDemonstrates
05-JSON.npasJSON.parse(...) into to load an object
06-CSV.npasCSV.parse(...) into to load rows
08-EntradaSaida.npasWriteLn and showMenu
13-MenuInterativo.npasNumbered menu with showMenu
14-EntradaUsuario.npasUser input with ReadLn
npas
var dados: Object;
var jsonString: String;

begin
  jsonString := '{"nome": "Carmen Sandiego", "idade": 30, "cidade": "São Paulo"}';
  JSON.parse(jsonString) into dados;
  WriteLn("Dados JSON processados com sucesso!");
end.
Saída
 Dados JSON processados com sucesso! 

Modules and internal libraries

FileDemonstrates
09-Modulos.npasuses of a local .npas module
10-ModulosCompleto.npasUsing multiple modules
11-ProjetoHierarquico.npasModules in hierarchical folders (lib.core.calculadora)
17-BibliotecasInternas.npasFunctions from internal.math, internal.string, internal.datetime
26-TesteDatetime.npasThe internal.datetime library
28-TesteFile.npas / 29-TesteFileSimples.npasThe internal.file library
npas
uses internal.math, internal.string;

begin
  WriteLn("Fatorial de 5: ", factorial(5));
  WriteLn("Fibonacci(8): ", fibonacci(8));
  WriteLn("Maiúsculas: ", toUpperCase("neoobjectpascal"));
end.

Details of all the functions in Internal libraries.

Java and hybrid systems

FileDemonstrates
20-SistemaHibrido.npasCombining Pascal code and embedded Java
21-TesteHibridoSimples.npasA simplified version of the hybrid system
22-TesteSemJava.npasThe equivalent without Java for comparison
23-DebugJava.npasDebugging Java blocks
24-FuncaoJava.npasA function that returns a value from a Java block
25-JavaComParametros.npasA Java block receiving parameters (param0, param1, ...)
27-SistemaHibridoFinal.npasThe complete hybrid system
npas
function testeJava(): String
begin
    return java:() {
        return "Olá do Java!";
    };
end;

begin
    WriteLn("Resultado: ", testeJava());
end.
Saída
 Resultado: Olá do Java! 

More in Java integration.

Object orientation

FileDemonstrates
30-ClasseSimples.npasA class with fields, constructor Create and a method
31-Heranca.npasInheritance with extends, virtual/override
32-Interface.npasinterface and implements
33-Polimorfismo.npasPolymorphism with overridden methods
npas
class Pessoa
    var nome: String;
    var idade: Integer;

    constructor Create(n: String, i: Integer)
    begin
        self.nome := n;
        self.idade := i;
    end;

    public function apresentar(): String
    begin
        return "Olá, meu nome é " + self.nome + " e tenho " + self.idade + " anos.";
    end;
end;

var pessoa: Pessoa;

begin
    pessoa := new Pessoa("João", 30);
    WriteLn(pessoa.apresentar());
end.
Saída
 Olá, meu nome é João e tenho 30 anos. 

Full guide in Classes, Inheritance and Interfaces.

Testing and mocking

FileDemonstrates
18-TesteSimples.npas / 19-TesteCompleto.npasIntroductory test blocks
34-TesteSimples.test.npasGIVEN-WHEN-THEN pattern with expect(...).toBe(...)
35-TesteHeranca.test.npasInheritance tests
36-TesteInterface.test.npasInterface tests
37-TestePolimorfismo.test.npasPolymorphism tests
38-TesteMocking.test.npasmock ... thenReturn and verify
npas
class Calculadora
    public function somar(a: Integer, b: Integer): Integer
    begin
        return a + b;
    end;
end;

test "Calculadora deve somar dois números corretamente"
begin
    var calc: Calculadora;
    calc := new Calculadora();

    var resultado: Integer;
    resultado := calc.somar(5, 3);

    expect(resultado).toBe(8);
end;

Replace a dependency with a mock and then verify it was called:

npas
test "NotificadorUsuario deve chamar EmailService ao notificar"
begin
    var emailService: EmailService;
    emailService := new EmailService();

    mock EmailService enviarEmail thenReturn true;

    var notificador: NotificadorUsuario;
    notificador := new NotificadorUsuario(emailService);

    var resultado: Boolean;
    resultado := notificador.notificar("usuario@teste.com");

    expect(resultado).toBeTrue();
    verify EmailService enviarEmail;
end;

Full guide in Unit testing.

Debugging and cloud

FileDemonstrates
39-DebugSimples.npasA simple program for the interactive debugger (-d)
40-CloudExample.npasAn example to run on NeoObjectPascal Cloud
debug-boolean.npas, debug-class.npas, debug-class2.npasAuxiliary debugging scenarios

New features

Examples that exercise recent language features:

FileDemonstrates
41-OperadoresBooleanos.npasThe and, or, not operators in conditions
42-AritmenticaReal.npasArithmetic with Real and auto-promotion of Integer
43-Arrays.npasArray literals, 0-based indexing, element assignment and for ... in
44-TratamentoErros.npastry/catch/finally and raise
npas
var numeros: Array;
var item: Integer;
var soma: Integer;

begin
    numeros := [10, 20, 30, 40, 50];
    numeros[2] := 99;              // atribuição de elemento (base 0)

    soma := 0;
    for item in numeros do
        soma := soma + item;

    WriteLn("Soma: ", soma);
end.
Saída
 Soma: 219 

Error handling with try/catch/finally and raise:

npas
function validarIdade(idade: Integer): String
begin
    if idade < 0 then
        raise "Idade invalida: " + idade;
    return "Idade valida: " + idade;
end;

begin
    try
    begin
        WriteLn(validarIdade(0 - 5));
    end
    catch (erro)
    begin
        WriteLn("Capturado: ", erro);
    end
    finally
    begin
        WriteLn("Cleanup concluido");
    end;
end.
Saída
 Capturado: Idade invalida: -5 Cleanup concluido 

Keep exploring

New here? Start with the Introduction to install the interpreter and run your first program. For the complete syntax, see the Language reference.