Define Expressions, Variables and Methods in JShell in Java 9



JShell is a Read-Evaluate-Print Loop (REPL) that evaluates declarations, statements, and expressions as we have entered and immediately shows the results. This tool is run from the command prompt.

Below, we can define expressions, variables, and methods in JShell.

Expression

The combination of variables, operators, and methods is known as an Expression in Java. They perform some logic that evaluates to a single value.

int a=5, b=10, c=0;
c=a+b; 

Here, "a+b" is an expression that evaluates the value of c as 15.

Expression in JShell

We can type any valid Java expression in JShell. The expression is either an arithmetic operation, string manipulation, or method call, and evaluates immediately. All the results are automatically assigned to a variable created by JShell. These variables have prefixed with $ symbol.

Example

jshell> 10 * 5
$1 ==> 50

jshell> 77 % 3
$2 ==> 2

jshell> $1 + $2
$3 ==> 52

jshell>

Variable

The variables are like containers that are used to store the values. Each variable in Java has a specific type, which determines the size and layout of the variable's memory.

int var=10;

Here, "var" is the variable whose value is assigned as "10".

Variable in JShell

The Variables defined in JShell are the same as those defined in a Java program. Once a variable is defined, it is present in the scope.

Example

jshell> String str = "Tutorialspoint"
str ==> "Tutorialspoint"

jshell> str
str ==> "Tutorialspoint"

jshell>

Method

The Method is a collection of statements that are grouped together to perform an operation.

Syntax to Create a Java Method

modifier returnType nameOfMethod (Parameter List) {
// method body
}

Method in JShell

We can define methods in JShell in the same way as we can in Java classes. Once a method has created in a JShell session, we can call it anytime until quitting that session.

Example

jshell> int sum(int x, int y) {
   ...> return x + y;
   ...> }
| created method sum(int,int)

jshell> sum(10,20)
$2 ==> 30

jshell>
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-06-10T18:41:50+05:30

995 Views

Kickstart Your Career

Get certified by completing the course

Get Started