93

Is there something like python's interactive REPL mode, but for Java? So that I can, for example, type InetAddress.getAllByName( localHostName ) in a window, and immediately get results, without all this public static void nightmare() thing?

svick
  • 236,525
  • 50
  • 385
  • 514
Yoni Roit
  • 28,280
  • 7
  • 36
  • 32
  • 5
    Yes, there is: http://www.scravy.de/blog/2012-02-27/a-read-eval-print-loop-for-java.htm – scravy Oct 08 '12 at 20:52
  • 3
    Java introducing it in [JDK-9](http://openjdk.java.net/projects/jdk9/) : [JEP 222: jshell: The Java Shell](http://openjdk.java.net/jeps/222) – Not a bug Jun 17 '15 at 09:49

29 Answers29

64

edit Since Java 9 there's JShell

Original answer follows

You can also use Groovy Console. It is an interactive console where you can do what you want. Since Groovy also includes classes from the core java platform, you'll be able to use those classes as well.

It looks like this:

Screenshot of Groovy

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • 1
    The screenshot no longer exists on imageshack. –  Mar 04 '13 at 18:31
  • What's particularly nice about the groovy console is that a lot more packages are imported by default (e.g. java.util.*), so you don't need to write so many import statements – Dónal Jul 15 '13 at 17:27
  • 2
    For those that are too lazy to install Groovy, there's an online version of this console available here: http://groovyconsole.appspot.com. Some JDK libs are unavailable (e.g. I/O and `System.exit()`) but for most purposes it should be adequate. – Dónal Jul 15 '13 at 17:32
  • This does not accept classes is that normal? `class test{public static void test(){System.out.println('test')}}` – Lime Feb 11 '17 at 03:22
52

Eclipse has a feature to do this, although it's not a loop. It's called a "Scrapbook Page". I assume the analogy is supposed to be that you have a scrapbook where you collect little snippets of code.

Anyway, to make it work, open a project in Eclipse (your Scrapbook Page is going to be associated with a project -- Eclipse likes it when projects own things).

Then:

  1. In the project navigator window, select a folder that exists somewhere in your project.
  2. Either select the menu File -> New -> Other, or hit Control-N.
  3. Select Java -> Java Run/Debug -> Scrapbook Page.
  4. Hit "Next", then give it a filename, then hit "Finish".

Now you have a scrapbook page. Type some code, like maybe this:

System.out.println(System.getProperties());

Then select the text with the mouse, and either hit Control-U or select "Execute" from the context menu. The code will run and the output will appear on the console.

You can also type an expression, select it, and select Display from the context menu. It'll evaluate the expression and print its type. For example, running Display on 1 + 2 will print (int) 3.

29

BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell dynamically executes standard Java syntax and extends it with common scripting conveniences such as loose types, commands, and method closures like those in Perl and JavaScript. You can use BeanShell interactively for Java experimentation and debugging as well as to extend your applications in new ways. Scripting Java lends itself to a wide variety of applications including rapid prototyping, user scripting extension, rules engines, configuration, testing, dynamic deployment, embedded systems, and even Java education.

http://www.beanshell.org/

http://www.beanshell.org/manual/syntax.html#Standard_Java_Syntax

bakkal
  • 54,350
  • 12
  • 131
  • 107
  • There are also Jython and JRuby interactive shells for less verbose syntaxes. – bakkal Apr 14 '10 at 09:02
  • 1
    BeanShell is actively maintained as beanshell 2 - https://code.google.com/p/beanshell2/ – hshib Oct 30 '13 at 13:24
  • A simple example of running beanshell from the command line [can be found here](http://www.philippeadjiman.com/blog/2009/10/17/beanshell-tutorial-quick-start-on-invoking-your-own-or-external-java-code-from-the-shell/) – Brad Parks Jan 13 '16 at 14:53
  • @hshib: It's now at [Github](https://github.com/pejobo/beanshell2) and the last commit is from 2013. That's *not* "actively maintained". – Martin Schröder May 22 '17 at 12:34
  • @MartinSchröder, that comment WAS in 2013 :-) – hshib May 23 '17 at 13:39
  • I did some research on the state of BeanShell a couple years ago as an answer to https://stackoverflow.com/questions/26549307/current-state-of-beanshell a couple years ago. – hshib May 23 '17 at 13:43
19

Old question, but there is a better answer now (May 2013) - java-REPL! It's available on github and also available live at the java-repl website for quick one-off testing.

If you grab the git hub code and run ant to generate the artifacts, you can make it easy to use with a small script like:

#!/bin/sh
java -jar /home/rdahlgren/scripts/javarepl-dev.build.jar

Since finding this project I probably use it 5 times a day. Enjoy!

  • The link for the online repl now seems to be http://www.javarepl.com/term.html the old link just shows Java errors. – Tony Oct 05 '17 at 21:02
19

You can use Eclipse Scrapbook pages.

In Eclipse create a Scrapbook page. In your project, New->Other->Scrapbook page.

In the file, enter some text, select it and hit ctrl-U, and there you go.

To manage your imports, right click in the page and select Set Imports, where you can choose to import a package or a single class. This is persistent, and is saved with the page.

Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
  • 3
    Useful as it may be, a scrapbook page isn't a persistant session, so doesn't really work very well as a REPL. – MHarris Jan 17 '12 at 13:35
13

Seems nobody mentioned yet that Java (6, 7) ships a REPL console called jrunscript. It is language agnostic (so can be used with Jython, JRuby etc.). It defaults to JavaScript (Rhino) which is also bundled by default, and like the other languages you can access all the packages/objects available on the classpath.

user268396
  • 11,576
  • 2
  • 31
  • 26
12

It's part of OpenJDK 9!

A REPL called JShell (developed by Oracle) has been released as part of JDK 9.

Just download JDK 9, and launch bin/jshell.

Screen shot of JShell

Resources

aioobe
  • 413,195
  • 112
  • 811
  • 826
12

As an alternative to Groovy, try Beanshell: http://www.beanshell.org/

It is more Java-like and allows you to use Java-syntax directly.

Tim Jansen
  • 3,330
  • 2
  • 23
  • 28
11

Jython is a python implementation which lets you inspect and interact with Java objects.

>>> from java.net import *
>>> InetAddress.getAllByName("google.com")
array(java.net.InetAddress,[google.com/209.85.171.100, 
                            google.com/74.125.45.100,
                            google.com/74.125.67.100])
jfs
  • 399,953
  • 195
  • 994
  • 1,670
speciousfool
  • 2,620
  • 5
  • 28
  • 33
9

Java-REPL by Albert Latacz works well.

You can try it directly from your browser here: http://www.javarepl.com/term.html

The source code is available here, and it has a decent Intelli-J plugin.

https://github.com/albertlatacz/java-repl

seinecle
  • 10,118
  • 14
  • 61
  • 120
Matthieu Cormier
  • 2,185
  • 1
  • 21
  • 32
8

Clojure provides a REPL you can use.

Ande Turner
  • 7,096
  • 19
  • 80
  • 107
7

The groovy console allows you to do that. It actually was meant to try and test groovy code, but since groovy is a superset of Java, it allows plain Java stuff as well.

I just entered this into the console:

InetAddress.getAllByName('localhost')

and hit CTRL-R, then it returned:

groovy> InetAddress.getAllByName('localhost')

Result: [localhost/127.0.0.1]
Ole
  • 1,214
  • 9
  • 10
7

Scala also offers an interactive console. I was able to use it to get a result for the expression in your question by fully qualifying InetAddress, as in:

java.net.InetAddress.getAllByName("localhost")
joel.neely
  • 30,725
  • 9
  • 56
  • 64
6

While JRuby, BeanShell, Julian Fleischer's REPL are there Albert Latacz's REPL seems to be the latest and active.

Tried it with a simple class definition, works fine.

$ java -jar javarepl.jar
Welcome to JavaREPL version 56 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_17)
Type in expression to evaluate.
Type :help for more options.

java> public class Test {
    | public static void execute(String [] s) {
    |  System.out.println(54353 + s[0]);
    | }}

java> Test.execute(new String [] {"234343"});
54353234343

java> System.exit(0);
sandeepkunkunuru
  • 6,150
  • 5
  • 33
  • 37
3

For folks with access to Mathematica, JLink lets you access Java and script with Mathematica code:

Needs["JLink`"]
LoadJavaClass["java.net.InetAddress"]
InetAddress`getAllByName["localhost"]

Hit Shift-Enter to evaluate, and you get

{<<JavaObject[java.net.Inet4Address>>}

Then you can use Mathematica's Map function to call toString on the returned objects:

#@toString[]& /@ %

to get the result (or to use the less obscure syntax, Map[Function[obj, obj@toString[]], %]):

{"localhost/127.0.0.1"}

If you start to get serious with this, you'll want to read Todd Gayley's tutorial at http://reference.wolfram.com/mathematica/JLink/tutorial/Overview.html.

jfklein
  • 877
  • 1
  • 11
  • 13
2

Yes, there is: http://www.scravy.de/blog/2012-02-27/a-read-eval-print-loop-for-java.htm

scravy
  • 11,904
  • 14
  • 72
  • 127
2

If you already know Groovy (which I assume you do, since you mentioned the Groovy Console), then just use groovysh or groovyConsole, which are included in the Groovy distro. If you have custom jars that you want to import, you can either write a batch file that starts up groovysh/groovyConsole with those added to the classpath. You can also do this

this.class.classLoader.rootLoader.addURL(new URL("file:///path to file"))

from within the shell to load other jars.

I used to use Jython several years ago to do just what you're asking. As part of my build script, I generated a custom jython.bat and .py file that included the full classpath for the project I was working on. That way when I started Jython, it would have all the code available, and it would bring up Spring to let me twiddle things in the live system. You can do the same thing with Groovy, JRuby, BeanShell, etc.

Joey Gibson
  • 7,104
  • 1
  • 20
  • 14
  • I know I could use the groovy shell, but Groovy doesn't have exactly the same semantics as Java, and has no type-checking. So it's possible that I could get compile errors, or different runtime behaviour with a piece of Java code that seemed to work in the Groovy shell. – Dónal Apr 14 '10 at 14:30
  • groovy will also load all lib in ~/.groovy/lib , you could either copy stuff in there or use symlinks – Jason Aug 14 '15 at 16:59
2

you can script java using jruby http://kenai.com/projects/jruby/pages/CallingJavaFromJRuby

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
1

You could take a look at BlueJ which is an interactive Java development environment meant for teaching OOP rather than as full IDE like Eclipse or NetBeans. It's kind of fun to have a play with anyway.

You can see it in action on YouTube in a series of Java tutorials.

Trevor Tippins
  • 2,827
  • 14
  • 10
  • this is interesting. Bluej is like an op repl. Not really useful for the things you currently use a repl for but you might use it to prototype your oo design as you would use a repl to prototype a method. – Bill K Nov 28 '14 at 09:12
1

There is simple IDE called DrJava that has an Interactions console. It works exactly as I would expect. Just load a file and start interacting with the objects in it.

dansalmo
  • 11,506
  • 5
  • 58
  • 53
1

There's an online REPL: http://www.javarepl.com/console.html

Typing more to reach the character limit ...

Max Heiber
  • 14,346
  • 12
  • 59
  • 97
1

For java 8, there is nudge4j. see https://github.com/lorenzoongithub/nudge4j

nudge4j java repl

... and the beauty is that you can pilot your application from the browsert

Zo72
  • 14,593
  • 17
  • 71
  • 103
1

JPad is a java scratchpad with a builtin REPL:

C:\>jpad
       _ _____          _
      | |  __ \        | |
      | | |__) |_ _  __| |
  _   | |  ___/ _` |/ _` |
 | |__| | |  | (_| | (_| |
  \____/|_|   \__,_|\__,_|



Anything you type is evaluated as java.
The code is continuously appended until you call \clear.
Other Available Commands:
\exit - exit
\clear (n) - clear past java statements
\history - display all past java statements
\help - display this help

j>2+2
4
j>Math.sin(100.1)
-0.4177477
j>

It is also smart about dumping collections, lists, maps etc and allows rendering them as a table or chart:

enter image description here

Ryan Hamilton
  • 2,601
  • 16
  • 17
1

Most IDE's have a window called something like "immediate mode" that will allow you to evaluate java code on the fly.

krosenvold
  • 75,535
  • 32
  • 152
  • 208
  • Eclipse has "display" view which is close to what I want. Problem is, it has to be in the context of running application. I have to run an app, stop on breakpoint and only then I can type what I want. – Yoni Roit Dec 29 '08 at 11:03
  • @YoniRoit IMHO I like "display" + debug mode better than a command line REPL. I used to use REPL w/ Python a long time ago so I have done both. I think its far better to write a Unit Test and place a break point and play with the desired context while pasting whatever code works back into the unit test. Getting an exact context in a plain REPL is much harder than say a Unit Test. – Adam Gent Mar 31 '13 at 13:56
1

Java 9 is providing the JShell.

jshell> println( "Print me!")
jshell> Print me!
Neha Gangwar
  • 670
  • 9
  • 14
1

DrJava is an educational IDE that includes an REPL pane.

There is an Eclipse plugin as well, but it hasn't worked for me. I think it just hasn't been updated in a while. So what I generally do is keep a DrJava window open for the "what happens if I do this" questions.

EclipseShell might be good too, but I haven't used it yet.

johncip
  • 2,087
  • 18
  • 24
1

Beanshell 2

harish
  • 181
  • 1
  • 7
0

Jython, JIRB for JRuby, Groovy (groovyconsole et al) and Beanshell are all viable options.

I've used the InteractiveConsole for Jython, it really worked nicely in the app.

gpampara
  • 11,989
  • 3
  • 27
  • 26
0

Since JDK 11, which was released in September 2018, the java command allows launching of a single java source code file. See bug report 8192920 and also JEP 330

Abra
  • 19,142
  • 7
  • 29
  • 41