beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

java 9 JShell – Working with Methods

By Chaitanya Singh | Filed Under: Java 9 Features

In the previous tutorial we learned how to work with variables in JShell. In this guide, we will learn how to create methods in JShell, how to use them and how to modify the definition of already defined method.

JShell – Methods

Lets see how to define a method in JShell. In the following example, we have defined a method add() and later called this method with arguments to get the sum of two integer numbers.

jshell> int add(int a, int b) {
   ...> return a+b;
   ...> }
|  created method add(int,int)

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

JShell Methods

JShell – how to change the definition of already defined method

We can also change the definition of an already defined method. In the following example, we are modifying the definition of method add()

jshell> int add(int a, int b) {
   ...> return a+b;
   ...> }
|  created method add(int,int)

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

jshell> int add(int a, int b) {
   ...> return a+b+100;
   ...> }
|  modified method add(int,int)

jshell> add(10, 20)
$4 ==> 130

Note: Since we are changing the definition of method add(), JShell feedback shows it as modified method add(int, int) instead of created method add(int,int).
JShell changing method definition

Reference:

Oracle JDK 9 Documentation

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java 9 Tutorial

  • Java 9 features
  • JShell
  • Immutable List
  • Immutable Set
  • Immutable Map
  • Private Methods in Interface
  • Try-With-Resources Enhancement
  • Java 9 -Diamond operator Enhancement
  • @SafeVarargs annotation
  • Java 9 - Stream API Enhancements
  • Java 9 Modules

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap