12

How to find the type of a variable or Expression Result in JShell.

Was experimenting Bitwise Operators in Java

jshell> byte b=5<<-1;
|  Error:
|  incompatible types: possible lossy conversion from int to byte
|  byte b=5<<-1;
|         ^---^

jshell> 5<<-1
$2 ==> -2147483648

jshell>

Is there an alternative like Python type(5<<-1) to find the result type of expression or variable in Jshell.

Sundar Rajan
  • 556
  • 4
  • 25
  • The error message is saying that the output of the bitwise operation is an `int` and not a `byte`. – jaco0646 Feb 05 '18 at 18:46
  • 1
    True, I realized the type mismatch. Bit operations involve promotion to int. Would be even more handy to find without Error or Exception, Sometimes there may not be one. – Sundar Rajan Feb 05 '18 at 18:58
  • 1
    In [java repl](http://www.javarepl.com/term.html) use the `:type` command, e.g. `:type 5<<-1`. – jaco0646 Feb 06 '18 at 15:10

2 Answers2

16

Just figured out it can be solved by setting the feedback mode.

/set feedback verbose

Reference https://docs.oracle.com/javase/9/jshell/feedback-modes.htm

Now can easily find the type of an expression or variable in the response.

jshell> 5<<-1
$15 ==> -2147483648
|  created scratch variable $15 : int

The mode can be reset by using the command

/set feedback normal

and the current mode can be queried by simply calling

/set feedback
Sundar Rajan
  • 556
  • 4
  • 25
4

I found an explicit way to do this (I'm running with JDK11) using the /vars command

|  Welcome to JShell -- Version 11
|  For an introduction type: /help intro

jshell> 5<<-1
$1 ==> -2147483648

jshell> /vars
|    int $1 = -2147483648
Karl Horton
  • 539
  • 5
  • 7