Java 9 Programming By Example
eBook - ePub

Java 9 Programming By Example

  1. 504 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Java 9 Programming By Example

Book details
Book preview
Table of contents
Citations

About This Book

Get the steps you need to discover the world of Java 9 programming using real-world examplesAbout This Book• We bridge the gap between "learning" and "doing" by providing real-world examples that will improve your software development• Our example-based approach will get you started quickly with software programming, get you up-to-speed with Java 9, and improve your Java skills• This book will show you the best practices of Java coding and improve your productivityWho This Book Is ForThis book is for anyone who wants to learn the Java programming language. You are expected to have some prior programming experience with another language, such as JavaScript or Python, but no knowledge of earlier versions of Java is assumed.What You Will Learn• Compile, package and run a trivial program using a build management tool• Get to know the principles of test-driven development and dependency management• Separate the wiring of multiple modules from the application logic into an application using dependency injection• Benchmark Java execution using Java 9 microbenchmarking• See the workings of the Spring framework and use Java annotations for the configuration• Master the scripting API built into the Java language and use the built-in JavaScript interpreter• Understand static versus dynamic implementation of code and high-order reactive programming in JavaIn DetailThis book gets you started with essential software development easily and quickly, guiding you through Java's different facets. By adopting this approach, you can bridge the gap between learning and doing immediately. You will learn the new features of Java 9 quickly and experience a simple and powerful approach to software development. You will be able to use the Java runtime tools, understand the Java environment, and create Java programs.We then cover more simple examples to build your foundation before diving to some complex data structure problems that will solidify your Java 9 skills. With a special focus on modularity and HTTP 2.0, this book will guide you to get employed as a top notch Java developer.By the end of the book, you will have a firm foundation to continue your journey towards becoming a professional Java developer.Style and approachThroughout this book, our aim is to build Java programs. We will be building multiple applications ranging from simpler ones to more complex ones. Learning by doing has its advantages as you will immediately see the concepts explained in action.

Frequently asked questions

Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes, you can access Java 9 Programming By Example by Peter Verhas in PDF and/or ePUB format, as well as other popular books in Informatique & Programmation en Java. We have over one million books available in our catalogue for you to explore.

Information

Year
2017
ISBN
9781786464514

Optimizing the Sort - Making Code Professional

In this chapter, we will develop the sorting code and make it more general. We want to sort not only an array of Strings. Essentially, we will write a program that can sort anything that is sortable. That way, we will bring the coding to its full extent toward one of the major strengths of Java: abstraction.
Abstraction, however, does not come without a price tag. When you have a class that sorts strings and you accidentally mix an integer or something else, which is not a string, into the sortable data, then the compiler will complain about it: Java does not allow you to put an int into a String array. When the code is more abstract, such programming errors may slip in. We will look at how to handle such exceptional cases catching and throwing Exceptions.
To identify the bugs, we will use unit testing, applying the industry standard JUnit version 4. As JUnit heavily uses annotation, and because annotations are important, you will learn about it a bit.
After that, we will modify the code to use the generics feature of Java that was introduced into the language in version 5. Using that possibility, we will catch the coding error during compilation time, which is better than during run time. The earlier a bug is identified, the cheaper it is to fix.
For the build, we will still use Maven, but this time, we will split the code into small modules. Thus, we will have a multi-module project. We will have separate modules for the definition of a sorting module and for the different implementations. That way, we will look at how classes can extend each other and implement interfaces, and, generally, we will really start to program in the object-oriented way.
We will also discuss Test Driven Development (TDD), and at the end of the section, we will start using the brand new feature of Java 9: module support.
In this chapter, we will cover the following topics:
  • Object-oriented programming principles
  • Unit testing practices
  • Algorithmic complexity and quick sort
  • Exception handling
  • Recursive methods
  • Module support

The general sorting program

In the previous chapter, we implemented a simple sort algorithm. The code can sort elements of a String array. We did this to learn. For practical use, there is a ready cooked sort solution in the JDK that can sort members of collections, which are comparable.
The JDK contains a utility class called Collections. This class contains a static Collections.sort method that is capable of sorting any List that has members that are Comparable. List and Comparable are interfaces defined in the JDK. Thus, if we want to sort a list of Strings, the simplest solution is as follows:
 public class SimplestStringListSortTest { 
@Test
public void canSortStrings() {
ArrayList actualNames = new ArrayList(Arrays.asList(
"Johnson", "Wilson",
"Wilkinson", "Abraham", "Dagobert"
));
Collections.sort(actualNames);
Assert.assertEquals(new ArrayList<String>(Arrays.<String>asList(
"Abraham", "Dagobert", "Johnson", "Wilkinson", "Wilson")), actualNames);
}
}
This code fragment is from a sample JUnit test, which is the reason we have the @Test annotation in front of the method. We will discuss that in detail later. To execute that test, you can issue the following command:
 $ mvn -Dtest=SimplestStringListSortTest test 
This sort implementation, however, does not fit our needs. First of all, because it is there ready (no need to code) and using it does not need anything new that you have not learned in the previous chapters. Except for the annotation in front of the method, there is nothing new in the code that you cannot understand. You may refresh BY turning some pages back, or else consult the oracle online documentation of the JDK (https://docs.oracle.com/javase/8/docs/api/), but that is all. You already know these things.
You may wonder why I wrote the URL for the Java version 8 API to the link. Well, then this is the moment of honesty and truth-when I wrote this book, the Java 9 JDK was not available in its final form. I created most of the examples on my Mac Book using Java 8 and I only tested the features that are Java 9 specific. Support at the moment for Java 9 in the IDEs is not perfect. When you read this book, Java 9 will be available, so you can try and change that one single digit from 8 to 9 in the URL and get to the documentation of the version 9. At the moment, I get HTTP ERROR 404.
Sometimes, you may need the documentation of older versions. You can use 3, 4, 5, 6, or 7 instead of 8 in the URL. Documentation for 3 and 4 is not available to read online, but it can be downloaded. Hopefully, you will never need that anymore. Version 5, perhaps. Version 6 is still widely used at large corporations.
Although you can learn a lot from reading code that was written by other programmers, I do not recommend trying to learn from the JDK source code at this early stage of your studies. These blocks of code are heavily optimized, not meant to be tutorial codes, and old. They do not get rusted during the years, but they were not refactored to follow the coding styles of Java as it matured. At some places, you can find really ugly code in the JDK.
Okay, saying that we need to develop a new sort code because we can learn from it, is a bit contrived. The real reason why we need a sort implementation is that we want something that can sort not only List data types and a List of something that implements the Comparable interface. We want to sort a bunch of objects. All we require is that the bunch containing the objects provides simple methods that are just enough to sort them and have a sorted bunch.
Originally I wanted to use the word collection instead of bunch, but there is a Collection interface in Java and I wanted to emphasize that we are not talking about java.util.Collection of objects.
We also do not want the objects to implement the Comparable interface. If we require the object to implement the Comparable interface, it may violate the Single Responsibility Principle (SRP).
When we design a class, it should model some object class of the real world. We will model the problem space with classes. The class should implement the features that represent the behavior of the objects that it models. If we look at the example of students from the second chapter, then a Student class should represent the features that all students share, and is important from the modeling point of view. A Student object should be able to tell the name of the student, the age, the average scores of the last year, and so on. All students have feet, and certainly each of those feet have size so we may think that a Student class should also implement a method that returns the size of the student's foot (one for the left and one for the right just to be precise), but we do not. We do not, because the size of the foot is irrelevant from the model point of view. If we want to sort a list containing Student objects, the Student class has to implement the Comparable interface. But wait! How do you compare two students? By names, by age. or by the average score of them?
Comparing a student to another is not a feature of the Student. Every class, or for that matter, package, library, or programming unit should have one responsibility and it should implement only that and nothing else. It is not exact. This is not mathematics. Sometimes, it is hard to tell if a feature fits into the responsibility or not. There are simple techniques. For example, in case of a student, you can ask the real person about his name and age, and probably they can also tell you their average score. If you ask one of them to compareTo (another student), as the Comparable interface requires this method, they will probably ask back, but by what attribute? Or how? Or just, what? In such a case, you can suspect that implementing the feature is probably not in the area of that class and this concern; the comparison should be segregated from the implementation of the original class. This is also called Segregation of Concerns, which is closely related to SRP.
JDK developers were aware of this. Collections.sort that sorts a List of Comparable elements is not the only sorting method in this class. There is another that just sorts any List if you pass a second argument and object that implements the Comparator interface and is capable of comparing two elements of List. This is a clean pattern to separate the concerns. In some cases, separating the comparison is not needed. In other cases, it is desirable. The Comparator interface declares one single method that the implementing classes have to provide: compare. If the two arguments are equal, then this method returns 0. If they are different, it should return a negative or a positive int depending on which argument precedes which one.
There are also sort methods in the JDK class, java.util.Arrays. They sort arrays, or only a slice of an array. The method is a good example of method overloading. There are methods with the same name, but with different arguments to sort a whole array for each primitive type, for a slice of each, and also two for object array implementing the Comparable interface, and also for object array to be sorted using Comparator. As you see, there is a whole range of sort implementations available in the JDK, and in 99 percent of the cases, you will not need to implement a sort yourself. The sorts use the same algorithm, a stable merge sort with some optimization.
What we will implement is a general approach that can be used to sort lists, arrays, or just anything that has elements and it is possible to swap any two elements of it; the solution will be able to use the bubble sort that we have already developed and also other algorithms.

A brief overview of various sorting algorithms

There are many different sorting algorithms. As I said, there are simpler and more complex algorithms and, in many cases, more complex algorithms are the ones that run faster. In this chapter, we will implement the bubble sort and quick sort. We have already implemented the bubble sort for strings in the previous chapter, so in this case, the implementation will mainly focus on the recoding for general sortable object sorting. Implementing quick sort will involve a bit of algorithmic interest.
Be warned that this section is here to give you only a taste of algorithmic complexity. It is far from precise and I am in the vain hope that no mathemati...

Table of contents

  1. Title Page
  2. Credits
  3. About the Author
  4. About the Reviewer
  5. www.PacktPub.com
  6. Customer Feedback
  7. Preface
  8. Getting Started with Java 9
  9. The First Real Java Program - Sorting Names
  10. Optimizing the Sort - Making Code Professional
  11. Mastermind - Creating a Game
  12. Extending the Game - Run Parallel, Run Faster
  13. Making Our Game Professional - Do it as a Webapp
  14. Building a Commercial Web Application Using REST
  15. Extending Our E-Commerce Application
  16. Building an Accounting Application Using Reactive Programming
  17. Finalizing Java Knowledge to a Professional Level