Becoming a Programmer - Getting Started - Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Part I: Getting Started

Hour 1. Becoming a Programmer

THIS HOUR’S TO-DO LIST:

Image Find out the reasons to learn Java.

Image Discover how programs work.

Image Select a Java development tool.

Image Get ready to write your first program.

You’ve probably heard that computer programming is insanely difficult. It requires a degree in computer science, thousands of dollars in computer hardware and software, a keen analytical mind, the patience of Job, and a strong liking for caffeinated drinks.

Aside from the part about caffeine, you heard wrong. Programming is easier than you might think, despite what programmers have been telling people for years to make it easier for us to land high-paying jobs.

This is a great time to learn programming. Countless programming tools are being made available as free downloads on the Web, and thousands of programmers distribute their work as open source so other people can examine how the software was written, fix errors, and contribute improvements. Even in a struggling economy, many companies are hiring programmers.

It’s a great time to learn Java, because the language is everywhere. Billions of mobile devices use Android, an operating system whose apps are all written in Java. If you have an Android phone, you’ve been enjoying the work of Java programmers every time you look up a movie, rock out on Internet radio, or sling an antagonistic avian at a poorly built fortress of swine.

This book aims to teach Java programming to three kinds of people:

1. Nervous novices who never tried to program before

2. Bitter beginners who tried programming but hated it like Lord Voldemort hates orphaned British schoolchildren

3. Impatient intellectuals who know another programming language and want to get up to speed quickly on Java

To achieve this goal, this book uses the English language as much as possible instead of technical jargon or obscure acronyms. All new programming terms are thoroughly explained as they are introduced.

If I’ve succeeded, you will finish this book with enough programming skills to be a danger to yourself and others. You’ll be able to write programs, dive into programming classes and books with more confidence, and learn new languages more easily. (Programming languages, I mean. This book won’t help you master Spanish, Esperanto, or Klingon.)

You also will have skills with Java, the most widely used programming language on the planet.

The first hour of this book provides an introduction to programming and guidance on how to set up your computer so you can use it to write and run Java programs.

Choosing a Language

If you’re comfortable enough with a computer to prepare a nice-looking résumé, balance a checkbook, or share your vacation photos on Facebook, you can create computer software.

The key to learning how to program is to start with the right language. The programming language you choose often depends on the tasks you want to accomplish. Each language has strengths and weaknesses. Back in my day, young whippersnappers, people learned to program with some form of the BASIC language because it was created with beginners in mind.


Note

The BASIC language was invented to be easy for students to learn (the B in BASIC stands for Beginner’s). The downside to using some form of BASIC is that it’s easy to fall into sloppy programming habits with the language.


The most popular language that employs BASIC today is Visual Basic.NET, a programming language and set of development tools from Microsoft that has moved far beyond its roots. VB.NET, as it also is called, is designed for creating programs to run on computers and mobile devices that use a Windows operating system. Another popular language is PHP, a scripting language for creating websites. Other widely used languages you may have heard about are C++, C#, Ruby, and Python.

Each of these languages has its adherents, but the most widely taught in computer science classes at the high school and collegiate level is Java.

The Java programming language, which is offered by Oracle, is more difficult to learn than some languages such as VB.NET and PHP, but it’s a good starting place for several reasons. One advantage of learning Java is that you can use it across a variety of operating systems and computing environments. Java programs can be desktop software, web applications, Internet servers, Android apps, and more on Windows, Mac, Linux, and other operating systems. This versatility is referenced by the ambitious early Java slogan: “Write once, run anywhere.”


Note

Early Java critics had a less flattering slogan: “Write once, debug everywhere.” The language has come a long way, baby, since the first version was released in 1996.


Another important advantage is that Java requires a highly organized approach for getting programs to work. You must be particular about how you write programs and how they store and alter data.

When you start writing Java programs, you might not see the language’s persnickety behavior as an advantage. You might tire of writing a program and having several errors to fix before the program even can be run. The benefit of this extra effort is that the software you create is more reliable, useful, and error-free.

In the coming hours, you learn all of Java’s rules and the pitfalls to avoid.

Java was invented by the Canadian computer scientist James Gosling as a better way to create computer programs. While working at Sun Microsystems in 1991, Gosling was unhappy with the way the C++ programming language was performing on a project, so he created a new language that did the job better. It’s a matter of contentious debate whether Java is superior to other programming languages, of course, but the success of the language demonstrates the strength of his initial design. Three billion devices across the world are running Java, a number so amazing I’m going to repeat it. Three billion! More than 1,000 books have been published about the language since its introduction. (This is my eighteenth.)


Note

C++ is mentioned several times this hour, so you might be tripping over the term wondering what it means—and how it’s pronounced. C++ is pronounced “C-Plus-Plus,” and it’s a programming language developed by Danish computer scientist Bjarne Stroustrop at Bell Laboratories. C++ is an enhancement of the C programming language, hence the Plus-Plus part of the name. Why not just call it C+? The Plus-Plus part is a computer programming joke you’ll understand later in this book.


Regardless of whether Java is the best language, it definitely is a great language to learn. You get your first chance to try out Java during Hour 2, “Writing Your First Program.”

Learning one programming language makes it much easier to learn subsequent languages. Many are similar to each other, so you aren’t starting from scratch when you plunge into a new one. For instance, many C++ and Smalltalk programmers find it fairly easy to learn Java because Java borrows ideas from those earlier languages. Similarly, C# adopts many ideas from Java, so it’s easier to pick up for Java programmers.

Telling the Computer What to Do

A computer program, also called software, is a way to tell a computer to perform a task. Everything that the computer does, from booting up to shutting down, is done by a program. Mac OS X is a program; Minecraft is a program; the driver software that controls your printer is a program; even the dreaded blue screen of death on a crashed Windows PC is a program.

Computer programs are made up of a list of commands the computer handles in a specific order when the program is run. Each command is called a statement.

If your house had its own butler and you were a control freak with a Type-A personality, you could give your servant a detailed set of instructions to follow every day, like this:

Dear Mr. Jeeves,

Please take care of these errands for me while I’m out asking Congress for a bailout:

Item 1: Vacuum the living room.

Item 2: Go to the store.

Item 3: Pick up soy sauce, wasabi, and as many California sushi rolls as you can carry.

Item 4: Return home.

Sincerely, your lord and master,

Bertie Wooster

If you tell a human butler what to do, there’s a certain amount of leeway in how your requests are fulfilled. If California rolls aren’t available, Jeeves could bring Boston rolls home instead.

Computers don’t do leeway. They follow instructions literally. The programs that you write are followed precisely, one instruction at a time.

The following example is a three-line computer program, written in BASIC. Take a look at it, but don’t worry too much about what each line is supposed to mean.

1 PRINT "Hey Tom, it's Bob from the office down the hall."
2 PRINT "It's good to see you buddy, how've you been?"
3 INPUT A$

Translated into English, this program is equivalent to giving a computer the following to-do list:

Dear personal computer,

Item 1: Display the message, “Hey Tom, it’s Bob from the office down the hall.”

Item 2: Ask the question, “It’s good to see you buddy, how’ve you been?”

Item 3: Give the user a chance to answer the question.

Sincerely, your lord and master,

Ima Coder

Each line in a computer program is called a statement. A computer handles each statement in a program in a specific order, in the same way that a cook follows a recipe or Mr. Jeeves the butler follows the orders of Bertie Wooster. In BASIC, the line numbers are used to put the statements in the correct order. Other languages such as Java do not use line numbers, favoring different ways to tell the computer how to run a program.

Figure 1.1 shows the three-line BASIC program in ReadyBASIC, a BASIC interpreter that’s offered on the Web at www.readybasic.com.

Image

FIGURE 1.1 An example of a BASIC program.


Note

The ReadyBASIC interpreter was created using the Java language. Developer Kevin Matz created a Java applet, a type of Java program that runs inside web pages, to interpret statements of BASIC code.

Your browser must be equipped to run Java programs for ReadyBASIC to work. If you have problems, visit Oracle’s Java site at www.java.com to test whether your browser has Java—and install the Java Plug-in if necessary.

You also might need to adjust your Java security settings to allow the program to run. On Windows, run Control Panel, click Java, and then click the Security tab to bring it to the front. You can change your security level or allow specific sites to run Java applets.


Because of the way programs function, you can’t blame the computer when something goes wrong as your program runs. The computer is doing exactly what you told it to do, so the blame for errors usually lies with the programmer.

That’s the bad news. The good news is you can’t do any permanent harm. No computers will be injured as you learn to program in Java.

How Programs Work

The collection of statements that make up a computer program is called its source code.

Most computer programs are written in the same way that you write an email—by typing each statement into a text window. Some programming tools come with their own source code editor and others can be used with any text-editing software.

When you have finished writing a computer program, you save the file to disk. Computer programs often have their own filename extension to indicate what type of file they are. Java programs must have the extension .java, as in Calculator.java.

To run a program you have saved as a file, you need some help. The kind of help required depends on the programming language you’re using. Some languages require an interpreter to run their programs. The interpreter examines each line of a computer program and executes that line, then goes on to the next. Many versions of BASIC are interpreted languages.


Note

If your favorite text editor is a word processing program that has features such as boldface text, font sizes, and other stylistic touches, when writing a computer program, either choose another editor or do not use those features. Programs should be prepared as text files with no special formatting. Notepad, a text editor that comes with Windows, saves all files as unformatted text. You also can use TextEdit on Macs or the vi editor or emacs on Linux systems to create text files without formatting.


The biggest advantage of interpreted languages is that they are faster to test. When you are writing a BASIC program, you can try it out immediately, fix errors, and try again. The primary disadvantage is that interpreted languages run slower than other programs. Each line has to be translated into instructions the computer can run, one line at a time.

Other programming languages require a compiler. The compiler takes a program and translates it into a form that the computer can understand. It also makes the program run as efficiently as possible. The compiled program can be run directly without the need for an interpreter.

Compiled programs run more quickly than interpreted programs but take more time to test. You have to write your program and compile the whole thing before trying it out. If you find an error and fix it, you must compile the program again.

Java is unusual because it requires both a compiler and an interpreter. The compiler converts the statements that make up the program into bytecode that can be run by an interpreter called the Java Virtual Machine.

The Java Virtual Machine, also called a JVM, is the thing that makes it possible for the same Java program to run without modification on different operating systems and different kinds of computing devices. The virtual machine turns bytecode into instructions that the device’s operating system can execute.

When Programs Don’t Work

Many new programmers become discouraged when they start to test their programs. Errors appear everywhere. Some of these are syntax errors, which are identified by the computer as it looks at the program and becomes confused by the way a statement has been written. Other errors are logic errors, which only are noticed by the programmer as the program is being tested (or might be overlooked entirely). Logic errors often cause it to do something unintended.


Note

One of the first computer bugs was discovered in 1947 by a team that included the American computer scientist Grace Hopper. Hopper was testing a computer at Harvard when a relay malfunctioned. The cause turned out to be not a software problem but an actual bug. She debugged the computer by removing a dead moth, which was taped into a logbook with the note, “First actual case of bug being found.” The bug and logbook page can be viewed at www.doncio.navy.mil/CHIPS/ArticleDetails.aspx?id=3489.


As you begin writing your own programs, you become well-acquainted with errors. They’re a natural part of the process. Programming errors are called bugs, a term that dates back a century or more to describe errors in technical devices.

The process of fixing errors also has its own term: debugging.

It’s no coincidence that there are so many ways to describe errors. You get a lot of debugging experience as you learn programming—whether you want it or not.

Choosing a Java Programming Tool

To start writing Java programs, you must have a Java programming tool. Several such programs are available for Java, including the simple Java Development Kit and more sophisticated Eclipse, IntelliJ IDEA, and NetBeans. The latter three tools are each an integrated development environment (IDE), a powerful tool used by professional programmers to get work done.

Whenever Oracle releases a new version of Java, the first tool that supports it is the Java Development Kit (JDK).


Note

You don’t have to use NetBeans in this book. If you can use the JDK or another tool to create, compile, and run a program, it’s all that most projects require. NetBeans is covered because for readers of past editions it has proven easier than the JDK. I use NetBeans for all of my Java programming.


To create the programs in this book, you must use JDK version 8 or a programming tool that works on top of it. The JDK is a set of free command-line tools for creating Java software. It lacks a graphical user interface, so if you have never worked in a nongraphical environment such as the Windows command prompt or Linux command-line interface, you will find it challenging to use the JDK.

The NetBeans IDE, also offered for free by Oracle, is a much easier way to write and test Java code than the JDK. NetBeans offers a graphical user interface, source code editor, user interface designer, and project manager. It works in complement to the JDK, running it behind the scenes, so you must have both tools on your system when you begin developing Java programs.

The programs in this book were created with NetBeans, which you can download and install separately from the JDK. You can use other Java tools as long as they support JDK 8.

Installing a Java Development Tool

Every hour of this book ends with a Java programming project you can undertake to enhance your knowledge of the subject matter while it percolates in your brain.

You can’t do any of that programming if you lack a Java programming tool on your computer.

If you already have installed a tool that supports Java, you can use it to develop the tutorial programs in the next 23 hours. However, you already should have some familiarity with how to use the tool. Learning Java and a complex IDE at the same time can be daunting.

The recommended choice for programming as you read this book is NetBeans 8.0, which is free from Oracle’s website at http://netbeans.org. Though NetBeans has advanced features that take time to learn, it makes it easy to create and run simple Java applications.

To find out how to download and install NetBeans, read Appendix A, “Using the NetBeans Integrated Development Environment.”

Summary

During this hour, you were introduced to the concept of programming a computer—giving it a set of instructions called statements that tell it what to do. You also learned why you made a good call choosing to teach yourself Java instead of another programming language.

You also might have downloaded and installed a Java development tool to use on the programs you create in the hours to come.

Ask 10 programmers for the best programming language and you may get 10 answers, complete with “my language can beat up your language” taunts and “your source code is so bloated” jokes. Java scores highly in such arguments because it is widely adopted, extremely versatile, and smartly designed. You can accomplish a lot with this language and it makes learning others a little easier.

If you are still confused about programs, programming languages, or Java in general, don’t panic. Everything will begin to make sense in the next hour, “Writing Your First Program,” which gently steps through the process of creating a Java program.

Workshop

Q&A

Q. BASIC? C++? Smalltalk? Java? What are the names of these languages supposed to mean?

A. BASIC gets its name from an acronym: Beginner’s All-purpose Symbolic Instruction Code. C++ is a programming language that was created to be an improvement on the C language, which itself was an improvement of the B programming language. Smalltalk is an innovative object-oriented language developed in the 1970s that had numerous ideas adopted by Java.

Java goes against the tradition of naming a language with an acronym or other meaningful term. It’s just the name that Java’s developers liked the best, beating out WebRunner, Silk, Ruby, and others. (The Ruby programming language didn’t exist back then.)

When I create my own programming language, it will be named Salsa. Everybody loves salsa.

Q. Why are interpreted languages slower than compiled ones?

A. They’re slower for the same reason that a person interpreting a live speech in a foreign language is slower than a translator interpreting a printed speech. The live interpreter has to think about each statement that’s being made as it happens, while the other interpreter can work on the speech as a whole and take shortcuts to speed up the process. Compiled languages can be much faster than interpreted languages because they do things to make the program run more efficiently.

Q. Do you only answer questions about Java?

A. Not at all. Ask me anything.

Q. Okay, what is the lowest score ever given on Dancing with the Stars?

A. The worst dance by a celebrity contestant on the hit ABC show was performed by the rapper Master P during the second season in 2006. His paso doble with professional dancer Ashly DelGrosso scored a lowest-ever 8. Judges Len Goodman and Bruno Tonioli scored it a 2 and judge Carrie Ann Inaba a 4.

Tonioli’s take: “It was a nightmare. ... It looked like a child on the mall lost looking for his mother.”

Goodman: “I know viewers think they’re being kind by bringing you back. They’re not. They’re being cruel—to Ashly, to the judges.”

Inaba: “I actually thought that that was your best dancing.”

Master P only trained 20 hours for the show, compared to 130 for the other contestants at that point in the season. He also refused to wear dancing shoes and performed in basketball sneakers. The dance was his last before being voted off.

The dance can be seen on YouTube, where one commenter writes, “Thumbs up if you’re watching this just to see the 2 paddle.”

Quiz

Test your knowledge of the material covered in this hour by answering the following questions.

1. Which of the following is NOT a reason that people think computer programming is painfully difficult?

A. Programmers spread that rumor to improve our employment prospects.

B. Jargon and acronyms are all over the place.

C. People who find programming too difficult are eligible for a government bailout.

2. What kind of tool runs a computer program by figuring out one line at a time?

A. A slow tool

B. An interpreter

C. A compiler

3. Why did James Gosling hole up in his office and create Java?

A. He was unhappy with the language he was using on a project.

B. His rock band wasn’t getting any gigs.

C. When you can’t visit YouTube at work, the Internet is pretty dull.

Answers

1. C. Computer book authors didn’t get a bailout either.

2. B. Interpreters interpret one line at a time. Compilers figure out the instructions beforehand so the program can run faster.

3. A. He was frustrated with C++. Back in 1991 when he created Java, YouTube was the place that held YouToothpaste.

Activities

If you’d like to better introduce yourself to the subjects of Java and computer programming, do the following activities:

Image To hear from programmers about why they chose this language, visit the Stack Overflow question-and-answer site at www.stackoverflow.com/questions/209555 to read how people answered the question, “Why would you choose the Java programming language over others?”

Image Using English sentences, write a set of instructions to convert a temperature from Celsius to Fahrenheit. Break the instructions into as many short one-sentence lines as you can.

To see solutions to the activities at the end of each hour, visit the book’s website at www.java24hours.com.