1

GETTING STARTED

Image

In this chapter, you’ll get started by installing Java, Eclipse, and Android Studio onto your computer, and then you’ll get familiar with some basic Java programming by testing out some commands in the interactive command line shell, JShell.

Java is a powerful, multiplatform programming language that’s free to download and install on Windows, macOS, and Linux. Eclipse, an industry-standard integrated development environment (IDE), is a toolkit for building Java apps quickly and easily. And Android Studio is the development environment for Android mobile apps in Java. It gives you the power to program your own mobile games and apps for phones, tablets, and more.

Java on Windows, macOS, and Linux

One of the great things about Java is that the Java programs you write can run on any other computer that has the Java Virtual Machine (JVM) software (sometimes called the Java Runtime Environment, or JRE) installed. JVM technology allows you to write a program once and run the same code on any operating system (Windows, macOS, Linux, Android, and more).

This sounds like an obvious idea, but most other programming languages require you either to write different code for Windows, macOS, Linux, and smartphones or to compile a separate version for each operating system. The JVM is a runtime environment that makes this unnecessary.

Figure 1-1 shows the same graphical Java app running on Windows, macOS, and Ubuntu Linux.

Image

Figure 1-1: The same Java code running on three different operating systems—Windows, macOS, and Linux!

This simple but powerful concept is one of the reasons Java has been adopted by individuals and businesses worldwide.

Installing Java 8 and 9 for Developers

The Java Development Kit (JDK) is the version of Java for developers or programmers—like you! The JDK gives you the power to write and compile your own Java apps that you can share with your friends, deploy in a business, or run anywhere on almost any device.

We’re going to install both versions 8 and 9 of the JDK. That way, we can gain the benefits of version 8’s widespread use while also accessing version 9’s newest features.

To install JDK 8:

1. Go to http://jdk.java.net/8/.

2. Click the Accept License Agreement radio button.

3. Find the link for your operating system in the list of downloads under JDK, and click it. If your operating system is Windows or Linux, choose the 64-bit version.

4. Open the JDK file from your computer’s Downloads directory and install the JDK.

To install JDK 9, go to http://jdk.java.net/9/ and then repeat steps 2–4 from your JDK 8 installation.

NOTE

For more detailed, step-by-step instructions in video form, you can preview the online course associated with this book for free at http://www.udemy.com/java-the-easy-way/.

That’s all it takes to get your computer ready to compile and run Java programs from the text-based command line or terminal, but we also want to take advantage of Java’s ability to create graphical user interface (GUI) applications like those in Figure 1-1. To tap into Java’s GUI awesomeness, next we’ll install an integrated development environment called Eclipse.

Installing the Eclipse IDE for Java Developers

Eclipse is one of the most popular IDEs for programming in Java. It’s also open source, which means it’s free for both personal and business use, and there’s a thriving open source community continually improving and supporting Eclipse. There are a number of alternative IDEs for Java, but Eclipse is famous for its ease of use in developing Java apps. It’s also pretty easy to install.

To install Eclipse on your computer, go to http://www.eclipse.org/downloads/, download the installer for your operating system (as shown in Figure 1-2), and then run it. The current version as of this writing is Eclipse Oxygen.

Image

Figure 1-2: Download the Eclipse IDE installer for your operating system.

You’ll see a menu like the one in Figure 1-3. Choose Eclipse IDE for Java Developers and click Install. Be careful to choose the Eclipse IDE for Java Developers option and not one of the other options (the Java EE, or Enterprise Edition, doesn’t have some of the features we’ll use in this book).

Installation may take several minutes to complete.

Image

Figure 1-3: Choose Eclipse IDE for Java Developers from the Eclipse installer menu.

Setting Up Eclipse

Let’s get our Eclipse installation configured to look and feel like the professional development environment it is, complete with the WindowBuilder Editor, a coder-friendly color scheme, and easy-to-read fonts.

Start Eclipse by clicking the Eclipse icon. When Eclipse starts, it will usually ask you where you want to store your workspace, which holds all of your Java projects, as shown in Figure 1-4. You can use the default location (on Windows it’s C:Users<YourUserName>eclipse-workspace, on macOS it’s /Users/<YourUserName>/Documents/eclipse-workspace/, and on Linux it’s /home/<YourUserName>/eclipse-workspace/), or you can choose a custom location for your Java workspace folder.

Image

Figure 1-4: Eclipse begins by asking where you would like to store your Java projects.

If you don’t have another preference, use the default eclipse-workspace location. No matter what, remember the location of this folder because this is where all your Java projects will be stored. If you check the box labeled “Use this as the default and do not ask again,” the Eclipse Launcher window won’t pop up every time you start Eclipse. If you plan to use multiple workspaces, you might want to leave the checkbox unchecked so that you can switch between workspaces easily when opening Eclipse.

The first time you run Eclipse, you’ll see a welcome screen. Depending on your version of Eclipse, this screen may include some useful sample projects and tutorials, or it might be simpler. Feel free to click around and explore a bit if you’d like, and when you’re ready to move ahead, close the Welcome tab by clicking the small X at the top.

Installing the WindowBuilder Editor

The most important upgrade we’ll make to Eclipse is to install the WindowBuilder Editor, which allows us to build windowed applications by dragging and dropping GUI elements like buttons, labels, and text fields onto a graphical preview of the app.

Some versions of Eclipse have the WindowBuilder Editor already installed, but we’ll go over the steps to install or update it to make sure you’re ready to build GUI applications starting in Chapter 3.

First, go to http://www.eclipse.org/windowbuilder/ and click Download. On the download page, find the WindowBuilder version that matches your version of Eclipse (for Eclipse Oxygen, that’s version 4.7), right-click or CONTROL-click the corresponding link, and copy the link address, as shown in Figure 1-5.

Image

Figure 1-5: Find the latest WindowBuilder Editor download link and copy the link address.

Next, come back to Eclipse and select Help Install New Software. In the Work with: text box, paste the URL of the WindowBuilder Editor (for Eclipse Oxygen, that’s http://download.eclipse.org/windowbuilder/WB/integration/4.7/), click the Add... button, and enter WB in the Name field in the pop-up, as shown in Figure 1-6.

Click OK, and when the WindowBuilder checkbox appears in the install window, click Select All to install all of the needed WindowBuilder components. Click Next until you are prompted to accept the license agreement, and finally click Finish.

Image

Figure 1-6: Use Eclipse’s Install New Software window to add the WindowBuilder Editor.

The software may take a few minutes to install—you’ll see a progress indicator in the bottom-right corner of Eclipse. When installation completes, you’ll be asked to restart Eclipse. Click Restart Now, and the WindowBuilder installation will be complete.

Next, let’s add a few optional tweaks to make code in Eclipse easier to read by changing the background, text colors, and font.

Customizing Eclipse’s Look and Feel

Now that you’ve installed the required elements, you may also want to customize Eclipse’s appearance. On Windows and Linux, you can access the Preferences menu by going to Window Preferences. On macOS, go to the menu bar and select Eclipse Preferences.

For example, you may want to change the theme (color palette) and the font size used in the text editor. Depending on your monitor’s size and the environment in which you’re programming, your theme and your font size can make a big difference in readability, comfort, and even productivity.

In the Preferences menu, under General Appearance, you’ll see the Theme option. You can choose from favorites such as Classic (light, grayish background with dark fonts) or Dark (black background with brighter, more colorful fonts). I prefer the Dark theme because the font colors are brighter against the dark background and the display can be easier to read on a monitor or projection screen.

Under General Appearance Colors and Fonts, you can change the font size. In the Colors and Fonts pane on the right, choose Basic Text Font and click the Edit button. The Font menu will pop up. Choose a font you can read easily. I prefer Courier New or Consolas. I recommend a font size of 18 to 20 and a font style of Bold. The Font window will display a sample of the selected font, style, and size, as shown in Figure 1-7.

Image

Figure 1-7: The Colors and Fonts preferences menu (left) and the Font preferences menu (right)

Click OK when you’re finished with your selections, and you’ll return to the main Eclipse workspace. You’ll see your preference settings in effect when you begin coding in the Java text editor in Chapter 2.

Installing Android Studio for Mobile App Development

Android Studio is the official Android mobile app development environment. It gives us the ability to design and code mobile apps using Android’s native Java programming language. Like Java and Eclipse, Android Studio is free to download, install, and use. Because of its large size, Android Studio may take from several minutes to several hours to download and install, depending on your internet connection.

To download Android Studio, go to http://developer.android.com/studio/ and click Download Android Studio, as shown in Figure 1-8. Read and agree to the terms and conditions and then click Download Android Studio for <operating system>.

Follow the instructions to complete the installation. The installation process may download additional software development kit (SDK) components, and it could take several more minutes to install once all the components are downloaded.

Image

Figure 1-8: Android Studio is the official Android mobile app development environment.

Getting to Know Java with JShell

Now that we’ve set up our programming environment, let’s test our setup by using JShell, an interactive interpreter for Java. JShell is a great way to start learning how Java works, as it gives you feedback on your code right away. Before Java 9, Java coders had to type a complete program, compile it, and run it to see the result. Now, with JShell, we can type a single line of Java code, such as System.out.println(“Hello, Java!”), press ENTER, and see the output immediately on the screen, as shown in Figure 1-9.

Image

Figure 1-9: JShell in Java 9 allows us to quickly test code in an interactive command line shell.

Any valid Java statement will work in JShell, which makes it a great tool for learning the basics of Java coding, so let’s jump right in!

Running JShell

You should be able to run JShell either from the command line or by setting up a shortcut. Just in case one of those options doesn’t work for you, though, we’ll go over both.

First, you must have JDK 9 installed. You can confirm that JDK 9 is installed by running a command from the command line.

Here’s how to launch the command line interface on Windows, macOS, and Linux:

• On Windows, open the command prompt by going to the Start menu and typing cmd in the Search box. Press ENTER or click the Command Prompt icon.

• On macOS, open the Launchpad and enter terminal in the search box. Click the Terminal app icon.

• On Linux, search for terminal and click the Terminal app icon.

A command prompt window will appear. Enter java -version at the prompt, and Java will tell you which JDK version is installed. You’ll see something like the following output on Windows:

C:UsersPayne> java -version
java version "9-ea"
Java(TM) SE Runtime Environment (build 9-ea+153)
Java HotSpot(TM) 64-Bit Server VM (build 9-ea+153, mixed mode)

Or you’ll see this output on macOS and Linux:

Payne:~ payne$ java -version
java version "1.9.0_33"
Java(TM) SE Runtime Environment (build 1.9.0_33)...

If Java responds with something containing version 9 or version 1.9, as shown here, you’re ready to run JShell. If you’d like to run it from the command line, continue to the next section, “Running JShell from the Command Line.” If you get an earlier version of Java, like 1.8, go back to “Installing Java 8 and 9 for Developers” on page 2 and install JDK 9. If version 9 doesn’t appear on the command line after installing or if you’d prefer to set up a desktop shortcut, skip to “Running JShell from a Shortcut” on page 11.

Running JShell from the Command Line

To run JShell from the command prompt, type jshell and press ENTER. Java will respond with a JShell welcome message and prompt, which look like the following in Windows.

C:UsersPayne> jshell
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro

jshell>

On macOS or Linux, the message and prompt look similar:

Payne:~ payne$ jshell
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro

jshell>

If you get the jshell> prompt, you’re ready to move ahead to “Working with Java Expressions in JShell” on page 12. If the jshell command doesn’t work on your computer after installing JDK 9, try following the steps in the next section.

Running JShell from a Shortcut

If you have any trouble getting JShell to run from the command line, or if you’d prefer to run it from a desktop shortcut, follow these instructions to access JShell directly from the JDK 9 bin folder and set up a shortcut. (The folder name bin is short for binaries, which are programs written in computer language with just 1s and 0s.)

NOTE

Unfortunately, this method doesn’t reliably work for Linux, but you should be able to use the command line method.

You can find JShell in the following directories:

• On Windows, use C:Program FilesJavajdk-9injshell.exe

• On macOS, use /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/jshell

Your JDK folder may be labeled jdk-1.9.x instead of jdk-9, but it will work the same either way. Navigate to the JDK 9 bin folder on your computer and find the JShell file, as shown in Figure 1-10.

You can double-click the JShell file’s icon to run JShell. You can also create a shortcut to run JShell directly from your desktop for convenience:

• On Windows, right-click jshell.exe and select Create Shortcut. Windows will respond with “Windows can’t create a shortcut here. Do you want the shortcut to be placed on the desktop instead?” Click Yes.

• On macOS, CONTROL-click the jshell file and select Make Alias. A file called jshell alias will appear. Drag it to your desktop.

Now, anytime you want to run JShell, simply double-click the icon on your desktop, and you’re ready to code in Java.

Image

Figure 1-10: The JShell program file in the JDK 9 bin folder on Windows (left) and macOS (right)

Working with Java Expressions in JShell

An expression is any combination of values (like numbers or text) and operators that results in another value. An operator performs an operation like addition, subtraction, multiplication, or division. In Java, the symbols we use for these operators are, respectively, +, -, *, and /. Let’s try one out with a simple math expression. At the JShell prompt, type 2+2 and press ENTER:

jshell> 2+2
$1 ==> 4

JShell tells you the answer: the value of the expression 2+2 is 4. The $1 is a temporary variable. JShell creates these variables to store values, and here the variable $1 is storing the value 4 temporarily, in case you want to use it later. If you want to know what value is in a variable, you can enter it in JShell. For example, if you enter $1 now, JShell will tell you $1 is storing the value 4:

jshell> $1
$1 ==> 4

Let’s try another expression. This time, let’s combine two strings of text. Strings are characters between quotation marks that are used to display words, names, and other text. You can use the + operator to combine strings:

jshell> "Your" + "Name"
$3 ==> "YourName"

You’ll see that a different temporary variable is created—in this case, $3. The number after the $ indicates the line of code where the expression was entered. This is my third snippet of code, so JShell is storing "YourName" in the variable $3.

Notice also that Java concatenates, or adds, the two strings, with no space between. If we want a space between two concatenated strings, we have to include it inside double quotes, like this:

jshell> "Your" + " " + "Name"
$4 ==> "Your Name"

Any valid Java expression can be evaluated in JShell, so go ahead and try a few more expressions. To edit a statement you’ve entered, press the up arrow key. JShell will display the last command you typed, allowing you to edit it and press ENTER to run the statement again. Pressing the up arrow more than once will scroll you through the history of previous statements, all the way to the first line you entered.

Declaring Java Variables in JShell

Evaluating expressions with simple values is nice, but you’ll usually want to store values in variables so you can use them later. JShell has been creating temporary variables for us automatically, like $1 and $3 in the previous section, but you can also create, or declare, your own.

Numeric Variables

Let’s create an integer (whole number) variable called x and store the value 42 in it. Java stores whole numbers in variables of the type int, so at the JShell prompt, enter int x = 42:

jshell> int x = 42
x ==> 42

The equal sign (=) is the assignment operator in Java, meaning that it is used to assign a value to a variable. JShell responds, letting us know the variable x contains the value 42. Now, when we want to use that value, we can just call the variable by name. Let’s find out what x * 2 (x times two) equals:

jshell> x * 2
$6 ==> 84

Java uses the asterisk (*) as the symbol for multiplication, and JShell is letting us know that x * 2 is equal to 84. Did we change the value of x, though, by getting its value and multiplying that value by two? Let’s find out by entering x:

jshell> x
x ==> 42

Whew! Our variable x still has the same value, 42. That means we can use the value stored in a variable without changing the variable.

So how would we change the value stored in the variable? We simply use the assignment operator again. Enter x = x + 7 at the JShell prompt:

jshell> x = x + 7
x ==> 49

We’ve replaced the value stored in x by taking the old x value and adding 7 to it. From now on, whenever we ask for the value of x, we’ll get 49, until we change it again. The value of a variable can change, or vary, as often as we need it to—that’s why they’re called variables.

Let’s try a few variables of different types. We’ve seen an integer value, so let’s try a decimal, or floating-point, number. Java stores decimal numbers in variables of the type double (short for double-precision floating point), so create a double called meters and store the decimal value 1.83 in it:

jshell> double meters = 1.83
meters ==> 1.83

Java handles decimal values just as easily as integer values. Let’s do some math and convert meters to centimeters:

jshell> double centimeters = meters * 100
centimeters ==> 183.0

We’ve converted the value in meters to a value in centimeters by multiplying it by 100.

Java handles a few other types of numbers, but int and double values are the most common ones you’ll use. Anytime you come across a new type of variable, feel free to open JShell and play around with different values.

String Variables

The String variable type is used to store strings of text characters. Let’s define a String variable called myName and store a name in it as follows (you can use your name instead of mine):

jshell> String myName = "Bryson Payne"
myName ==> "Bryson Payne"

We use the equal sign assignment operator, like we did with numeric variables.

NOTE

Case matters in Java variable, method, and class names. All-lowercase myname is different from all-uppercase MYNAME, and both of those are different from myName. The convention, or common way of doing things, in Java is to use camel case—capitalizing the first letter of each new word in a name, like myName or thisIsASillyNameButShowsCamelCase, so that the words resemble a camel’s humps. Classes are in camel case and also begin with an uppercase letter.

Now let’s use the value stored in myName. Let’s say you’ve added a certification or earned a degree. Add some characters after your name, as follows:

jshell> myName + ", PhD"
$12 ==> "Bryson Payne, PhD"

Notice that we didn’t use the assignment operator, so the value stored in myName should still be your name without the extra characters.

This time, let’s change the value stored in the variable myName. Add a formal title or greeting to your name, like you would for addressing an envelope or invitation:

jshell> myName = "Dr. " + myName
myName ==> "Dr. Bryson Payne"

JShell shows us the updated value stored in myName. We’ll continue to work with both numeric and text variables in the next section, and you’ll learn to output values to the screen from inside a Java program.

Printing Output in Java

Up to this point, we’ve just been evaluating expressions by entering them into JShell to see their values, but this won’t usually be the case when we start writing actual programs. In a Java program, we won’t see anything echoed back to the screen as we type line by line.

When we want to print something to the screen, we use a print function, like System.out.println(), which prints a line of output to the system console, or your screen. If you’re still using the same JShell window from the previous section, you can print the value we stored in x as follows:

jshell> System.out.println(x)
49

If you get an error, declare a new variable int x = 49 and then run the print statement again.

Notice that this time, JShell doesn’t respond with x ==> 49, because you aren’t asking it to evaluate an expression. The println() statement tells JShell to print only what you’ve placed inside the parentheses, which is the variable x, so JShell simply responds with 49.

Let’s try some output using strings instead. Enter the following statement:

jshell> System.out.println("Hello, " + myName)
Hello, Dr. Bryson Payne

As long as you’ve still got a variable called myName from the previous section, Java will greet you by name.

Whenever you need to print information to the screen for a user to read, the System.out.println() statement will allow you to print exactly what you want to communicate.

JShell Commands

JShell has been so easy to use that you might never want to leave it, but eventually you’ll need to get on with other work, like building exciting desktop and mobile apps in Java. Let’s take a look at the commands that JShell has to offer, including the command to exit JShell.

At the JShell prompt, enter /help:

jshell> /help

JShell will respond with the full list of special commands that it recognizes. We precede each command with the forward slash, /, to indicate that we’re talking to the JShell program directly, not to Java. Here’s a shortened, partial version of the commands JShell recognizes:

|    /list [<name or id>|-all|-start]     -- list the source you have typed
|    /edit <name or id>                   -- edit a source entry referenced by name or id
|    /save [-all|-history|-start] <file>  -- save snippet source to a file
|    /open <file>                         -- open a file as source input
|    /vars [<name or id>|-all|-start]     -- list the declared variables and their values
|    /imports                             -- list the imported items
|    /exit                                -- exit jshell
|    /reset                               -- reset jshell
|    /history                             -- history of what you have typed
|    /help [<command>|<subject>]          -- get information about jshell

Try some of the commands, like /list to see all the source code you’ve typed. You’ll notice that JShell adds semicolons at the ends of lines where needed—the semicolon is how Java separates multiple statements in a program. The /history command shows you what you’ve typed, including commands like /help, /list, and even /history.

When you’re editing regular Java programs in the next chapter and beyond, you’ll be working in files, saving often, and reopening the files when you want to work on them more. In JShell, though, once you close the JShell window, everything you’ve typed is gone for good—unless you save it, that is. Thankfully, JShell includes the ability to save, open, and edit the awesome code snippets you produce. To save code you created in JShell, use the /save command and specify where you’d like to store your file:

jshell> /save ~/Desktop/filename.txt

The tilde (~) means your user directory on your computer, so this command will save all the code you’ve typed since you opened JShell, or since the last /reset, in a file on your desktop. Look at your computer’s desktop screen and you should see the new file.

To open the file again, use the /open command and tell JShell where to find it:

jshell > /open ~/Desktop/filename .txt

JShell will open the file and run the code.

Anytime you write a snippet of code that you’d like to store for later use, use the /save and /open commands to keep your code from one JShell session to the next.

To start a new code snippet, use the /reset command. JShell will remember and save only what you type after the /reset command, but you can reopen a file that you’ve saved anytime. Try the following code for a quick example of saving a file, resetting, and opening a file:

 jshell> /reset
  |  Resetting state.
 jshell> System.out.println("Hello, Java!")
  Hello, Java!
  jshell> System.out.println("My name is Bryson, nice to meet you!")
  My name is Bryson, nice to meet you!
 jshell> /save ~/Desktop/myJava.txt
 jshell> /reset
  |  Resetting state.
 jshell > /open ~/Desktop/myJava.txt
 Hello, Java!
  My name is Bryson, nice to meet you!

NOTE

The numbered circles point out important lines, but they aren’t actually part of the code.

First, you need to reset JShell so that you don’t include any earlier code you might have written before the code you want to save. Once you’ve done that, you can write out your program, which in this case is two print statements , and then save it to your desktop . Even after JShell is reset , the /open command recalls the two lines of code we typed before the /save command and runs them . You can use /edit to change the code and /save again when you’re done.

JShell can store and recall a snippet whether it’s a single line or as many lines as you care to type.

If you’re finished exploring, use the /exit command to close JShell:

jshell> /exit
Goodbye

JShell is even polite when you leave, bidding you a kind goodbye.

What You Learned

In this chapter, you’ve not only installed Java, Eclipse, and AndroidStudio but you’ve also begun learning Java by testing various commands in the JShell interactive shell. JShell is an exciting improvement to the already omnipresent, industry-standard Java, and it’s a great tool for beginners and seasoned developers alike.

For new coders, JShell encourages exploration and removes some of the unnecessary barriers to learning basic Java commands. For experienced programmers, JShell provides a way to rapidly test new pieces of code and see results instantly on the screen. As an educator and coder, I’m excited about what JShell means for the future of Java and for the millions of coders who’ll be able to benefit from this important new set of tools.

You’ve set up your programming environments for Java desktop and mobile apps, and you’ve learned how to test code in JShell. You’ve also gained some experience with a number of programming concepts that you’ll use in the Java desktop and mobile apps that we’ll build in the upcoming chapters. Here’s a quick overview of what you’ve accomplished so far:

• Installing Java JDK 8 and 9

• Installing Eclipse IDE for Java Developers and the WindowBuilder Editor

• Installing Android Studio for mobile app development

• Running JShell from the command line and from the JDK9/bin folder

• Evaluating Java expressions in JShell, including numbers and text

• Declaring integer, decimal, and string variables in Java

• Printing output to the screen using System.out.println()

• Using JShell commands such as /reset, /edit, /save, /open, and /exit

• Saving and opening files from JShell

In the next chapter, we’ll build our first complete Java application, the Hi-Lo guessing game. In the chapters that follow, we’ll create text-based programs, desktop apps, and, finally, Android mobile apps for each of our programs.

Along the way, we’ll use the programming concepts we picked up in JShell, including expressions, variables, output, and more. Whether you’re building your first app or your thousandth, a desktop app for work or a mobile game for fun, these same elements will be part of everything you code.

You’ve got the tools, so let’s jump into Chapter 2 and get started!

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

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