Home of The JavaSpecialists' Newsletter

250Learning Java with jshell

Posted: 2017-10-26Category: LanguageJava Version: 9Dr. Heinz M. Kabutz
 

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?

Birthday and Anniversary Special: Since the 30th November 2017 is the 17th anniversary of our newsletter and my birthday is coming up on the 4th December, we are giving away a 30% discount on our new Data Structures for Java 9 Course (Late 2017 Edition). Whether you are a seasoned Java programmer or you just want to get ready for your next job interview, this course will help you. Besides detailed lectures, the course has over 130 questions that will help you discover what you missed.

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, 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, Core Java, Java: How to Program, Head First Java, 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

 

Related Articles

Browse the Newsletter Archive

About the Author

demo

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

Java Training

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

Java Consulting

Nobody ever wants to call a Java performance consultant, but with first-hand experience repairing and improving commercial Java applications - JavaSpecialists are a good place to start...

Threading Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.