- Java for Small Tasks: Java is suitable for both large and small tasks. Recent language features enhance its usability for small jobs. Compile-time typing and great tool support are key.
- Automating Repetitive Tasks: In author and teaching jobs, repetitive tasks like file manipulation lead to messy bash scripts. Python's API isn't great and dynamic typing causes debugging issues. Java, with its known API and static typing, is a better choice.
- Launching without Compiling: For simple tasks like verifying backups, Java code can be launched directly as a
.java
file without compiling or making a JAR. JEP 330 and JEP 458 enable this. Graal can compile scripts into native executables for faster startup. JShell isn't ideal for scripts. - Instance Main Methods and Implicit Classes: JEP 477 reduces verbosity in small Java programs. Any Java file with a top-level
main
method becomes an implicit class. Alljava.base
modules are automatically imported. - Records and Enums: Java has records and enums that make code more readable and natural. Records are useful for aggregating information, and enums are better than Python's enumerations.
- Other Helpful Language Features: In scripts,
var
is used liberally, and static imports are more aggressive. Text blocks help keep data with code. - Helpful API Features: The Java library for strings, regex, collections, and date/time is excellent. But it lacks JSON and command-line processing. Simple libraries can be used instead.
- Checked Exceptions: In scripts, checked exceptions can be a burden.
throws Exception
can be added to methods, or "sneaky throw" libraries can be used to handle exceptions. - IDEs and File Organization: An IDE is helpful for Java scripting. Middle-weight editors like Visual Studio Code or Emacs with LSP mode can be used. Heavy-weight IDEs can be coaxed to use the project base directory as the source directory.
- JBang: The biggest pain with Java scripting is using third-party libraries. JBang allows adding Maven dependencies directly into the source file and launching programs easily.
- Notebooks: Exploratory programming is done using notebooks. Python has Jupyter, and Java has Jupyter Java Anywhere with different Java kernels. Sven Reimers is developing JTaccuino for a better Java notebook experience. Kotlin has the Kotlin Notebook IntelliJ plugin.
- Conclusion: With the right tooling, Java is an effective choice for small programs. It benefits from compile-time typing and has potential for exploratory programming.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。