12,99 €
Swiftly brush up on the foundations of Java programming
Java Essentials For Dummies is a reliable and succinct reference on the core components of Java—the multifaceted general-purpose language used for desktop, mobile, and web applications. This straightforward book gets right to the point—eliminating review material and wordy explanations—so you get what you need, fast.
Perfect for supplementing classroom learning, reviewing for a certification, or staying knowledgeable on the job, Java Essentials For Dummies is a direct reference that's great to keep on hand as an everyday desk reference.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 239
Veröffentlichungsjahr: 2024
Cover
Title Page
Copyright
Introduction
About This Book
Foolish Assumptions
Icons Used in This Book
Where to Go from Here
Chapter 1: Installing and Using Java Tools
Downloading and Installing the Java Development Kit
Confirming Your Java Version
Chapter 2: Working with TextPad
Downloading and Installing TextPad
Editing Source Files
Compiling a Program
Running a Java Program
Chapter 3: Java Programming Basics
Looking at the Venerable Hello, World! Program
Dealing with Keywords
Working with Statements
Working with Blocks
Creating Identifiers
Crafting Comments
Introducing Object-Oriented Programming
Importing Java API Classes
Chapter 4: Working with Variables and Data Types
Declaring Variables
Initializing Variables
Using Final Variables (Constants)
Working with Primitive Data Types
Working with Strings
Understanding Scope
Chapter 5: Working with Numbers and Expressions
Working with Arithmetic Operators
Using Compound Assignment Operators
Using the Math Class
Formatting Numbers
Chapter 6: Making Choices
Using Simple Boolean Expressions
Using if Statements
Using Mr. Spock’s Favorite Operators (Logical Ones, of Course)
Using the switch Statement
Chapter 7: Going Around in Circles (or, Using Loops)
Using Your Basic while Loop
Breaking Out of a Loop
Using the continue Statement
Running do-while Loops
Using the Famous for Loop
Chapter 8: Adding Some Methods to Your Madness
The Basics of Making Methods
Methods That Return Values
Methods That Take Parameters
Chapter 9: Handling Exceptions
Understanding Exceptions
Catching Exceptions
Handling Exceptions with a Preemptive Strike
Catching All Exceptions at Once
Using a finally Block
Chapter 10: Making Your Own Classes
Declaring a Class
Working with Members
Using Getters and Setters
Creating Constructors
Chapter 11: Using Subclasses and Inheritance
Introducing Inheritance
Creating Subclasses
Overriding Methods
Protecting Your Members
Using the this and super Keywords in Your Subclasses
Understanding Inheritance and Constructors
Using the final Keyword
Chapter 12: Using Arrays
Understanding Arrays
Creating Arrays
Initializing an Array
Using for Loops with Arrays
Using Arrays with Methods
Using Varargs
Using Two-Dimensional Arrays
Chapter 13: Ten Techniques for Easier Java Coding
Compiling a Java Program from the Command Line
Running a Java Program from the Command Line
Casting Numeric Data
Printing Data with System.out
Getting Input with the JOptionPane Class
Using the Unary Plus and Minus Operators
Using the Increment and Decrement Operators
Using the Conditional Operator
Comparing Strings
Nesting Your Loops
Index
About the Authors
Connect with Dummies
End User License Agreement
Chapter 1
TABLE 1-1 Subfolders of the JDK Home Folder
Chapter 3
TABLE 3-1 Java’s Keywords
Chapter 4
TABLE 4-1 Java's Primitive Types
TABLE 4-2 Escape Sequences for Character Constants
TABLE 4-3 Wrapper Classes for the Primitive Types
TABLE 4-4 Methods That Convert Strings to Numeric Primitive Types
Chapter 5
TABLE 5-1 Java’s Arithmetic Operators
TABLE 5-2 Compound Assignment Operators
TABLE 5-3 Constants of the Math Class
TABLE 5-4 Commonly Used Mathematical Functions Provided by the Math Class
TABLE 5-5 Rounding Functions Provided by the Math Class
TABLE 5-6 Methods of the NumberFormat Class
Chapter 6
TABLE 6-1 Relational Operators
TABLE 6-2 Logical Operators
Chapter 1
FIGURE 1-1: The Environment Variables dialog box.
FIGURE 1-2: Creating the
JAVA_HOME
variable.
FIGURE 1-3: Editing the
Path
variable.
Chapter 2
FIGURE 2-1: Configuring tools in TextPad.
FIGURE 2-2: Editing a Java file in TextPad.
FIGURE 2-3: Error messages displayed by the Java compiler.
FIGURE 2-4: Running a program.
Chapter 3
FIGURE 3-1: The class in Listing 3-4 displays this dialog box.
Chapter 9
FIGURE 9-1: Why you have to call next to discard the invalid input.
Cover
Table of Contents
Title Page
Copyright
Begin Reading
Index
About the Authors
i
ii
1
2
3
4
5
6
7
8
9
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
99
100
101
102
103
104
105
106
107
108
109
111
112
113
114
115
116
117
118
119
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
187
188
189
190
191
192
193
194
195
196
197
198
199
Java® Essentials For Dummies®
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2025 by John Wiley & Sons, Inc. All rights reserved, including rights for text and data mining and training of artificial technologies or similar technologies.
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. Java is a registered trademark of Oracle America, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit https://hub.wiley.com/community/support/dummies.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2024944840
ISBN 978-1-394-29697-2 (pbk); ISBN 978-1-394-29699-6 (ebk); ISBN 978-1-394-29698-9 (ebk)
Welcome to Java Essentials For Dummies. This book contains all the basic information you need to know to get going with Java programming, starting with writing statements and using variables and ending with techniques for using Java features such as arrays. Along the way, you find plenty of not-so-basic information about working with classes and objects, handling exceptions, and working from the command line.
The basic idea here is that we’ve tried to wring out the not-quite-200-or-so most useful pages of information on the most important Java programming topics: setup and configuration, basic programming, and object-oriented programming. Thus, you get a nice, trim book with just the Java you need to know.
So, whether you’re just getting started with Java programming or you’re a seasoned pro, you’ve found the right book.
In Java Essentials For Dummies, all the information you need is conveniently packaged for you in-between one set of covers. And all the information is current for a recent release of Java, known as JDK 19. This book doesn’t pretend to be a comprehensive reference for every detail on every possible topic related to Java programming. Instead, it shows you how to get up and running fast so that you have more time to do the things you really want to do. Designed using the easy-to-follow For Dummies format, this book helps you get the information you need without laboring to find it.
We’ve never met, so it’s difficult for us to make any assumptions about why you’re interested in this book. However, let’s start with a few basic assumptions:
You own or have access to a relatively modern computer.
The examples were created on a Windows computer, but you can learn to program in Java just as easily on a Mac or Linux computer.
You’re an experienced computer user.
In other words, we assume that you know the basics of using your computer, such as starting programs and working with the file system.
You’re interested in learning how to write programs in the Java language.
That’s what this book is about, so it’s a fair assumption.
We do not assume you have any previous programming experience in Java or in any other programming language.
Like any For Dummies book, this book is chock-full of helpful icons that draw your attention to items of particular importance. You find the following icons throughout this book:
Danger, Will Robinson! This icon highlights information that may help you avert disaster.
Did we tell you about the memory course we took?
Pay special attention to this icon; it lets you know that some particularly useful tidbit is at hand.
This isn’t the kind of book you pick up and read from start to finish, as if it were a cheap novel. If we ever see you reading it at the beach, we’ll kick sand in your face. Beaches are for reading romance novels or murder mysteries, not programming books. Although you could read straight through from start to finish, this book is the kind you can pick up, open to just about any page, and start reading. You don’t have to memorize anything in this book. It’s a “need-to-know” book: You pick it up when you need to know something. Need a reminder on how to declare a class? Pick up the book. Can’t remember the goofy syntax of the for loop? Pick up the book. After you find what you need, put the book down and get on with your life.
Chapter 1
IN THIS CHAPTER
Downloading Java from the Oracle website
Installing Java
Identifying your version of Java
Java development environments have two basic approaches. On the one hand, you can use a sophisticated integrated development environment (IDE) such as NetBeans or Eclipse. These tools combine a full-featured source editor that lets you edit your Java program files with integrated development tools, including visual development tools that let you create applications by dragging and dropping visual components onto a design surface.
At the other extreme, you can use just the basic command-line tools that are available free from Oracle’s Java website (https://java.oracle.com). Then you can use any text editor you want to create the text files that contain your Java programs (called source files), and compile and run your programs by typing commands at a command prompt.
As a compromise, you may want to use a simple development environment, such as TextPad. TextPad is an inexpensive text editor that provides some nice features for editing Java programs (such as automatic indentation) and shortcuts for compiling and running programs. It doesn’t generate any code for you or provide any type of visual design aids, however. TextPad is the tool we used to develop all the examples shown in this book. For information about downloading and using TextPad, see Chapter 2.
If you prefer a free alternative, you can also investigate Notepad++ at https://notepad-plus-plus.org.
You can also compile and run simple Java programs online at sites such as JDoodle (www.jdoodle.com/online-java-compiler) or Programiz (www.programiz.com/java-programming/online-compiler). At these sites, you can enter simple Java programs, compile them, and run them. They’re a great way to dip your toes into the shallow end of the Java programming pool without having to install anything.
Before you can start writing Java programs, you have to download and install the correct version of the Java Development Kit (JDK) for the computer system you’re using. Oracle’s Java website provides versions for Windows, macOS, and Unix. The following sections show you how to download and install the JDK.
If you prefer, you can download and install the open-source version of Java from https://openjdk.org.
To get to the download page, point your browser to www.oracle.com/java/technologies. Then follow the appropriate links to download the latest version of Java SE for your operating system. (At the time we wrote this, the latest version was 18.0.1.1. However, Java 19 was available in early release form. By the time this book hits the shelves, Java 19 or later should be available from www.oracle.com/java/technologies.)
When you get to the Java download page, you’ll need to select your operating system; Java is available for Linux, macOS, and Windows. In this chapter, we show you how to deploy Java to a Windows 10 or 11 computer. The procedures for deploying Java to Linux or macOS are similar.
The JDK download comes in three versions: a compressed.zip file, an executable installer (.exe), or a Windows installer package (.msi). All are about the same size (under 200MB). We find it easier to download and run the .exe installer.
After you download the JDK file, you can install it by running the executable file you downloaded. The procedure varies slightly depending on your operating system, but basically, you just run the JDK installation program file after you download it, as follows:
On a Windows system, open the folder in which you saved the installation program and double-click the installation program’s icon.
On a Linux or macOS system, use console commands to change to the directory to which you downloaded the file and then run the program.
After you start the installation program, it prompts you for any information that it needs to install the JDK properly, such as which features you want to install and what folder you want to install the JDK in. You can safely choose the default answer for each option.
When the JDK installs itself, it creates several folders on your hard drive. The locations of these folders vary depending on your system and how you installed Java. The three most likely places to find the Java home folder in Windows are the root of your C: drive, the folder C:\Program Files\Java, or the folder C:\Program Files (x86)\Java. Within one of these locations, you’ll find the Java home folder, whose name starts with jfk- and ends with the version number. For version 19, the home folder is named jdk-19.
Table 1-1 lists the subfolders created in the JDK home folder. As you work with Java, you’ll refer to these folders frequently.
TABLE 1-1 Subfolders of the JDK Home Folder
Folder
Description
bin
The compiler and other Java development tools
conf
Configuration file
include
This library contains files needed to integrate Java with programs written in other languages
jmods
Modules for the Java Module System
legal
Copyright and license information for various Java components
lib
Library files, including the Java API class library
After you install the JDK, you need to configure your operating system so that it can find the JDK command-line tools. To do that, you must set two environment variables: JAVA_HOME, which provides the location of the Java home folder, and Path, which lists the folders that the operating system uses to locate executable programs. Follow these steps:
Open File Explorer, right-click This PC, and choose Properties.
This brings up the System Properties page.
Click the Advanced System Settings link.
Click the Environment Variables button.
The Environment Variables dialog box appears, as shown in Figure 1-1.
In the System Variables list, click the New button.
The New System Variable dialog box, shown in Figure 1-2, appears.
Type
JAVA_HOME
in the Variable Name text box.
Click the Browse Directory button, browse to the Java home folder, and then click OK.
This action inserts the path to the home folder in the Variable Value text box.
Click OK.
The JAVA_HOME variable is created.
Scroll to the Path variable in the System Variables list, select it, and then click the Edit button.
This brings up a handy dialog box that lets you add or remove paths to the Path variable or change the order of the paths, shown in Figure 1-3.
FIGURE 1-1: The Environment Variables dialog box.
FIGURE 1-2: Creating the JAVA_HOME variable.
Peruse the list of entries in thePathvariable. If you find one that references a previous version of Java, delete it.
Specifically, look for an entry that begins with C:\Program Files\Java. If you find such an entry, select it and then click Delete.
Click the New button.
This opens a line for you to create a new path entry.
FIGURE 1-3: Editing the Path variable.
Type %JAVA_HOME%\bin as the new path entry.
The percent signs insert the value of the JAVA_HOME variable in your new path entry. For example, if JAVA_HOME is set to C:\Program Files\Java\jdk19, the new path entry will be C:\Program Files\Java\jdk19\bin.
Click OK three times to exit.
The first OK gets you back to the Environment Variables dialog box; the second OK gets you back to the System Properties dialog box; and the third OK closes the System Properties dialog box.
For Linux, the procedure depends on which shell you’re using. For more information, consult the documentation for the shell you’re using.
After you’ve installed Java, it’s a good idea to confirm that you’ve installed the correct version. To do that, follow these steps:
Press the Windows key, type
cmd
, and press Enter to open a command prompt.
Type java -version and press Enter.
This command instructs Java to display its version number. You’ll see output similar to this:
openjdk version "19-ea" 222-09-20OpenJDK Runtime Environment (build 19-ea+27-2074)OpenJDK 64-Bit Server VM (build 19-ea+27-2074, mixed mode, sharing)
Confirm that the first line of the output reflects the version you installed.
In this example, Java version 19-ea is installed. The ea indicates that we’re using the early-access version of Java 19, which is the version we used as we wrote this book. By the time you read this, you’ll see a slightly different version of Java 19 or later. Or, you may see a Java 18 or even a Java 17 version number. Any of these versions will work for the coding examples in this book, unless we specifically mention that a specific Java version is required.
Close the command window.
Chapter 2
IN THIS CHAPTER
Acquiring TextPad
Using TextPad to edit source files
Compiling Java programs
Running Java programs
TextPad is an inexpensive ($27) text editor that you can integrate with the Java Development Kit (JDK) to simplify the task of coding, compiling, and running Java programs. It isn’t a true integrated development environment (IDE), as it lacks features such as integrated debugging, code generators, and drag-and-drop tools for creating graphical user interfaces.
TextPad is a popular tool for developing Java programs because of its simplicity and speed. It’s ideal for learning Java because it doesn’t generate any code for you. Writing every line of code yourself may seem like a bother, but the exercise pays off in the long run because you have a better understanding of how Java works.
You can download a free evaluation version of TextPad from Helios Software Systems at www.textpad.com. You can use the evaluation version free of charge, but if you decide to keep the program, you must pay for it. (Helios accepts credit card payment online.)
If the Java JDK is already installed on your computer when you install TextPad, TextPad automatically configures itself to compile and run Java programs. If you install the JDK after you install TextPad, you need to configure TextPad for Java by following these steps:
Choose Configure ⇒ Preferences to open the Preferences dialog box.
Click Tools in the tree that appears on the left side of the dialog box.
Click the Add button to reveal a drop-down list of options and then click Java SDK Commands.
Click OK.
The commands you need to compile and run Java programs are added to TextPad’s Tools menu.
Figure 2-1 shows how the Preferences dialog box appears when the Java tools are installed. As you can see, the Tools item in the tree on the left side of the dialog box includes three Java tools: Compile Java, Run Java Application, and Run Java Applet. (The Run Java Applet tool is obsolete, so you can safely ignore it.)
FIGURE 2-1: Configuring tools in TextPad.
If you plan on using any preview features in Java, add the --enable-preview and --release 19 flags to the command line arguments for the Compile tool. The complete Compile tool arguments should look like this:
--enable-preview --release 19 $File
Then, add just the --enable-preview flag to the Run Java Application arguments list; the complete arguments should look like this:
--enable-preview $BaseName
Do not add the --release flag to the Run Java Application tool. If you do, the tool won’t be able to start the JVM, because --release is not a valid flag for the java command.
Figure 2-2 shows a Java source file being edited in TextPad. If you’ve worked with a Windows text editor before, you’ll have no trouble mastering the basics of TextPad. We won’t go over such basic procedures as opening and saving files because they’re standard; instead, we describe some TextPad features that are useful for editing Java program files.
FIGURE 2-2: Editing a Java file in TextPad.
When you first create a file (by clicking the New button on the toolbar or by choosing File ⇒ New), TextPad treats the file as a normal text file, not as a Java program file. After you save the file (by clicking the Save button or choosing File ⇒ Save) and assign .java as the file extension, TextPad’s Java-editing features kick in.
The following paragraphs describe some of TextPad’s most noteworthy features for working with Java files:
You can’t really tell from
Figure 2-2
, but TextPad uses different colors to indicate the function of each word or symbol in the program. Brackets are red so that you can spot them quickly and make sure that they’re paired correctly. Keywords are blue. Comments and string literals are green. Other text, such as variable and method names, is black.
TextPad automatically indents whenever you type an opening bracket and then reverts to the previous indent when you type a closing bracket. This feature makes keeping your code lined up easy.
Line numbers display down the left edge of the editing window. You can turn these line numbers on or off by choosing View ⇒ Line Numbers.
To go to a particular line, press Ctrl+G to bring up the Go To dialog box. Make sure that Line is selected in the Go to What box, enter the line number in the text box, and click OK.
If you have more than one file open, you can switch between the files by using the Document Selector — the pane on the left side of the TextPad window (refer to
Figure 2-2
). If the Document Selector isn’t visible, choose View ⇒ Document Selector to summon it.
Another way to switch between two (or more) files is to choose View ⇒ Document Tabs. Tabs appear at the top of the document window, and you can click these tabs to switch documents.
A handy Match Bracket feature lets you pair brackets, braces, and parentheses. To use this feature, move the insertion point to a bracket, brace, or parenthesis and then press Ctrl+M. TextPad finds the matching element.
To search for text, press F5. In the Find dialog box, enter the text you’re looking for, and click OK. To repeat the search, press Ctrl+F.
To replace text, press F8.
To compile a Java program in TextPad, choose Tools ⇒ Compile Java or use the keyboard shortcut Ctrl+1. The javac command compiles the program, and the compiler output is displayed in the Tool Results pane of the TextPad window. If the program compiles successfully, the message Tool completed successfully appears in the Tool Results pane. If the compiler finds something wrong with your program, one or more error messages are displayed, as shown in Figure 2-3.
FIGURE 2-3: Error messages displayed by the Java compiler.
In this example, two compiler error messages are displayed:
C:\Users\doug\Documents\HelloApp.java:5: error: ')' expected System.out.println(Hello, World!"); ^C:\Users\doug\Documents\HelloApp.java:5: error: unclosed string literal System.out.println(Hello, World!"); ^2 errorsTool completed with exit code 1
If you double-click the first line of each error message, TextPad takes you to the spot where the error occurred. If you double-click the line with the unclosed string literal message, for example, you’re taken to line 5, and the insertion point is positioned at the spot where the compiler found the error. Then you can correct the error and recompile the program.