Command Palette

Search for a command to run...

Back to the lesson: Topic 0.6 — Try Java Instantly with JShell
Core Java · Example 2 of 3 Java 16+

Methods and records, tested in JShell, kept in a file

In a file, methods called from main must be static (Topic 4.6), and the record sits beside the class.

JShell is Java's interactive playground, included in every JDK since Java 9. You type one line of Java, press Enter, and see the result at once, with no class, no main method and no compile step, which makes it the fastest way to test an idea or explore a library method.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

In JShell, compute how many seconds are in a week. Then write the same as a program.

02

In JShell, define a method square(int n) and call it with 7 and -3. Then write a program with the same method.

03

Use JShell to find what " Java ".strip() and " Java ".length() return. Write a program that prints both.

Explain it without notes

01

What is a REPL, and how does JShell fit that description?

02

What do x ==> 5 and $2 ==> 10 mean in JShell output?

03

Name three ways JShell is more relaxed than a normal Java source file.

04

When would you use JShell, and when would you write a .java file instead?

Methods and records, tested in JShell, kept in a file Java 16+
Sign in to run this example in your browser.

Expected output

twice(21) = 42
twice(-4) = -8
A pet: Pet[name=Milo]