Running on Java 24-ea+24-2960 (Preview)
Home of The JavaSpecialists' Newsletter

250Learning Java with jshell

Author: Dr. Heinz M. KabutzDate: 2017-10-26Java Version: 9Category: Language
 

Abstract: Java 9 has changed the way that new programmers can be introduced to Java. No more "public static void main(String[] args)", but instead a beautiful jshell REPL that lets us experiment with Java features without understanding the subtleties of "static".

 

Welcome to the 250th edition of The Java(tm) Specialists' Newsletter, sent to you from a wet and rainy Crete. Soon the kazanis will be fired up to make tsikoudia, a pomace based brandy that is consumed in great volumes on Crete. Usually the owners of the kazani invite their friends to celebrate the fresh produce. It is a jovial time, with lots of good food, drink and company. The frozen stuff we feed tourists cannot compare to drinking it straight out of the kazani. The months from October to March are some of the finest to visit our Island of Crete. The weather is not too hot and the food improves as the wild herbs sprout. October is a good time to reflect on the year and to consider what can still be achieved in the next two months. Perhaps start a good exercise plan? Improve your diet? Learn something new? Finish answering all those emails?

javaspecialists.teachable.com: Please visit our new self-study course catalog to see how you can upskill your Java knowledge.

Learning Java with jshell

I pity any poor soul that needs to learn Java nowadays. Back when I did, all you needed was Bruce Eckel's Thinking in Java [ISBN 0131872486] , a masterpiece that contained everything. Eckel made it available for free PDF download, so we could (and did once) print it out. I think the strategy paid off. It wasn't cost effective to print, since the toner and paper would be more than to just buy it from the book store. I used his book as a basis for my first introductory Java course and thus bought hundreds of bound copies. Java was also quick and easy to learn. One week was all it took and that included such esoteric topics as reflection, serialization and JDBC.

Recently, a friend asked me to review an introductory Java book. Over 1000 pages of heft. I imagined the horror if one of my four children brought that home from a beginner's programming course. I would not blame them if they never wanted to write a line of code. It started, as all "good" Java books do, with a detailed explanation of public static void main(String[] args). Phew! I was flying whilst reading the book on my computer. The person next to me kept on glancing at me as I would mumble "no, no, no, no, no".

My niece in South Africa will be learning Java programming next year. I helped three of my nephews get started in Java and they all are doing splendidly. Only qualm I have is that they became too good at it and now consider programming as "beneath them". Not my fault though, they are all just a bit too smart for human consumption, with doctors as parents. Still, it is 2017 - do we really want to be starting newbies off on a diet of public static void main(String[] args)? That's like asking someone to do 50 pull-ups before they can join the spin class.

I run at least one mile every day. Yes, neither snow, hail, 48 celsius heat waves nor rattlesnakes stop me. During my runs in Bucharest last week, I spent a lot of time thinking about how I would introduce a complete beginner to Java. Someone who had never had the joy of a segmentation violation due to a null pointer. My first thought was to take the best intro Java books, such as Thinking in Java [ISBN 0131872486] , Core Java [ISBN 0134177304] , Java: How to Program [ISBN 0134743350] , Head First Java [ISBN 0596009208] , etc. and create an introductory course from this. However, even though Horstmann and Deitel have kept up with the developments in the Java language, their books most likely would still contain too much baggage from previous versions.

Instead I started thinking - what if I were to record a course for complete beginners? If I remember back on how little I knew when I started coding? How would I like to explore programming? Since I had my professional DPA microphones with me on the trip, I started recording at Bucharest Airport and continued at Athens Elefterios Venizelos Airport. You can hear the faint noise of a busy airport in the background, but luckily my DPA hides most of that.

My new course is not for you. It is for people who have no experience at all in programming. My mother recently retired from running a factory in South Africa. She signed up. She is determined to learn how programming works.

How does it work? Well, we start with the absolute basics. Instead of going to the horror of public static void main(String[] args), we fire up Java 9 and then launch jshell. We start with simple numbers, such as: 4 + 5. We explain how to multiply in Java. Yes, it's the "*" character, and "x" won't work. Things that we all take for granted, because we've seen them so many times. I spend an entire lesson on the semicolon, explaining that it was most likely chosen due to the position on the US keyboard layout. On European keyboards the semicolon is harder to get to, which explains why Scala, invented in Europe, shuns it.

After numbers, I showed Strings and variables. I'm sure the other people in the Aegean Lounge were wondering what I'm up to.

if-else was a bit tricky to get right with jshell. After you type if, the REPL does not know that an else is coming, so it simply completes.

When I first saw jshell, I was skeptical it could be used for learning Java. However, with a bit of care, I think it might work. I've recorded the first section of the course and it is available for free on my JavaSpecialists Teachable Platform. I realize that if you're reading my The Java(tm) Specialists' Newsletter, you would not get much from this course. But perhaps your friends or family could benefit from it?

Some Java 8 and 9 Tips

Java 8 introduced a new way to create a concurrent hash set. In Java 6 and 7, we would wrap the ConcurrentHashMap with a converter to a Set, like so:

    Set<Integer> setJava7 = Collections.newSetFromMap(new ConcurrentHashMap<>());

But since Java 8, we have a better method built into ConcurrentHashMap directly:

    Set<Integer> setJava8 = ConcurrentHashMap.newKeySet();

Also in Java 9 we now finally have the ability to transfer from an InputStream to an OutputStream, just as you thought that IO was going out of vogue. We can thus write a nice echo server in just a few lines. Let's do it in jshell. Fire it up and type:

    new ServerSocket(8080)

This should produce output that looks like this, where $1 is the name of the variable representing our ServerSocket

$1 ==> ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8080]

Next we type

$1.accept()

This will block, waiting for a connection. In another window, connect to the open socket on port 8080 using telnet, thus telnet localhost 8080. When you do, jshell should return with output that looks something like this:

$2 ==> Socket[addr=/0:0:0:0:0:0:0:1,port=61621,localport=8080]

Like before, the $2 is the variable representing our socket. We now use the new Java 9 transferTo() method to set up a super simple "Echo Server":

$2.getInputStream().transferTo($2.getOutputStream())

Our work is done! You can type text into the telnet session and it will get echoed back to you. In jshell, we didn't need semicolons nor exception handling. If we wanted to be a bit more fancy, we could declare variables and do everything in a try-with-resource block, for example:

try (ServerSocket ss = new ServerSocket(8080);
    Socket s = ss.accept();
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream()) {
  in.transferTo(out);
}

However, this has some gotchas at the moment in Java 9.0.1. You can't simply copy and paste that into jshell, as it blocks when we call ss.accept() and loses some of the text. You can put the lines above into a file called echoserver.jsh and then launch jshell, sending it that output, like so:

jshell < echoserver.jsh

You can also type the lines into jshell one at a time, but that is a bit tedious.

That's it for this month. I have been busy this year, from speaking at 25 events around the world (not all listed yet), to running a dozen webinars including Heinz's Happy Hour, to producing tutorials and courses for Java. I've not written as many editions of The Java(tm) Specialists' Newsletter as I wanted to, but there is plenty else for you to dig your teeth into, such as a self-study course on how to write non-blocking IO using Java NIO and some nice Java 9 features.

Feedback is always welcome :-)

Kind regards from Crete

Heinz

 

Comments

We are always happy to receive comments from our readers. Feel free to send me a comment via email or discuss the newsletter in our JavaSpecialists Slack Channel (Get an invite here)

When you load these comments, you'll be connected to Disqus. Privacy Statement.

Related Articles

Browse the Newsletter Archive

About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack '23

Superpack '23 Our entire Java Specialists Training in one huge bundle more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...