Java Shell User S Guide - Oracle

Transcription

Java Platform, Standard EditionJava Shell User’s GuideRelease 9E87478-01September 2017

Java Platform, Standard Edition Java Shell User’s Guide, Release 9E87478-01Copyright 2017, Oracle and/or its affiliates. All rights reserved.This software and related documentation are provided under a license agreement containing restrictions onuse and disclosure and are protected by intellectual property laws. Except as expressly permitted in yourlicense agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify,license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means.Reverse engineering, disassembly, or decompilation of this software, unless required by law forinteroperability, is prohibited.The information contained herein is subject to change without notice and is not warranted to be error-free. Ifyou find any errors, please report them to us in writing.If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it onbehalf of the U.S. Government, then the following notice is applicable:U.S. GOVERNMENT END USERS: Oracle programs, including any operating system, integrated software,any programs installed on the hardware, and/or documentation, delivered to U.S. Government end users are"commercial computer software" pursuant to the applicable Federal Acquisition Regulation and agencyspecific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of theprograms, including any operating system, integrated software, any programs installed on the hardware,and/or documentation, shall be subject to license terms and license restrictions applicable to the programs.No other rights are granted to the U.S. Government.This software or hardware is developed for general use in a variety of information management applications.It is not developed or intended for use in any inherently dangerous applications, including applications thatmay create a risk of personal injury. If you use this software or hardware in dangerous applications, then youshall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure itssafe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of thissoftware or hardware in dangerous applications.Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks oftheir respective owners.Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks areused under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron,the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced MicroDevices. UNIX is a registered trademark of The Open Group.This software or hardware and documentation may provide access to or information about content, products,and services from third parties. Oracle Corporation and its affiliates are not responsible for and expresslydisclaim all warranties of any kind with respect to third-party content, products, and services unless otherwiseset forth in an applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not beresponsible for any loss, costs, or damages incurred due to your access to or use of third-party content,products, or services, except as set forth in an applicable agreement between you and Oracle.

ContentsPreface1234AudiencevDocumentation AccessibilityvRelated DocumentsvConventionsvIntroduction to JShellWhy Use JShell?1-1Starting and Stopping JShell1-1SnippetsTrying Out Snippets2-1Changing Definitions2-2Forward References2-3Exceptions2-4Tab Completion for Snippets2-4Snippet Transformation2-5CommandsIntroduction to Commands3-1Tab Completion for Commands3-2Command Abbreviations3-4EditingShell Editing4-1Input Line Navigation4-1History Navigation4-2Input Line Modification4-3Search and More4-3iii

External Editor5674-4External CodeSetting the Class Path5-1Setting Module Options5-1Feedback ModesSetting the Feedback Mode6-1Defining a Feedback Mode6-2ScriptsStartup Scripts7-1Creating and Loading Scripts7-2iv

PrefaceThis guide provides information about using the Java Shell tool (JShell) to explore theJava language and prototype code.AudienceThis document is intended for developers interested in using a Read-Eval-Print Loop(REPL) tool to learn the Java language, explore new Java APIs and features, andprototype complex code.Documentation AccessibilityFor information about Oracle's commitment to accessibility, visit the OracleAccessibility Program website at http://www.oracle.com/pls/topic/lookup?ctx acc&id docacc.Access to Oracle SupportOracle customers that have purchased support have access to electronic supportthrough My Oracle Support. For information, visit http://www.oracle.com/pls/topic/lookup?ctx acc&id info or visit http://www.oracle.com/pls/topic/lookup?ctx acc&id trsif you are hearing impaired.Related DocumentsSee Oracle JDK 9 Documentation for other JDK 9 guides.ConventionsThe following conventions are used in this document:ConventionMeaningboldfaceBoldface type indicates graphical user interface elements associatedwith an action, or terms defined in text or the glossary.italicItalic type indicates book titles, emphasis, or placeholder variables forwhich you supply particular values.monospaceMonospace type indicates commands within a paragraph, URLs, codein examples, text that appears on the screen, or text that you enter. keys Name of a keyboard key or key combination in angle brackets ( )indicates that the key or key combination is pressed as part of the userinput.v

1Introduction to JShellThe Java Shell tool (JShell) is an interactive tool for learning the Java programminglanguage and prototyping Java code. JShell is a Read-Evaluate-Print Loop (REPL),which evaluates declarations, statements, and expressions as they are entered andimmediately shows the results. The tool is run from the command line.Topics Why Use JShell? Starting and Stopping JShellFor reference information for this tool, see jshell in Java Platform, Standard EditionTools Reference.Why Use JShell?Using JShell, you can enter program elements one at a time, immediately see theresult, and make adjustments as needed.Java program development typically involves the following process: Write a complete program. Compile it and fix any errors. Run the program. Figure out what is wrong with it. Edit it. Repeat the process.JShell helps you try out code and easily explore options as you develop your program.You can test individual statements, try out different variations of a method, andexperiment with unfamiliar APIs within the JShell session. JShell doesn’t replace anIDE. As you develop your program, paste code into JShell to try it out, and then pasteworking code from JShell into your program editor or IDE.Starting and Stopping JShellJShell is included in JDK 9. To start JShell, enter the jshell command on thecommand line.JDK 9 must be installed on your system. If your path doesn’t include java-home/jdk-9/bin, start the tool from within that directory.The following example shows the command and the response from JShell. Text thatyou enter is shown in bold:% jshell Welcome to JShell -- Version 91-1

Chapter 1Starting and Stopping JShell For an introduction type: /help introjshell The examples in this tutorial use the verbose mode. Verbose mode is recommendedas you work through this tutorial so that what you see matches the examples. Whenyou are more familiar with the tool, you might prefer to run in normal or a more concisemode.To start JShell in verbose mode, use the -v option:% jshell -vTo exit JShell, enter /exit:jshell /exit Goodbye1-2

2SnippetsJShell accepts Java statements; variable, method, and class definitions; imports; andexpressions. These pieces of Java code are referred to as snippets.Topics Trying Out Snippets Changing Definitions Forward References Exceptions Tab Completion for Snippets Snippet TransformationTrying Out SnippetsSnippets of Java code are entered into JShell and immediately evaluated. Feedbackabout the results, actions performed, and any errors that occurred is shown. Use theexamples in this section to give JShell a try.Start JShell with the verbose option to get the maximum amount of feedback available:% jshell -v Welcome to JShell -- Version 9 For an introduction type: /help introEnter the following sample statement at the prompt, and review the output that isshown:jshell int x 45x 45 created variable x : intFirst, the result is shown. Read this as: the variable x has the value 45. Because youare in verbose mode, a description of what occurred is also shown. Informativemessages start with a vertical bar. Notice that both the name and the type of thecreated variable are shown.Note:Terminating semicolons are automatically added to the end of a completesnippet if not entered.When an expression is entered that doesn't have a named variable, a scratch variableis created so that the value can be referenced later. The following example showsscratch values for an expression and for the results of a method. The example also2-1

Chapter 2Changing Definitionsshows the continuation prompt (. ) that is used when a snippet requires more thanone line of input to complete:jshell 2 2 3 4 created scratch variable 3 : intjshell String twice(String s) {. return s s;. } created method twice(String)jshell twice("Ocean") 5 "OceanOcean" created scratch variable 5 : StringChanging DefinitionsAs you experiment with code, you might find that the definition of a variable, method,or class isn’t doing what you want it to do. The definition is easily changed by enteringa new one, which overwrites the previous definition.To change the definition of a variable, method, or class, simply enter a new definition.For example, the twice method that was defined in Trying Out Snippets gets a newdefinition in the following example:jshell String twice(String s) {. return "Twice:" s;. } modified method twice(String)jshell twice("thing") 7 "Twice:thing" created scratch variable 7 : StringNotice that instead of showing created method as before, the feedback showsmodified method. This message means that the definition changed, but the methodhas the same signature, and therefore all existing usages continue to be valid.You can also change definitions in incompatible ways. The following example shows xbeing changed from int to String:jshell int x 45x 45 created variable x : intjshell String xx null replaced variable x : String update overwrote variable x : intThe type of the variable x changed, and the feedback now shows replaced.Changing the Level of FeedbackJShell was started in the verbose feedback mode, which provides a lot of commentary.You can set the amount and format of output with the /set feedback command, forexample /set feedback concise. If you primarily use JShell by pasting from other2-2

Chapter 2Forward Referenceswindows, then you might prefer a feedback mode with no prompt and only errorfeedback. If so, then enter the /set feedback silent command.Forward ReferencesJShell accepts method definitions that reference methods, variables, or classes thataren’t yet defined. This is done to support exploratory programming and becausesome forms of programming require it.As an example, if you want to define a method for the volume of a sphere, then youcan enter the following formula as the method volume:jshell double volume(double radius) {. return 4.0 / 3.0 * PI * cube(radius);. } created method volume(double), however, it cannot be invoked until variable PI,and method cube(double) are declaredJShell allows the definition but warns of what is yet to be defined. The definition can bereferenced, but if execution is attempted, then it fails until all of the required elementsare defined:jshell double PI 3.1415926535PI 3.1415926535 created variable PI : doublejshell volume(2) attempted to call method volume(double) which cannot be invoked until methodcube(double) is declaredjshell double cube(double x) { return x * x * x; } created method cube(double) update modified method volume(double)jshell volume(2) 5 33.510321637333334 created scratch variable 5 : doubleWith all of the definitions in place, the volume method now works.This method is now used to illustrate more about incompatible replacement. Forexample, to change the precision of PI, enter the new value as shown in the followingexample:jshell BigDecimal PI new BigDecimal("3.141592653589793238462643383")PI 3.141592653589793238462643383 replaced variable PI : BigDecimal update modified method volume(double) which cannot be invoked until this erroris corrected: bad operand types for binary operator '*' first type: double second type: java.math.BigDecimal return 4.0 / 3.0 * PI * cube(radius); ------------ update overwrote variable PI : doubleThe new definition of PI is type-incompatible with the definition of volume(). Becauseyou are in verbose mode, update information is shown for other definitions affected bythe change, which in this case describes the incompatibility. Notice that verbose mode2-3

Chapter 2Exceptionsis the only predefined feedback mode that displays update information. In otherfeedback modes, no warning is displayed until the code is executed. The purpose ofthis is to prevent an overload of updates. In all predefined modes, executing thevolume() method displays the issue:jshell volume(2) attempted to call method volume(double) which cannot be invoked until this erroris corrected: bad operand types for binary operator '*' first type: double second type: java.math.BigDecimal return 4.0 / 3.0 * PI * cube(radius); ------------ ExceptionsIn an exception backtrace, feedback identifies the snippet and the location withi

The Java Shell tool (JShell) is an interactive tool for learning the Java programming language and prototyping Java code. JShell is a Read-Evaluate-Print Loop (REPL), which evaluates declarations, statements, and expressions as they are entered and immediately shows the results. The tool is run from the command line. Topics Why Use JShell? Starting and Stopping JShell For reference .