Preface
To the Reader
In this book you will find lots of sample code that demonstrates almost every feature of the language and library. The sample programs are deliberately simple to focus on the main points, but, for the most part, they are not fake and do not cut corners. I assume that you are willing, even eager, to learn about all the advanced features that Java makes available to you.
With the explosive growth of the Java class library, a one-part treatment of all Java features that serious programmers need to know is no longer possible. This first volume focuses on the fundamental concepts of the Java language, along with the basics of user interface programming. A list of FAQs and bug fixes can be found at http://horstmann.com/corejava.
Strategically placed at the end of the errata page (to encourage you to read it first) is a form you can use to report errors and suggest improvements. Please do not be disappointed if I do not answer all inquiries or do not get back to you immediately.
A Tour of This Book
In addition to the rules of the Java language, you'll also get advice on good OOP design. Classes and encapsulation are only one part of the OOP story, and Chapter 5 introduces the other—namely, inheritance. Mastering interfaces allows you to have full access to the power of Java's completely object-oriented approach to programming.
I show you how to use strong typing and remove unsightly and unsafe casts, and how to deal with them. This chapter shows you how to take advantage of the standard collections that are pre-built for your use. I show how you can make windows, how to paint on them, how to draw with geometric shapes, how to format text in multiple fonts, and how to display images.
Next, you'll see how to write code that responds to events, such as mouse clicks or key presses. This is an important and exciting application of Java technology in an era where most processors have multiple cores that you want to keep busy.
Conventions
When you want to collect multiple objects and retrieve them later, you should use a collection that best suits your circumstances, rather than just throwing the items into an array. You will learn all about the different types of buttons, text components, frames, sliders, list boxes, menus and dialog boxes.
NOTE
CAUTION
C++ NOTE
Sample Code
Acknowledgments
An Introduction to Java
- Java as a Programming Platform
- The Java “White Paper” Buzzwords
- Simple
- Object-Oriented
- Distributed
- Robust
- Secure
- Architecture-Neutral
- Portable
- Interpreted
- High-Performance
- Multithreaded
- Dynamic
- Java Applets and the Internet
- A Short History of Java
- Common Misconceptions about Java
There is no need for header files, pointer arithmetic (or even pointer syntax), structures, unions, operator overloading, virtual base classes, and so on. See the C++ notes scattered throughout the text for more information on the differences between Java and C++.) However, the designers did not attempt to solve all the clumsy features of C++. One of the goals of Java is to enable software that can run stand-alone on small machines. Unfortunately, over time, hackers have become quite good at detecting subtle flaws in security architecture implementation.
The compiled code is executable on many processors, given the presence of the Java runtime system. The applet becomes part of the page and the text flows through the space used for the applet. After many years of research, generic types (roughly comparable to C++ templates) have been added. The challenge was to add this feature without requiring any changes to the virtual machine.
Researchers saw it as a challenge to find chinks in the Java armor and defy the strength and sophistication of the applet security model. Java in particular is strongly typed - the compiler catches many errors that arise from type abuse.
The Java Programming Environment
- Installing the Java Development Kit
- Downloading the JDK
- Setting up the JDK
- Installing Source Files and Documentation
- Using the Command-Line Tools
- Using an Integrated Development Environment
- JShell
If you are typing the program by hand, make sure you enter the uppercase and lowercase letters correctly. To close the program, click the Close box in the title bar or select File → Exit from the menu. In the previous section, you saw how to compile and run a Java program from the command line.
Click the triangles in the left pane next to the project until you find the Welcome.java file and double-click it. With the right mouse button, click on the project name (Welcome) in the left pane. The cursor moves to the matching line in the edit pane where you can correct your mistake.
JShell responds with the result - in this case, the number of characters in the "Core Java" string. You can move the cursor in line with the ← and → keys and add or delete characters.
Fundamental Programming Structures in Java
- A Simple Java Program
- Comments
- Data Types
- Integer Types
- Floating-Point Types
- The char Type
- Unicode and the char Type
- The boolean Type
- Variables and Constants
- Declaring Variables
- Initializing Variables
- Constants
- Enumerated Types
- Operators
- Arithmetic Operators
- Mathematical Functions and Constants
- Conversions between Numeric Types
- Assignment
- Increment and Decrement Operators
- Relational and boolean Operators
- The Conditional Operator
- Bitwise Operators
- Parentheses and Operator Hierarchy
- Strings
- Substrings
- Concatenation
- Strings Are Immutable
- Testing Strings for Equality
- Empty and Null Strings
- Code Points and Code Units
- The String API
- Reading the Online API Documentation
- Building Strings
- Text Blocks
- Input and Output
- Reading Input
- Formatting Output
- File Input and Output
- Control Flow
- Block Scope
- Conditional Statements
- Determinate Loops
- Multiple Selections with switch
- Statements That Break Control Flow
- Big Numbers
- Arrays
- Declaring Arrays
- Accessing Array Elements
- The “for each” Loop
- Array Copying
- Command-Line Parameters
- Array Sorting
- Multidimensional Arrays
- Ragged Arrays
You must make the source code file name the same as the public class name, with the .java extension appended to it. As with most programming languages, you can think of Java instructions as sentences of the language. The body of the main method contains a statement that sends one line of text to the console.
In the Unicode standard, code points are written in hexadecimal and with a U+ prefix, such as U+0041 for the code point of the Latin letter A. Static inputs are covered in Chapter 4. The methods in the Math class use the routines in the computer's floating point unit for the fastest performance. You can extract a substring from a larger string using the substring method of the String class.
For example, if you click on the link CompareToIgnoreCase, you will get the description of it. Make sure you indent to the end of the white space you want to remove. Now you can read from the file using one of the scanner methods you have already encountered.
That's not a good idea; the program may behave differently depending on where it is run. The main method of a Java program does not store the name of the program in the args array. To sort a set of numbers, you can use one of the sorting methods in the.
Objects and Classes
- Introduction to Object-Oriented Programming
- Objects
For experienced C++ programmers, this chapter, like the previous chapter, offers familiar information; however, there are enough differences between the two languages that you should read the later sections of this chapter carefully. Object-oriented programming, or OOP for short, is the dominant programming paradigm these days, replacing the "structured" or procedural programming techniques developed in the 1970s. Since Java is object oriented, you need to be familiar with OOP to become productive with Java.
Many objects in your programs are taken “ready-made” from a library; others will be custom designed. Whether you build or buy an object may depend on your budget or time. But in principle you don't care how the functionality is implemented, as long as an object meets your specifications.
Once the procedures were determined, the traditional next step was to find suitable ways to store the data. This is why the designer of the Pascal language, Niklaus Wirth, named his famous book on programming Algorithms + Data Structures = Programs (Prentice Hall, 1976). First, they decided on the procedures for manipulating the data; then they decided what structure to impose on the data to make the manipulations easier.
OOP reverses the order: it lays out the data first, then looks at the algorithms to operate on the data. It may require 2000 procedures to execute, all manipulating a set of global data. In an object-oriented style, there can be 100 classes with an average of 20 methods per class (see Figure 4.1).
It is much easier to find the culprit among 20 methods that had access to this data than among 2000 procedures. When you construct an object from a class, we say that you have created an instance of the class. However, you still need to create your own classes in Java to describe your application's problem domain objects.