Chapter 1

Getting Started with Java

To program in Java, you need the Java SE Development Kit (JDK). Therefore, the first section of this chapter provides instructions to download and install it.

Developing a Java program involves writing code, compiling it into bytecode, and running the bytecode. This is a process you will repeat again and again during your career as a Java programmer, and it is crucial that you feel comfortable with it. The main objective of this chapter therefore is to give you the opportunity to experience the process of software development in Java.

As it is important to write code that not only works but that is also easy to read and maintain, this chapter introduces you to Java code conventions. And, since the smart developer uses an integrated development environment (IDE), the last section of this chapter offers advice on Java IDEs.

Downloading and Installing Java

Before you can start compiling and running Java programs, you need to download and install the JDK as well as configure some system environment variables.

You can download the JRE and the JDK for Windows, Linux, and Mac OS X from this Oracle website:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

If you click the Download link on the page, you’ll be redirected to a page that lets you select an installation for your platform: Windows, Linux, Solaris or Mac OS X. The same link also provides the JRE. However, for development you need the JDK not only the JRE, which is only good for running compiled Java classes. The JDK includes the JRE.

After downloading the JDK, you need to install it. Installation varies from one operating system to another. These subsections detail the installation process.

Installing on Windows

Installing on Windows is easy. Simply double-click the executable file in you downloaded in Windows Explorer and follow the instructions. Figure 1.1 shows the first dialog of the installation wizard.

Figure 1.1: Installing the JDK 8 on Windows

Installing on Linux

On Linux platforms, the JDK is available in two installation formats.

  • RPM, for Linux platforms that supports the RPM package management system, such as Red Hat and SuSE.
  • Self-extracting package. A compressed file containing packages to be installed.

If you are using the RPM, follow these steps:

1. Become root by using the su command

2. Extract the downloaded file.

3. Change directory to where the downloaded file is located and type:

	chmod a+x rpmFile

where rpmFile is the RPM file.

4. Run the RPM file:

      ./rpmFile

If you are using the self-extracting binary installation, follow these steps.

1. Extract the downloaded file.

2. Use chmod to give the file the execute permissions:

      chmod a+x binFile

Here, binFile is the downloaded bin file for your platform.

3. Change directory to the location where you want the files to be installed.

4. Run the self-extracting binary. Execute the downloaded file with the path prepended to it. For example, if the file is in the current directory, prepend it with "./":

      ./binFile 

Installing on Mac OS X

To install the JDK 8 on Mac OS X, you need an Intel-based computer running OS X 10.8 (Mountain Lion) or later. You also need administrator privileges. Installation is straight-forward.

1. Double-click on the .dmg file you downloaded.

2. In the Finder window that appears, double-click the package icon.

3. On the first window that appears, click Continue.

4. The Installation Type window appears. Click Install.

5. A window appears that says “Installer is trying to install new software. Type your password to allow this.” Enter your Admin password.

6. Click Install Software to start the installation.

Setting System Environment Variables

After you install the JDK, you can start compiling and running Java programs. However, you can only invoke the compiler and the JRE from the location of the javac and java programs or by including the installation path in your command. To make compiling and running programs easier, it is important that you set the PATH environment variable on your computer so that you can invoke javac and java from any directory.

Setting the Path Environment Variable on Windows

To set the PATH environment variable on Windows, do these steps:

1. Click Start, Settings, Control Panel.

2. Double-click System.

3. Select the Advanced tab and then click on Environment Variables.

4. Locate the Path environment variable in the User Variables or System Variables panes. The value of Path is a series of directories separated by semicolons. Now, add the full path to the bin directory of your Java installation directory to the end of the existing value of Path. The directory looks something like:

	C:Program FilesJavajdk1.8.0_<version>in 

5. Click Set, OK, or Apply.

Setting the Path Environment Variable on UNIX and Linux

Setting the path environment variable on these operating systems depends on the shell you use. For the C shell, add the following to the end of your ~/.cshrc file:

set path=(path/to/jdk/bin $path)

where path/to/jdk/bin is the bin directory under your JDK installation directory.

For the Bourne Again shell, add this line to the end of your ~/.bashrc or ~/.bash_profile file:

export PATH=/path/to/jdk/bin:$PATH

Here, path/to/jdk/bin is the bin directory under your JDK installation directory.

Testing the Installation

To confirm that you have installed the JDK correctly, type javac on the command line from any directory on your machine. If you see instructions on how to correctly run javac, then you have successfully installed it. On the other hand, if you can only run javac from the bin directory of the JDK installation directory, your PATH environment variable was not configured properly.

Downloading Java API Documentation

When programming Java, you will invariably use classes from the core libraries. Even seasoned programmers look up the documentation for those libraries when they are coding. Therefore, you should download the documentation from here.

http://www.oracle.com/technetwork/java/javase/downloads/index.html

(You need to scroll down until you see “Java SE 8 Documentation.”)

The API documentation is also available online here:

http://download.oracle.com/javase/8/docs/api

Your First Java Program

This section highlights steps in Java development: writing a program, compiling it into bytecode and running the bytecode.

Writing a Java Program

You can use any text editor to write a Java program. Open a text editor and write the code in Listing 1.1. Alternatively, if you have downloaded the program examples accompanying this book, you can simply copy it to your text editor.

Listing 1.1: A simple Java program

class MyFirstProgram {
    public static void main(String[] args) {
        System.out.println("Java rocks.");
    }
}

For now, suffice it to say that Java code must reside in a class. Also, make sure you save the code in Listing 1.1 as a MyFirstProgram.java file. All Java source files must have java extension.

Compiling Your Java Program

You use the javac program in the bin directory of your JDK installation directory to compile Java programs. Assuming you have edited the PATH environment variable in your computer (if not, see the section “Downloading and Installing Java”), you should be able to invoke javac from any directory. To compile the MyFirstProgram class in Listing 1.1, do the following:

1. Open a terminal or a command prompt and change directory to the directory where the MyFirstProgram.java file was saved in.

2. Type the following command.

	javac MyFirstProgram.java

If everything goes well, javac will create a file named MyFirstProgram.class in your working directory.

Note

The javac tool has more features that you can use by passing options. For example, you can tell it where you want the generated class file to be created. Appendix A, “javac” discusses javac in clear detail.

Running Your Java Program

To run your Java program, use the java program that is part of the JDK. Again, having added the PATH environment variable, you should be able to invoke java from any directory. From your working directory, type the following and press Enter.

java MyFirstProgram

Note that you do not include the class extension when running a Java program.

You will see the following on your console.

Java rocks.

Congratulations. You have successfully written your first Java program. Since the sole aim of this chapter is to familiarize yourself with the writing and compiling process, I will not explain how the program works.

You can also pass arguments to a Java program. For example, if you have a class named Calculator and you want to pass two arguments to it, you can do it like this:

java Calculator arg-1 arg-2

Here, arg-1 is the first argument and arg-2 the second. You can pass as many arguments as you want. The java program will then make these arguments available to your Java program as an array of strings. You’ll learn to handle arguments in Chapter 6, “Arrays.”

Note

The java tool is an advanced program that you can configure by passing options. For instance, you can set the amount of memory allocated to it. Appendix B, “java” explains these options.

Note

The java tool can also be used to run a Java class that is packaged in a jar file. Check the section “Setting an Application’s Entry Point” in Appendix C, “jar.”

Java Code Conventions

It is important to write correct Java programs that run. However, it is also crucial to write programs that are easy to read and maintain. It is believed that eighty percent of the lifetime cost of a piece of software is spent on maintenance. Also, the turnover of programmers is high, thus it is very likely that someone other than you will maintain your code during its lifetime. Whoever inherits your code will appreciate clear and easy-to-read program sources.

Using consistent code conventions is one way to make your code easier to read. (Other ways include proper code organization and sufficient commenting.) Code conventions include file names, file organization, indentation, comments, declaration, statements, white space and naming conventions.

A class declaration starts with the keyword class followed by a class name and the opening brace {. You can place the opening brace on the same line as the class name, as shown in Listing 1.1, or you can write it on the next line, as demonstrated in Listing 1.2.

Listing 1.2: MyFirstProgram written using a different code convention

class MyFirstProgram
{
    public static void main(String[] args) 
    {
        System.out.println("Java rocks.");
    }
}

The code in Listing 1.2 is as good as the one in Listing 1.1. It is just that the class has been written using a different convention. You should adopt a consistent style for all your program elements. It is up to you to define your own code conventions, however Sun Microsystems has published a document that outlines standards that its employees should follow. The document can be viewed here. (Of course, the document is now part of Oracle.com)

http://www.oracle.com/technetwork/java/codeconvtoc-136057.html

Program samples in this book will follow the recommended conventions outlined in this document. I’d also like to encourage you to develop the habit of following these conventions since the first day of your programming career, so that writing clear code comes naturally at a later stage.

Your first lesson on styles is about indentation. The unit of indentation must be four spaces. If tabs are used in place of spaces, they must be set every eight spaces (not four).

Integrated Development Environments (IDEs)

It is true that you can write Java programs using a text editor. However, an IDE will help. Not only will it check the syntax of your code, an IDE can also auto complete code, debug, and trace your programs. In addition, compilation can happen automatically as you type, and running a Java program is simply a matter of clicking a button. As a result, you will develop in much shorter time.

There used to be dozens of Java IDEs out there, but today these three are the only major players left. Fortunately, the first two are completely free.

  • NetBeans (free and open source)
  • Eclipse (free and open source)
  • IntelliJ IDEA (offers free and paid editions)

The two most popular Java IDEs are NetBeans and Eclipse and the past few years have seen a war between the two to become the number one. NetBeans and Eclipse are both open source projects with strong backers. Sun Microsystems launched NetBeans in 2000 after buying the Czech company Netbeans Ceska Republika. Eclipse was originated by IBM to compete with NetBeans.

Which one is better depends on who you ask, but their popularity has become the impetus that propelled other software makers to give away their IDEs too. Even Microsoft, whose .NET technology is Java’s most fierce competitor, followed suit by no longer charging for the Express Editions of its Visual Studio.NET.

This book provides a brief tutorial of NetBeans and Eclipse in Appendix D and Appendix E, respectively. Do consider using an IDE because it helps a lot.

Summary

This chapter provided instructions on how to download and install the JDK and helped you write your first Java program. You used a text editor to write the program, used javac to compile it to a class file, and ran the class file with the java tool.

As programs grow in complexity and projects get larger, an IDE will help expedite application development.

..................Content has been hidden....................

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