Book Image

Java 9 Programming By Example

By : Peter Verhas
Book Image

Java 9 Programming By Example

By: Peter Verhas

Overview of this book

This 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.
Table of Contents (17 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Using an IDE


Integrated development environments are outstanding tools that help the development by offloading the mechanical tasks from the developer's shoulders. They recognize many of the programming errors as we type the code, help us find the needed library methods, display the documentation of the libraries, and provide extra tools for style checking, debugging, and so on.

In this section, we will look at some IDEs and how to leverage the functions they provide.

To get an IDE, you will have to download and install it. It does not come with the Java development tools because they are not part of the language environment. But, don't worry. They can be downloaded free of charge and are easy to install. They may be more complex to start up than a notepad editor, but even after a few hours of work, they will pay back the time you devote to learning them. After all, it is not without reason that no developer is coding Java in notepad or vi.

The three topmost IDEs are NetBeans, Eclipse, and IntelliJ. All are available in community versions, which means that you need not pay for them. IntelliJ has a full version that you can also buy. The community edition will be usable for learning the language. In case you do not like IntelliJ, you can use Eclipse or NetBeans. These are all free of charge. Personally, I use the IntelliJ community edition for most of my projects and the screen samples that show an IDE in this book will feature this IDE. But, it does not necessarily mean that you have to stick to this IDE.

Note

In the developer community, there are topics that can be heavily debated. These topics are about opinions. Were they about facts the debate would easily be soon over. One such topic is: "Which is the best IDE?" It is a matter of taste. There is no definite answer. If you learn how to use one, you will like that and you will be reluctant to learn another one, unless you see that the other one is so much better. That is the reason developers love the IDE they use (or just hate, depending on their personality), but they keep using the same IDE usually for a long time. There is no best IDE.

To download the IDE of your choice, you can visit either one of the following websites:

NetBeans

NetBeans is supported by Oracle and is continuously developed. It contains components, such as the NetBeans profiler, that became part of the Oracle Java distribution. You may notice that when you start Visual VM and start the profiling, the Java process started has netbeans in its name.

Generally, NetBeans is a framework to develop rich client applications and the IDE is only one application of the many that are built on top of the framework. It supports many languages, not only Java. You can develop PHP, C, or JavaScript code using NetBeans and have similar services for Java. For the support of different languages, you can download plugins or a special version of NetBeans. These special versions are available from the download page of the IDE and they are nothing more than the basic IDE with some preconfigured plugins. In the C package, the developers configure the plugins that are needed when you want to develop C; in the PHP version, they plugin for PHP.

Eclipse

Eclipse is supported by IBM. Similar to NetBeans, it is also a platform for rich client application and it is built around the OSGi container architecture, which itself is a topic that can fill a book like this. Most of the developers use Eclipse and, almost exclusively, it is the choice when developers create code for the IBM WebSphere application server. The Eclipse special version contains a developer version of WebSphere.

Eclipse also has plugins to support different programming languages and also has different variations similar to NetBeans. The variations are plugins prepackaged with the basic IDE.

IntelliJ

The last one in the preceding enumeration is IntelliJ. This IDE is the only one that does not want to be a framework. IntelliJ is an IDE. It also has plugins, but most of the plugins that you will need to download to use in NetBeans or Eclipse are preconfigured. When you want to use some more advanced plugin, it may however be something you have to pay for, which should not be a problem when you are doing professional, paid work, should it? These things are not that expensive. For learning the subjects in this book, you will not need any plugin that is not in the community edition. As in this book, I will develop the samples using IntelliJ and I recommend that you follow me during your learning experience.

Note

I want to emphasize that the examples in this book are independent of the actual IDE to be used. You can follow the book using NetBeans, Eclipse, or even Emacs, notepad, or vi.

IDE services

Integrated development environments provide us with services. The most basic service is that you can edit files with them, but they also help build the code, find bugs, run the code, deploy to the application server in development mode, debug, and so on. In the following sections, we will look at these features. I will not give an exact and precise introduction on how to use one or the other IDE. A book like this is not a good medium for such a tutorial.

IDEs differ on menu placement, keyboard shortcuts, and they may even change as newer versions are released. It is best to look at the actual IDE tutorial video or online help. Their features, on the other hand, are very similar. IntelliJ has the video documentation at https://www.jetbrains.com/idea/documentation/.

IDE screen structure

The different IDEs look similar, and have the same screen structure more or less. In the following screenshot, you can see an IntelliJ IDE:

On the left side, you can see the file structure of a Java project. A Java project typically contains many files in different directories which we will discuss in the next chapter. The simple HelloWorld application contains a pom.xml project description file. This file is needed for the Maven build tool, which is also a topic for the next chapter. For now, you should only know that it is a file that describes the project structure for maven. The IDE also keeps track of some administrative data for itself. It is stored in HelloWorld.iml. The main program file is stored in the src/main/java directory and named HelloWorld.java.

On the right side, you can see the files. In the screenshot, we have only one file opened. In case there is more than one file opened, then there are tabs-one for each file. Now, the active file is HelloWorld.java that can be edited in the source code editor.

Editing files

When editing, you can type in characters or delete characters, words, and lines, but this is something that all editors can do. IDEs offer extra. IDEs analyze the source code and format it, which, in turn, automatically indents the lines. It also continuously compiles the code in the background while you edit it and if there is some syntax error, then it underlines it with a red waiving line. When you fix the error, the red underlining disappears.

The editor also automatically gives suggestions for further characters as you type. You can ignore the window that pops up and continue typing. However, many times, it is easier to stop after a character and use the up and down arrows to select the word that needs finishing before pressing Enter: the word will be inserted into the source code automatically.

In the screenshot, you can see that I wrote System.o and the editor immediately suggested that I wanted to write out. The other alternatives are the other static fields and methods that are in the class System and which contain the letter o.

The IDE editor gives you hints not only when it can type for you, but also when it cannot type instead of you. In the screenshot, the IDE tells you to type some expression as argument to the println()method that is boolean, char, int, and so on. The IDE has absolutely no idea what to type there. You have to construct the expression. Still, it can tell you that it needs to be of a certain type.

It is not only the built-in types that the editor knows. The editor integrated with the JDK continuously scans the source files and knows what classes, methods, and fields are there in the source code which are usable at the place of editing.

This knowledge is also heavily used when you want to rename a method or variable. The old method was to rename the field or method in the source file and then do an exhaustive search for all references to the variable. Using the IDE, the mechanical work is done by it. It knows all the uses of a field or method and automatically replaces the old identifier with the new one. It also recognizes whether a local variable happens to have the same name as the one that we rename, and the IDE only renames those occurrences that are really referring to the one we are renaming.

You can usually do more than just renaming. There are more or less mechanical tasks that programmers call refactoring. These are supported by the IDEs using some keyboard shortcut and context sensitive menu in the editor—right click on the mouse and click Menu.

The IDE also helps you to read the documentation of the libraries and source code as shown in the following image:

Libraries provide Javadoc documentation for the public methods and you should also write Javadoc for your own method. Javadoc documentation is extracted from special comments in the source code and we will learn how to create those in Chapter 4, Mastermind - Creating a Game. These are located in comments in front of the actual method head. As creating compiled documentation is part of the compilation flow, the IDE also knows the documentation and it displays as a hovering box over the method names, class names, or whatever element you want to use in the source file when you position the cursor on the element.

Managing projects

On the left side of the IDE window, you can see the directory structure of the project. The IDE knows the different types of files and shows them in a way that is meaningful from the programming point of view. For example, it does not display Main.java as a filename. Instead, it displays Main and an icon that signals that Main is a class. It can also be an interface still in a file named Main.java but, in that case, the icon will show that this is an interface. This is again done by the IDE continuously scanning and compiling the code.

The files are structured into subdirectories when we develop a Java code. These subdirectories follow the packaging structure of the code. Many times, in Java, we use compound and long package names, and displaying it as a deep and nested directory structure will not be so easy to handle.

Note

Packages are used to group the source files. The source files for classes that are related in some way should go into one package. We will discuss the notion of packages and how to use them in the next chapter

The IDE is capable of showing the package structure instead of the nested directories for those directories of the project that contain source files.

When you move a class or an interface from one package to another, it happens in a similar way as renaming or other refactoring. All references to the class or interface in the source files get renamed to the new package. If a file contains an import statement referring to the class, the name of the class in the statement is corrected. To move a class, you can open the package and use the good old drag and drop.

Package hierarchy is not the only hierarchy displayed in the IDE. The classes are in packages but, at the same time, there is an inheritance hierarchy. Classes may implement interfaces and can extend other classes. The Java IDEs help us by showing type hierarchies where you can navigate across a graphical interface along the inheritance relations.

There is another hierarchy that IDEs can show to help us with development: method call hierarchy. After analyzing the code, the IDE can show us the graph displaying the relations between the methods: which method calls which other methods. Sometimes, this call graph is also important in showing the dependencies of methods on each other.

Build the code and run it

The IDEs usually compile the code for analysis to help us spot syntax errors or undefined classes and methods on the fly. This compilation is usually partial, covering a part of the code, and as it runs all the time, the source code changes and is never actually complete. To create the deployable file, that is, the final deliverable code of the project, a separate build process has to be started. Most of the IDEs have some built-in tool for that, but it's not recommended to use these except for the smallest projects. Professional development projects use Ant, Maven, or Gradle instead. Here is an example of Maven.

The IDEs are prepared to use such an external tool, and they can help us in starting them. This way, the build process can run on the developer machine without starting a new shell window. IDEs can also import the settings from the configuration file of these external build tools to recognize the project structure, where source files are, and what to compile to support the error checking while editing.

The building process usually contains the execution of certain checks on the code. A bunch of the Java source file may compile smoothly and the code may still contain a lot of bugs and may be written in bad style, which will make the project becomes unmaintainable in the long run. To avoid such problems, we will use unit tests and static code analysis tools. These do not guarantee error free code but the chances are much better.

IDEs have plugins to run the static code analysis tools as well as unit tests. Being integrated into the IDE has a huge advantage. When there is any problem identified by the analysis tool, or by some unit tests, the IDE provides an error message that also functions like a link on a web page. If you click on the message, usually blue and underlined, exactly like on a web page, the editor opens the problematic file and places the cursor where the issue is.

Debugging Java

Developing code needs debugging. Java has very good facilities to debug code during development. JVM supports debuggers via the Java Platform Debugger Architecture. This lets you execute code in debug mode and JVM will accept external debugger tools to attach to it via a network, or it will try to attach to a debugger depending on command-line options. JDK contains a client, the jdb tool, which contains a debugger; however, it is so cumbersome to use when compared to the graphical client built into the IDEs that I have never heard of anyone using it for real work.

To start a Java program in debug mode so that JVM will accept a debugger client to attach the options to it, execute the following command:

-Xagentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=7896

The Xagentlib option instructs the Java runtime to load the jdwp agent. The part of the option that follows -Xagentlib:jdwp= is interpreted by the debugger agent. These options are as follows:

  • transport: This should specify which transport to use. It can be a shared memory (dt_shmem) socket or a TCP/IP socket transport but, in practice, you will always use the latter. This is specified in the preceding dt_socket sample.
  • server: This specifies if the debugged JVM starts in server mode or client mode. When you start the JVM in server mode, it starts to listen on a socket and accepts the debugger to connect to it. If it is started in client mode, then it tries to connect a debugger that is supposed to be started in server mode, listening on a port. The value of the option is y meaning server mode or n meaning nonserver, a.k.a. client mode.
  • suspend: This can also be y or n. If JVM is started in suspend mode, it will not start the Java code until a debugger is attached to it. If it is started with suspend=n, then the JVM starts and when a debugger attaches, it stops as soon as a breakpoint is reached. If you start a standalone Java application, you will usually start the debugging with suspend=y, which is the default. If you want to debug an application in an application server or servlet-container environment, then it is better to start with suspend=n; otherwise, the server does not start until the debugger attaches to it. Starting the Java process in suspend=y mode in case servlet application is only useful when you want to debug the servlet static initializer code, which is executed when the server is starting up. Without suspend mode, you will be required to attach the debugger very fast. It is better that JVM just waits for you in that situation.
  • address: This should specify the address that JVM communicates with. If the JVM started in client mode, then it will start to connect to this address. If the JVM runs in server mode, then it will accept connections from the debugger on that address. The address may specify only the port. In this case, the IP address is that of the local machine.

The other options the debugger agent may handle are for special cases. For the topics covered in this book, the preceding options are enough.

The following screenshot shows a typical debugging session where we debug the simplest program in IntelliJ IDE:

When you start a program from the IDE in debug mode, all these options are automatically set for you. You can set breakpoint just by clicking on the source code in the editor. You can have a separate form to add, remove, and edit breakpoints. Breakpoints can be attached to specific lines or specific events, like when an exception is thrown. Breakpoints attached to a specific line can also have conditions that tell the debugger to stop the execution of the code only when the condition is true; for example, if a variable has some predefined value.