Java 9 REPL (JShell): Codificação e Testes Interativos Simplificados
REPL significa Read-Eval-Print Loop. Com o JShell, o Java ganha capacidade REPL. Usando REPL, podemos codificar e testar lógica baseada em Java sem compilar com javac e ver o resultado de cálculos diretamente.
Executando o JShell
Abra o prompt de comando e digite jshell:
$ jshell
| Welcome to JShell -- Version 9-ea
| For an introduction type: /help intro
jshell>
Visualizando Comandos do JShell
Digite /help após iniciar o jshell:
jshell> /help
| Type a Java language expression, statement, or declaration.
| Or type one of the following commands:
| /list [<name or id>|-all|-start] | list the source you have typed
| /edit <name or id> | edit a source entry referenced by name or id
| /drop <name or id> | delete a source entry referenced by name or id
| /save [-all|-history|-start] <file> | Save snippet source to a file.
| /open <file> | open a file as source input
| /vars [<name or id>|-all|-start] | list the declared variables and their values
| /methods [<name or id>|-all|-start] | list the declared methods and their signatures
| /types [<name or id>|-all|-start] | list the declared types
| /imports | list the imported items
Executando Comandos no JShell
Digite /imports para ver imports padrão:
jshell> /imports
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| import java.util.concurrent.*
| import java.util.function.*
| import java.util.prefs.*
| import java.util.regex.*
| import java.util.stream.*
jshell>
Executando Cálculos no JShell
Teste cálculos simples:
jshell> 3+1
$1 ==> 4
jshell> 13%7
$2 ==> 6
jshell> $2
$2 ==> 6
jshell>
Criando e Usando Funções no JShell
Crie uma função doubled() que recebe int e retorna o dobro:
jshell> int doubled(int i){ return i*2;}
| created method doubled(int)
jshell> doubled(6)
$3 ==> 12
jshell>
Saindo do JShell
Digite /exit:
jshell> /exit
| Goodbye
O JShell acelera prototipação, aprendizado e testes exploratórios em Java.
Java
- Dominando Operadores Java: Tipos, Sintaxe e Exemplos Práticos
- Comentários em Java: Tipos, Uso e Boas Práticas
- Dominando o Loop for Aprimorado em Java: Sintaxe, Exemplos e Boas Práticas
- Dominando Strings em Java: Criação, Métodos e Boas Práticas
- Dominando Interfaces em Java: Conceitos, Implementação e Boas Práticas
- Dominando Classes Internas Anônimas em Java: Definição, Sintaxe e Exemplos Práticos
- Dominando Try-With-Resources em Java: Gerenciamento Automático de Recursos Explicado
- Anotações em Java Explicadas: Tipos, Posicionamento e Exemplos Práticos
- Asserções em Java: Guia Prático para Detectar Bugs e Garantir Confiabilidade do Código
- Entendendo o Java Vector: Uso, Recursos e Comparação com ArrayList