CHAPTER 2
Getting Started with Java Programming

“If a craftsman wants to do good work, he must first sharpen his tools.”

—Ancient Chinese proverb

2.1 Downloading and Installing Java

Let's get started with Java programming. First, you will need to download the latest Java software from the Oracle web site, as shown in Figure 2.1 (www.oracle.com/technetwork/java/javase/downloads/index.html). There are three download choices: JDK, Server JRE, and JRE. The server JRE and JRE are for running the Java programs only; since you will need to compile Java programs in this book, you need to download the JDK software package. Just follow the instructions on the web site to download and install the Java SE JDK on your computer.

Image described by caption and surrounding text.

Figure 2.1: The Java SE download web site

After installation, you will need to set up a few environmental variables, such as PATH and JAVA_HOME. Environment variables help programs know which folder to install files in, where to store temporary files, where to find user profile settings, and so on. To set up the environmental variables in Windows, go to Control Panel ➪ Advanced System Settings ➪ Environment Variables. In the section System Variables, find the PATH environment variable and double-click it to edit it. For example, if your Java JDK installation directory is C:Program FilesJavajdk-10.0.2in, then you just append a semicolon to the end, as in C:Program FilesJavajdk-10.0.2in;. The semicolon here is used to separate different PATH variables. Also in the section System Variables, find the JAVA_HOME environment variable and double-click it to edit it. Change its value to C:Program FilesJavajdk-10.0.2, as shown in Figure 2.2.

Image described by caption and surrounding text.

Figure 2.2: The Advanced tab of the System Properties window (top left); the Environmental Variables window (top right); and setting up the PATH (bottom, left) and JAVA_HOME (bottom right) variables

For more details of setting up Java environment variables, please visit https://www.java.com/en/download/help/path.xml.

To set up Java environmental variables in Linux/Unix and macOS, you will need to edit your shell startup scripts. For example, if your Java JDK is installed in the /usr/local/jdk-10.0.2/ directory, in the Bash shell, you can edit the startup file (~/.bashrc) like this:

JAVA_HOME = /usr/local/jdk-10.0.2/
export JAVA_HOME
 
PATH=/usr/local/jdk-10.0.2/bin:$PATH 
export PATH

Save and close the file, and type in the following command to load the startup file:

 ./.profile

If you find Java installation difficult, Figure 2.3 shows an intuitive and simple Java installation guide from Nanyang Technological University in Singapore (www.ntu.edu.sg/home/ehchua/programming/howto/JDK_HowTo.html).

Image described by caption and surrounding text.

Figure 2.3: An intuitive and simple Java SE installation guide from Nanyang Technological University in Singapore

Once the Java JDK has been installed properly, you can check the Java version from the Windows command prompt by typing java –version, as shown in Figure 2.4 (top). You can invoke the command prompt in Windows by choosing Start ➪ Run and typing cmd. You can also check the Java compiler by typing javac, as shown in Figure 2.4 (bottom).

Image described by caption and surrounding text.

Figure 2.4: The commands to check the Java version (top) and to test the Java compiler (bottom)

2.2 Java IDEs

As you do with any programming language, to write a Java program you need a good integrated development environment (IDE), which can make programming much easier. There are many good options, and here I will introduce a few popular ones.

The first is Notepad++, shown in Figure 2.5. Notepad++ is an open source text editor that supports many programming languages, including Java. It supports opening multiple Java files, color-coding the Java keywords, and displaying line numbers. It also supports code folding. Text editors are lightweight IDEs and do not have all the functions of full IDEs. But they are much simpler to use.

Image described by caption and surrounding text.

Figure 2.5: The Notepad++ text editor

The following is the download link for Notepad++:

https://notepad-plus-plus.org/download/v7.5.8.html

Other popular text editors include the following:

Another option is IntelliJ IDEA, which is a fully functional, powerful, dedicated Java IDE. IntelliJ IDEA is also relatively easy to use; see Figure 2.6. Compared to text editors, IntelliJ IDEA comes with many powerful features, such as smart completion, data flow analysis, language injection, inspections, and quick fixes. It also has many built-in developer tools, such as version control, a decompiler, an application server, and build tools such as Maven, Gradle, Ant, and others.

Image described by caption and surrounding text.

Figure 2.6: The IntelliJ IDEA Java IDE

The following is the download link for IntelliJ IDEA:

https://www.jetbrains.com/idea/

Another option is Eclipse, which is a powerful IDE that supports Java and many other programming languages such as C and C++. But for beginners, Eclipse might look daunting, with its complex user interface and sophisticated configurations, as shown in Figure 2.7.

Image described by caption and surrounding text.

Figure 2.7: The Eclipse Java IDE

The following is the download link for Eclipse:

www.eclipse.org/downloads/packages/release/mars/r/eclipse-ide-java-developers

Last but not least, another option is NetBeans, which can be downloaded with the JDK as a bundle. So, you will not need to download the JDK software separately. NetBeans also supports drag-and-drop graphical user interface (GUI) components, which make it easier to develop Windows applications; see Figure 2.8.

Image described by caption and surrounding text.

Figure 2.8: The NetBeans Java IDE

The following is the download link for NetBeans:

https://netbeans.apache.org/download/index.html

For beginners, I recommend starting with a text editor, such as Notepad++, as you gain more and more experience and then moving on to a Java IDE.

2.3 Java Hello World Program

A computer program is essentially a collection of statements (instructions) that can be executed by a computer automatically. To create a Java program, first you need to create the Java source code, which is a text file with .java as the extension name. The source code contains statements, which are lines of code that perform some actions. Second, you need to compile the source code into bytecode, a machine-understandable binary file with .class as the extension name, which can then be executed within Java runtime environments (JREs). Java's platform independence is achieved by installing the JRE on every operating system. The JRE handles the differences of various operating systems and provides a common platform for the bytecode to run. Therefore, the same bytecode can run on all JREs and give you the same result, irrespective of what the underlying operating system is.

Example 2.1 shows a simple Java program named HelloWorld.java, which just prints Hello World! to your screen.

In Java, every program consists of at least one class, and the source code file name (including the case) should be exactly the same as the class name, or it should be the name of the main class when there is more than one class.

Like C/C++, Java uses braces, { and }, to group blocks of codes, and it uses // to mark single-line comments and /* */ for multiple-line comments. Here's an example of a single-line comment:

//This is a single line comment

Here's an example of a multiple-line comment:

/*
   This is a multiple line comment 
   Where you can write multiple lines
*/

Every Java application program (except for Java applets) has one, and only one, public static void main(String [] args) method. For the main() method, the keyword public means it is accessible to other Java classes, static means it can be invoked without using any object, void means it does not return any value, and args is a String type array variable, which saves all the parameters typed at the command line. The main() method should always be static and public. In Java, each line that ends with a semicolon (;) is called a statement; that is, it's an action that is asking the computer to do something. In this example, there is only one statement:

System.out.println();

This is a Java statement for printing messages on the screen. The System.out.println() statement is just an object-oriented way of saying call the println() method, which is a method (or function) of the out object in the System class. System.out is the standard output (your computer screen) object. Similarly, there is also System.in, the standard input (your keyboard) object; System.err, the standard error object; and so on.

Every Java method or class belongs to a package. The default package is java.lang.*, which does not need to be explicitly imported, as shown in the previous example. But if you are using any methods or classes that belong to other packages, they need to be imported at the beginning of the program. In the next chapter's examples, you will use the java.text.* and java.util.* packages. To run the HelloWorld.java program, first use your favorite text editor or IDE to type in the previous code and save it in a text file named HelloWorld.java. Figure 2.9 shows how to create the HelloWorld.java program using Notepad++ and save the file as a Java source file (*.java). Remember, the file name must be the same as the class name.

Screen captures depicting HelloWorld.java program in Notepad++ text file and Save As dialog box with HelloWorld Java source file entered as file name.

Figure 2.9: Create the HelloWorld.java program using Notepad++ and save the file as a Java source file. The file name must be the same as the class name.

Then open a Windows command prompt window in the directory where your file is saved and enter the following command to compile it to bytecode:

javac HelloWorld.java 

A file named HelloWorld.class will be generated. Then use the following command to run the bytecode file, as shown in Figure 2.10:

Screen capture depicting Commands to compile and run the HelloWorld.java program marked by arrows: Compile the Java program, Run the Java program, and Output.

Figure 2.10: Commands to compile and run the HelloWorld.java program

java HelloWorld  

Congratulations! You now have your first Java program running. In addition to Notepad++, you can use a Java IDE such as IntelliJ IDEA. In that case, you don't need the Windows command prompt. You can write, compile, and run the Java program within the IDE.

Example 2.2 is an improved version of the previous Java program, named HelloWorld2.java. It will print Hello xxx! on your screen, where xxx is the first parameter that you type at the command line when you run the program. Figure 2.11 shows how to compile and run the HelloWorld2.java program. As explained, Java uses the args String array variable to store the command-line parameters, that is, the text you typed after java HelloWorld2. In this case, the command-line parameters are Perry Xiao; args[0] stores the value Perry, and args[1] stores the value Xiao. Therefore, System.out.println("Hello " + args[0]) should print Hello Perry! on the screen. Here, Java uses the + sign to concatenate two strings.

Screen capture depicting Commands to compile and run the HelloWorldApplication2.java program marked by arrows: Command-line parameters, args[0], and args[1].

Figure 2.11: Commands to compile and run the HelloWorldApplication2.java program

By default, the javac command uses the current directory (also called a folder) for Java source files and compiled class files. To use different directories or folders, you need to specify other options, such as –classpath, sourcepath, –d, –target, and others. The –classpath (or –cp) option specifies where you can find the precompiled Java class files (such as libraries) when you are compiling or running a Java program. The –sourcepath option specifies where you can find the Java source files. The –d option specifies where you want to save the compiled Java class files. The -target option specifies which version of the Java runtime environment you want to target when compiling Java files.

For example, the following command compiles the HelloWorld.java program using the current directory (.), the examples subdirectory, and the libfuns.jar file as the class path. In Windows, Java uses ; to separate different directories, while in Linux, it uses : to separate different directories.

  javac –classpath .;examples;libfuns.jar  HelloWorld.java 

The following command sets the H:examples directory as the source path:

  javac –sourcepath  H:examples  H:examplesHelloWorld.java 

The following command sets the .classes subdirectory as the destination path for the compiled class files:

  javac –d  .classes  HelloWorld.java 

For more details about the javac command options, type javac -help at the Windows command prompt.

2.4 Java Online Compilers

In addition to the text editors and IDEs introduced earlier, there are many online compilers, which means you don't need to download and install the Java JDK or an IDE onto your computer; you can simply write and run Java code from a web browser from your computers, tablets, and even phones.

Figure 2.12 shows a simple-to-use Java online compiler from Tutorialspoint (https://www.tutorialspoint.com/compile_java_online.php). On the left side you write the Java code, and you view the results on the right side. On the top-right side, there are also Fork, Project, Edit, Settings, and Login menus. You can create new projects and share projects. It supports compiling only a single file and supports only Java 8.

Image described by caption and surrounding text.

Figure 2.12: The Java online compiler from Tutorialspoint

Figure 2.13 shows the Codiva Java online compiler (https://www.codiva.io/java#). Codiva is a powerful online compiler. To use Codiva, you will need either to create an account (Figure 2.13A) or to try it without logging in (Figure 2.13B). After login, you will be able to create more projects and see other people's projects (Figure 2.13C), as well as compile and run your project (Figure 2.13D). The best feature of Codiva is autocompilation, which mean that as you are typing, it automatically compiles the code and displays the results. It also has an autocompletion function, which makes writing code much easier and efficient. Codiva also supports multiple projects, files, packages, and Java 8 and 9 but not Java 10 or 11. Besides Java, Codiva supports the C and C++ languages but doesn't offer UI themes or different compiler settings.

Image described by caption and surrounding text.

Figure 2.13: The Codiva Java online compiler: create a Codiva account (A); try Codiva without login (B); manage your project after login (C); and compile and run your project (D)

Figure 2.14 shows the CompileJava.net online compiler (https://www.compilejava.net/). It is a simple compiler, supporting only one Java file, but it does allow you to select different IDE background schemes, as shown in the figure.

Screen capture depicting CompileJava.net online compiler with menu at the right listing colors for different IDE background schemes.

Figure 2.14: The CompileJava.net online compiler

Figure 2.15 shows JDoodle (https://www.jdoodle.com/online-java-compiler), a popular Java online compiler. Unlike other online compilers, JDoodle supports Java 8, 9, and 10, as shown in the figure. You can create an account or use your Google account to log in. After login, you can create new projects and manage all your projects. You can also collaborate with others; see the bottom menu in the figure. In addition to Java, JDoodle supports more than 70 other programming languages.

Image described by caption and surrounding text.

Figure 2.15: The JDoodle Java online compiler

Figure 2.16 shows the Browxy Java online compiler (www.browxy.com/). Browxy used to be popular but is starting to lag behind as others catch up. It has almost no restrictions and supports multiple Java files and networking. As shown in the figure, you can run a Java networking program to get network information. You can learn more about Java networking programming in Chapter 5. Browxy also offers several interesting Java example applications, such as Hello World, Animal Game, Thread Example, and so on. Browxy supports only Java 8.

Image described by caption and surrounding text.

Figure 2.16: The Browxy Java online compiler

Figure 2.17 shows the OnlineGDB Java online compiler (https://www.onlinegdb.com/online_java_compiler). OnlineGDB is another powerful online compiler. A distinctive feature is its online debugger, which allows you to set breakpoints in the code and run the code step-by-step. It also supports code folding and autocompletion, two more features that make writing a complex program easier. You can log in using your Google or Facebook account, and after login, you can create a new project and manage your projects.

Image described by caption and surrounding text.

Figure 2.17: The OnlineGDB Java online compiler

Figure 2.18 shows the Rextester Java online compiler (http://rextester.com/l/java_online_compiler). Rextester stands for Regular Expression Tester. Rextester supports about 30 languages including Java, as shown in the figure (top), and is popular among C# users. Rextester has the best live collaboration support, which allows multiple users to edit the same file, as shown in the figure (bottom). Just click the Live Cooperation button in the page and give a name to your project. Rextester will then generate a unique URL, where multiple users can share and work on the same Java program. There is also a yellow chat box on the right, where users can exchange messages. But Rextester supports only a single Java file and only Java 8.

Image described by caption and surrounding text.

Figure 2.18: The Rextester Java online compiler

Figure 2.19 shows the IDEOne Java online compiler (https://www.ideone.com/). IDEOne claims to be one of the first online compilers. You can edit the code, fork the code (create new code), and download the code, as shown in the figure. It supports more than 60 programming languages, including Java. IDEOne provides an API for compilation as a service, which means you can create your own online IDE using its API.

Image described by caption and surrounding text.

Figure 2.19: The IDEOne Java online compiler

2.5 Java Online Code Converters

Online code converters can translate an application's source code from one programming language into the source code of another programming language. Figure 2.20 shows the Carlosag online code translator (https://www.carlosag.net/tools/codetranslator/), which can translate Java code into C#, VB.NET, and TypeScript code, and vice versa.

Image described by caption and surrounding text.

Figure 2.20: Carlosag online code translation

Figure 2.21 shows the mtSystems C code to Java code translation (https://www.mtsystems.com/). You will need to contact them to convert your C code to Java code, but there is a free online demo, which demonstrates how to convert different types of C code to Java code.

Image described by caption and surrounding text.

Figure 2.21: The mtSystems C code to Java code translation

2.6 Java Free Online Courses and Tutorials

Many free Java resources are available online. Figure 2.22 shows the Java tutorials from Oracle (https://docs.oracle.com/javase/tutorial/index.html). These comprehensive tutorials show you how to create applications in an easy and simple way. Topics include the basics, as well as more advanced topics such as object-oriented programming (OOP), GUIs, networking, and JavaBeans.

Image described by caption and surrounding text.

Figure 2.22: The Java tutorials from Oracle

Figure 2.23 shows the Java courses from Coursera (https://www.coursera.org/specializations/java-programming), one of the best-known online course web sites. Course videos are available in English, Spanish, Russian, Chinese, and French languages, including subtitles. There are many Java courses there.

Image described by caption and surrounding text.

Figure 2.23: The Java courses from Coursera

Figure 2.24 shows the Java courses from Codecademy (https://www.codecademy.com/learn/learn-java), which is another popular place for online courses. Codecademy offers a free Java programming course for beginners. Students can learn the basics of the Java language and work on different projects.

Image described by caption and surrounding text.

Figure 2.24: The Java courses from Codecademy

Figure 2.25 shows the Java courses from Udacity (https://eu.udacity.com/course/java-programming-basics--ud282), which is a for-profit educational organization founded by Sebastian Thrun, David Stavens, and Mike Sokolsky offering massive open online courses (MOOCs). Udacity's motto is “audacious for you, the student.” It originally focused on offering university-style courses but now focuses more on vocational courses for professionals.

Image described by caption and surrounding text.

Figure 2.25: The Java courses from Udacity

Figure 2.26 shows the Java tutorial from LearnJavaOnline (https://www.learnjavaonline.org/), which also comes with a Java online compiler so that you can learn the Java programming and run the code all in the same web site. It offers both basic and advanced Java topics.

Image described by caption and surrounding text.

Figure 2.26: The Java tutorial from LearnJavaOnline

Figure 2.27 shows the Java course for complete beginners from CaveofProgramming (https://courses.caveofprogramming.com/p/java-for-complete-beginners), which was created by John Purcell, a software developer with 14+ years of experience. It is free, and you can choose your schedule for classes as each is self-paced.

Image described by caption and surrounding text.

Figure 2.27: The Java course from CaveofProgramming

Figure 2.28 shows a Java language basics tutorial from IBM (https://www.ibm.com/developerworks/java/tutorials/j-introtojava1/index.html). This is also a good tutorial that covers comprehensive Java language topics.

Image described by caption and surrounding text.

Figure 2.28: The Java language basics tutorial from IBM

For more details about the Java language, please visit the Java API documentation web site.

https://docs.oracle.com/javase/10/docs/api/overview-summary.html

2.7 Java Version Control

For software developers, version control means maintaining a history of the software development. Why do you need version control? Imagine the following scenario. You are working a big project, and you have just added a new function to your program when suddenly it stops compiling. How can you revert it to the previous working version? In another scenario, you are working on a group project with several other developers, and they are all using the same source directory. How do you know who has changed what? Or, how do you prevent the code you have just developed from being overwritten by someone else? The answer is to use version control software—a central storage hub where developers can check files in and out so that a file one user has checked out to work on can't be modified by anyone else until it is checked back in.

The software that handles this function is called a version control system (VCS). You can use either a centralized version control system (CVCS) or a distributed/decentralized version control system (DVCS). A CVCS uses a central server to store all files, but the drawback is that it suffers a single point of failure—when the server is down or the files on the server are corrupted, everything is down and no one can work. Therefore, the DVCS approach is more suitable, especially when the project developers are located in different cities or even different countries. A DVCS not only allows developers to check out the latest snapshot of the directory but also fully mirrors the repository. If the server goes down, then the repository from any developer can be copied to the server to restore it.

One of the most widely used distributed version control systems is Git, which has an emphasis on speed. Git was initially designed and developed by Linus Torvalds, the famous Finnish software engineer who developed the Linux operating system while he was studying at the University of Helsinki in 1991. Torvalds designed Git for Linux kernel development. GitHub is a web-based service for version control using Git. Compared to other version control software, Git has the advantages of being free to use, small and fast, and open source based. It also has implicit backup and good security, is easier to branch, and has no need of powerful hardware.

If you're doing collaborative development and need to implement a DVCS, see Appendix C for a complete tutorial on using Git and GitHub.

2.8 Summary

This chapter showed how to download and install the Java JDK software. It also introduced four popular Java text editors/IDEs and showed how they handle simple Java Hello World programs. Then you looked at some popular Java online compilers, Java online code converters, and some Java free online courses and tutorials. Finally, you learned about software version control and saw how to use Git and GitHub for that purpose.

2.9 Chapter Review Questions

Q2.1.Where can you download the latest Java JDK software? What is the latest version?
Q2.2.For what purpose should you download the Java JDK package, and for what purpose should you download the JRE package?
Q2.3.In the Java HelloWorld program, what do the keywords public, static, and void accomplish?
Q2.4.How do you invoke the Windows command prompt in Windows?
Q2.5.What is the command to compile a Java program?
Q2.6.What is the command to run a Java program?
Q2.7.What are command-line parameters?
Q2.8.Use a table to compare different Java online compilers, and indicate whether they support features such as single file, multiple files, create projects, different Java versions, debugging, and so on.
Q2.9.Find a piece of code written in another programming language, and use a code converter to convert it to Java.
Q2.10.Use a table to compare different Java online courses or tutorials, and indicate whether they are free, have videos, are self-paced or fixed date and time, and so on.
Q2.11.What is software version control, and why do you need it?
Q2.12.What are Git and GitHub?
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset