DEV Community

Sjue Bsjs
Sjue Bsjs

Posted on

The Java Programming Environment

Installing the Java Development Kit

You can download the Java Development Kit from Oracle at https://www.oracle.com/java/technologies/downloads.

Setting Up the JDK

After downloading the JDK, you need to install it and figure out where it was installed - you'll need that information later. If you run Windows or have a Mac, simply launch the setup program and choose the default options. On Linux, uncompress the .tar.gz file to a location of your choice, such as your home directory or /opt. Then set the PATH to the bin subdirectory of the directory into which the JDK was placed, such as /opt/jdk-21.0.4/bin. This is usually achieved by adding a line such as the following to the end of your ~/.bashrc or ~/.bash_profile file:

export PATH=/opt/jdk-21.0.4/bin:$PATH

Here is how you test whether you did it right. Start a terminal window. Type the line

javac --version

and press the Enter key. You should get a display such as this one:

javac 21.0.4

If instead you get a message such as "javac: command not found" or "The name specified is not recognized as an internal or external command, operable program or batch file," then you need to double-check your installation.

It is often useful to know where the JDK is installed on your system. The installation directory is denoted as jdk. For example, when referring to the jdk/bin directory, I mean the directory such as /opt/jdk-17.0.4/bin or C:\Program Files\Java\jdk-21\bin.

On Windows, the Oracle JDK installer adds the directory C:\Program Files\CommonFiles\Oracle\Java\javapath to the PATH environment variable. That directory only contains the javac, javaw, java, and jshell executables. The javaw executable is a Windows-only feature for launching a program without a console window. The other tools in the Java Development Kit can be found in the bin subdirectory of the JDK installation directory. When invoking those programs, either specify the complete path (such as C:\Program Files\Java\jdk-21\bin\javadoc for the javadoc tool), or add the bin subdirectory to the PATH environment variable. One way to achieve this is with the setx command

setx PATH "%PATH%;c:\Program Files\Java\jdk-21\bin"

Open another terminal window for the change to take effect.

Installing Source Files and Documentation

The library source files are delivered in the JDK as a compressed file jdk/lib/src.zip. Unpack that file to get access to the source code. Simply do the following:

  1. Make sure the JDK is installed and the jdk/bin directory is on the executable path.
  2. Make a directory javasrc in your home directory. If you like, you can do this from a terminal window.

mkdir javasrc

  1. Inside the jdk/lib directory, locate the file src.zip.
  2. Unzip the src.zip file into the javasrc directory. In a terminal window, you can execute the commands

cd javasrc
jar xvf jdk/lib/src.zip
cd ..

The src.zip file contains the source code for all public libraries.

You can read the JDK documentation at https://docs.oracle.com/en/java/javase/21/docs/. If you prefer to have an offline version, follow these steps:

  1. Download the documentation zip file from https://www.oracle.com/java/technologies/downloads. It is called jdk-21.0.x_doc-all.zip.
  2. Unzip the file and rename the doc directory into something more descriptive, like jdk-21-docs. If you like, you can do this from the command line:

jar xvf Downloads/jdk-21.0.x_doc-all.zip
mv docs jdk-21-docs

  1. In your browser, navigate to jdk-21-docs/index.html and add this page to your bookmarks.

You should also install the Core Java program examples. You can download them from https://horstmann.com/corejava. The programs are packaged into a zip file corejava.zip. Just unzip them into your home directory. They will be located in a directory corejava. If you like, you can do this from the command line:

jar xvf Downloads/corejava.zip

Using the Command-Line Tools

If your programming experience comes from a development environment such as Microsoft Visual Studio, you are accustomed to a system with a built-in text editor, menus to compile and launch a program, and a debugger. The JDK contains nothing even remotely similar. You do everything by typing in commands in a terminal window. This may sound cumbersome, but it is nevertheless an essential skill. When you first install Java, you will want to troubleshoot your installation before you install a development environment. Moreover, by executing the basic steps
yourself, you gain a better understanding of what a development environment does behind your back.

However, after you have mastered the basic steps of compiling and running Java programs, you will want to use a professional development environment. You will see how to do that in the following section.

Let's get started the hard way: compiling and launching a Java program from the command line.

  1. Open a terminal window.
  2. Go to the corejava/v1ch02/Welcome directory. (The corejava directory is where you installed the source code for the book examples)
  3. Enter the following commands:

javac Welcome.java
java Welcome

In the terminal window, you should see the output below

Welcome to Core Java!
=====================

Congratulations! You have just compiled and run your first Java program.

What happened? The javac program is the Java compiler. It compiles the file Welcome.java into the file Welcome.class. The java program launches the Java virtual machine. It executes the bytecodes that the compiler placed in the class file.
The Welcome program is extremely simple. It merely prints a message to the terminal. You may enjoy looking inside the program below

/**
 * This program displays a greeting for the reader.
 */
 public class Welcome
 {
  public static void main(String[] args)
  {
  String greeting = "Welcome to Core Java!";
  System.out.println(greeting);
  for (int i = 0; i < greeting.length(); i++)
  System.out.print("=");
  System.out.println();
  }
 }

In the age of integrated development environments, many programmers are unfamiliar with running programs in a terminal window. Any number of things can go wrong, leading to frustrating results.

Pay attention to the following points:

  1. If you type in the program by hand, make sure you correctly enter the uppercase and lowercase letters. In particular, the class name is Welcome and not welcome or WELCOME.
  2. The compiler requires a file name (Welcome.java). When you run the program, you specify a class name (Welcome) without a .java or .class extension.
  3. If you get a message such as “Bad command or file name” or “javac: command not found,” go back and double-check your installation, in particular the executable path setting.
  4. If javac reports that it cannot find the file Welcome.java, you should check whether that file is present in the directory. Under Linux, check that you used the correct capitalization for Welcome.java. Under Windows, use the dir command, not the graphical Explorer tool. Some text editors (in particular Notepad) insist on adding an extension .txt to every file's name. If you use Notepad to edit Welcome.java, it will actually save it as Welcome.java.txt. Under the default Windows settings, Explorer conspires with Notepad and hides the .txt extension because it belongs to a “known file type.” In that case, you need to rename the file, or save it again placing quotes around the file name: "Welcome.java".
  5. If you launch your program and get an error message complaining about a java.lang.NoClassDefFoundError, then carefully check the name of the offending class. If you get a complaint about welcome (with a lowercase w), then you should reissue the java Welcome command with an uppercase W. As always, case matters in Java. If you get a complaint about Welcome/java, it means you accidentally typed java Welcome.java. Reissue the command as java Welcome.

Using an Integrated Development Environment

These environments are so powerful and convenient that it simply doesn’t make much sense to labor on without them. Excellent choices are the freely available Eclipse, IntelliJ IDEA, and NetBeans. In this section, you will learn how to get started with Eclipse.

Get started by downloading Eclipse from
https://eclipse.org/downloads. Versions exist for Linux, MacOS X, and Windows. Run the installation program and pick the installation set called “Eclipse IDE for Java Developers.”

Here are the steps to write a program with Eclipse:

  1. After starting Eclipse, select File → New → Project from the menu.
  2. Select “Java Project” from the wizard dialog.
  3. Click the Next button. Uncheck the “Use default location” checkbox. Click on Browse and navigate to the corejava/v1ch02/Welcome directory.
  4. Click the Finish button. The project is now created.
  5. Click on the triangles in the left pane next to the project until you locate the file Welcome.java, and double-click on it. You should now see a pane with the program code.
  6. With the right mouse button, click on the project name (Welcome) in the left pane. Select Run → Run As → Java Application. The program output is displayed in the console pane.

Presumably, this program does not have typos or bugs. (It was only a few lines of code, after all.) Let us suppose, for the sake of argument, that your code occasionally contains a typo (perhaps even a syntax error). Try it out—ruin your file, for example, by changing the capitalization of String as follows:

string greeting = "Welcome to Core Java!";

Note the wiggly line under string. In the tabs below the source code, click on Problems and expand the triangles until you see an error message that complains about an unknown string type. Click on the error message. The cursor moves to the matching line in the edit pane, where you can correct your error. This allows you to fix your errors quickly.

Often, an Eclipse error report is accompanied by a lightbulb icon. Click on the lightbulb to get a list of suggested fixes.

JShell

The JShell program provides a “read-evaluate-print loop,” or REPL. You type a Java expression; JShell evaluates your input, prints the result, and waits for your next input. This is an excellent way to experiment—much faster than writing a complete program in an integrated development environment.

To start JShell, simply type jshell in a terminal window.

JShell starts with a greeting, followed by a prompt:

| Welcome to JShell -- Version 21.0.4
| For an introduction type: /help intro
jshell>

Now type an expression, such as

"Core Java".length()

JShell responds with the result—in this case, the number of characters in the string “Core Java”.

$1 ==> 9

Note that you do not type System.out.println. JShell
automatically prints the value of every expression that you enter.

The $1 in the output indicates that the result is available in further calculations. For example, if you type

5 * $1 - 3

the response is

$2 ==> 42

If you need a variable many times, you can give it a more memorable name. For example,

jshell> var answer = 6 * 7
answer ==> 42

Another useful feature is tab completion. Type

Math.

followed by the Tab key. Because there are so many
completions, you are prompted to hit the Tab key again. You get a list of all methods that you can invoke with the Math class:

jshell> Math.
E IEEEremainder( PI
TAU abs( absExact(
acos( addExact( asin(
atan( atan2( cbrt(
ceil( ceilDiv(
ceilDivExact(
ceilMod( clamp( class
copySign( cos( cosh(
decrementExact( divideExact( exp(
expm1( floor( floorDiv(
floorDivExact( floorMod( fma(
getExponent( hypot(
incrementExact(
log( log10( log1p(
max( min(
multiplyExact(
multiplyFull( multiplyHigh(
negateExact(
nextAfter( nextDown( nextUp(
pow( random() rint(
round( scalb( signum(
sin( sinh( sqrt(
subtractExact( tan( tanh(
toDegrees( toIntExact( toRadians(
ulp( unsignedMultiplyHigh(

Now type l and hit the Tab key again. The method name is completed to log, and you get a shorter list:

jshell> Math.log
log( log10( log1p(

Now you can fill in the rest by hand:

jshell> Math.log10(0.001)
$4 ==> -3.0

To repeat a command, hit the ↑ key until you see the line that you want to reissue or edit. You can move the cursor in the line with the ← and → keys, and add or delete characters. Hit Enter when you are done. For example, hit the ↑ key and replace 0.001 with 1000, then hit Enter:

jshell> Math.log10(1000)
$5 ==> 3.0

You exit JShell with the command

/exit

JShell makes it easy and fun to learn the Java language and library without having to launch a heavy-duty development environment and without fussing with a program and a main method.

Top comments (0)