Ameba Ownd

アプリで簡単、無料ホームページ作成

grisanreli1980's Ownd

Core java 2 volume ii torrent

2022.01.16 00:38




















For government sales inquiries, please contact [email protected] For questions about sales outside the United States, please contact [email protected] Visit us on the Web: informit. All Rights Reserved. Oracle America Inc. All such documents and related graphics are provided "as is" without warranty of any kind. The documents and related graphics contained herein could include technical inaccuracies or typographical errors.


Changes are periodically added to the information herein. Partial screen shots may be viewed in full within the software version specified. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation.


All rights reserved. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. Actually Necessary? The promise of Java technology was that it would become the universal glue that connects users with information wherever it comes from—web servers, databases, information providers, or any other imaginable source.


Indeed, Java is in a unique position to fulfill this promise. It is an extremely solidly engineered language that has gained wide acceptance. Its built-in security and safety features are reassuring both to programmers and to the users of Java programs. Java has built-in support for advanced programming tasks, such as network programming, database connectivity, and concurrency.


Since , eleven major revisions of the Java Development Kit have been released. Over the course of the last 20 years, the Application Programming Interface API has grown from about to over 4, classes. The API now spans such diverse areas as user interface construction, database management, internationalization, security, and XML processing.


The book that you are reading right now is the first volume of the eleventh edition of Core Java. Each edition closely followed a release of the Java Development Kit, and each time, we rewrote the book to take advantage of the newest Java features.


As with the previous editions of this book, we still target serious programmers who want to put Java to work on real projects. Our goal is to enable you to fully understand the Java language and library, not to give you an illusion of understanding.


In this book you will find lots of sample code demonstrating almost every language and library feature that we discuss. They should make good starting points for your own code. We assume you are willing, even eager, to learn about all the advanced features that Java puts at your disposal. For example, we give you a detailed treatment of Object-oriented programming Reflection and proxies Interfaces and inner classes Exception handling Generic programming The collections framework The event listener model Graphical user interface design Concurrency With the explosive growth of the Java class library, a one-volume treatment of all the features of Java that serious programmers need to know is no longer possible.


Hence, we decided to break up the book into two volumes. This first volume concentrates on the fundamental concepts of the Java language, along with the basics of user-interface programming. The second volume, Core Java, Volume II—Advanced Features, goes further into the enterprise features and advanced user-interface programming. Strategically placed at the end of the errata page to encourage you to read through it first is a form you can use to report bugs and suggest improvements.


We do read all e-mail and appreciate your input to make future editions of this book clearer and more informative. A Tour of This Book Chapter 1 gives an overview of the capabilities of Java that set it apart from other programming languages. We explain what the designers of the language set out to do and to what extent they succeeded. Then, we give a short history of how Java came into being and how it has evolved. In Chapter 2, we tell you how to download and install the JDK and the program examples for this book.


Then we guide you through compiling and running three typical Java programs—a console application, a graphical application, and an applet—using the plain JDK, a Java-enabled text editor, and a Java IDE. Chapter 3 starts the discussion of the Java language. In this chapter, we cover the basics: variables, loops, and simple functions. If you come from a non-C background such as Visual Basic, you will want to read this chapter carefully.


Object-oriented programming OOP is now in the mainstream of programming practice, and Java is an object-oriented programming language. Chapter 4 introduces encapsulation, the first of two fundamental building blocks of object orientation, and the Java language mechanism to implement it—that is, classes and methods.


In addition to the rules of the Java language, we also give advice on sound OOP design. Finally, we cover the marvelous javadoc tool that formats your code comments as a set of hyperlinked web pages. Programmers coming from a non-object-oriented background should expect to spend some time mastering the OOP concepts before going further with Java. Classes and encapsulation are only one part of the OOP story, and Chapter 5 introduces the other—namely, inheritance. Inheritance lets you take an existing class and modify it according to your needs.


This is a fundamental technique for programming in Java. Interfaces let you go beyond the simple inheritance model of Chapter 5. After we cover interfaces, we move on to lambda expressions, a concise way for expressing a block of code that can be executed at a later point in time. We then cover a useful technical feature of Java called inner classes. Exceptions give you an efficient way of separating the normal processing code from the error handling.


Of course, even after hardening your program by handling all exceptional conditions, it still might fail to work as expected. In the final part of this chapter, we give you a number of useful debugging tips. Chapter 8 gives an overview of generic programming.


Generic programming makes your programs easier to read and safer. We show you how to use strong typing and remove unsightly and unsafe casts, and how to deal with the complexities that arise from the need to stay compatible with older versions of Java. The topic of Chapter 9 is the collections framework of the Java platform. Whenever you want to collect multiple objects and retrieve them later, you should use a collection that is best suited for your circumstances, instead of just tossing the elements into an array.


This chapter shows you how to take advantage of the standard collections that are prebuilt for your use. Chapter 10 provides an introduction into GUI programming. We 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.


Chapter 11 discusses the Swing GUI toolkit in great detail. The Swing toolkit allows you to build cross-platform graphical user interfaces. However, some of the more advanced components are discussed in Volume II. Chapter 12 finishes the book with a discussion of concurrency, which enables you to program tasks to be done in parallel.


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. The Appendix lists the reserved words of the Java language. Conventions As is common in many computer books, we use monospace type to represent computer code. When using an API call for the first time, we add a short summary description at the end of the section. These descriptions are a bit more informal but, we hope, also a little more informative than those in the official online API documentation.


The names of interfaces are in italics, just like in the official documentation. See Chapter 2 for more information on installing the Java Development Kit and the sample code. To start the registration process, go toinformit. Look on the Registered Products tab for an Access Bonus Content link next to this product, and follow that link to access any available bonus materials. If you would like to be notified of exclusive offers on new editions and updates, please check the box to receive email from us.


Making a book a reality takes many dedicated people, and it is my great pleasure to acknowledge the contributions of the entire Core Java team. A large number of individuals at Pearson provided valuable assistance but managed to stay behind the scenes. As always, my warm thanks go to my editor, Greg Doench, for steering the book through the writing and production process, and for allowing me to be blissfully unaware of the existence of all those folks behind the scenes. I am very grateful to Julie Nahil for production support, and to Dmitry Kirsanov and Alina Kirsanova for copyediting and type-setting the manuscript.


My thanks also to my coauthor of earlier editions, Gary Cornell, who has since moved on to other ventures. Thanks to the many readers of earlier editions who reported embarrassing errors and made lots of thoughtful suggestions for improvement. I am particularly grateful to the excellent reviewing team who went over the manuscript with an amazing eye for detail and saved me from many embarrassing errors.


Nicholas J. Java has the distinction of being the first and only programming language that had a ten-minute story on National Public Radio.


I hope you will enjoy a brief history of Java that you will find in this chapter. There is no doubt that it is one of the better languages available to serious programmers. We think it could potentially have been a great programming language, but it is probably too late for that.


Once a language is out in the field, the ugly reality of compatibility with existing code sets in. The Java language has a lot of nice features that we will examine in detail later in this chapter. It has its share of warts, and some of the newer additions to the language are not as elegant as the original features because of compatibility requirements.


But, as we already said in the first edition, Java was never just a language. There are lots of programming languages out there, but few of them make much of a splash. Java is a whole platform, with a huge library, containing lots of reusable code, and an execution environment that provides services such as security, portability across operating systems, and automatic garbage collection.


As a programmer, you will want a language with a pleasant syntax and As a programmer, you will want a language with a pleasant syntax and comprehensible semantics i. Java fits the bill, as do dozens of other fine languages. Well, Java has everything —a good language, a high-quality execution environment, and a vast library. That combination is what makes Java an irresistible proposition to so many programmers.


They also published a shorter overview that is organized along the following 11 buzzwords: 1. Simple 2. Object-Oriented 3. Distributed 4. Robust 5. Secure 6. Architecture-Neutral 7.


Portable 8. Interpreted 9. High-Performance Multithreaded Dynamic In the following subsections, you will find a summary, with excerpts from the white paper, of what the Java designers say about each buzzword, together with a commentary based on my experiences with the current version of Java.


Note The white paper can be found at www. There is no need for header files, pointer arithmetic or even a pointer syntax , structures, unions, operator overloading, virtual base classes, and so on.


For example, the syntax of the switch statement is unchanged in Java. Many developers used Visual Basic and its drag-anddrop programming environment. These developers did not find Java simple. It took several years for Java development environments to catch up. Nowadays, Java development environments are far ahead of those for most other programming languages.


Another aspect of being simple is being small. One of the goals of Java is to enable the construction of software that can run stand-alone on small machines. The size of the basic interpreter and class support is about 40K; the basic standard libraries and thread support essentially a self-contained microkernel add another K. This was a great achievement at the time.


Of course, the library has since grown to huge proportions. There is now a separate Java Micro Edition with a smaller library, suitable for embedded devices. Object orientation was pretty well established when Java was developed. Java applications can open and access objects across the Net via URLs with the same ease as when accessing a local file system. Java puts a lot of emphasis on early checking for possible problems, later dynamic runtime checking, and eliminating situations that are errorprone.


The Java compiler detects many problems that in other languages would show up only at runtime. As for the second point, anyone who has spent hours chasing memory corruption caused by a pointer bug will be very happy with this aspect of Java. Toward that end, a lot of emphasis has been placed on security. Java enables the construction of virus-free, tamper-free systems. Users were assured that nothing bad could happen because Java code, no matter where it came from, could never escape from the sandbox.


However, the security model of Java is complex. Not long after the first version of the Java Development Kit was shipped, a group of security experts at Princeton University found subtle bugs that allowed untrusted code to attack the host system.


Initially, security bugs were fixed quickly. Unfortunately, over time, hackers got quite good at spotting subtle flaws in the implementation of the security architecture.


Sun, and then Oracle, had a tough time keeping up with bug fixes. After a number of high-profile attacks, browser vendors and Oracle became increasingly cautious. Java browser plug-ins no longer trust remote code unless it is digitally signed and users have agreed to its execution. Note Even though in hindsight, the Java security model was not as successful as originally envisioned, Java was well ahead of its time. A competing code delivery mechanism from Microsoft relied on digital signatures alone for security.


The compiled code is executable on many processors, given the presence of the Java runtime system. The Java compiler does this by generating bytecode instructions which have nothing to do with a particular computer architecture. Rather, they are designed to be both easy to interpret on any machine and easy to translate into native machine code on the fly. Programming languages such as Lisp, Smalltalk, and Pascal had employed this technique for many years. Of course, interpreting virtual machine instructions is slower than running machine instructions at full speed.


However, virtual machines have the option of translating the most frequently executed bytecode sequences into machine code —a process called just-in-time compilation. It increases security because it can check the behavior of instruction sequences. The sizes of the primitive data types are specified, as is the behavior of arithmetic on them.


For example, an int in Java is always a bit integer. The only restriction is that the int type must have at least as many bytes as a short int and cannot have more bytes than a long int.


Having a fixed size for number types eliminates a major porting headache. Binary data is stored and transmitted in a fixed format, eliminating confusion about byte ordering. Strings are saved in a standard Unicode format. The libraries that are a part of the system define portable interfaces. The example of a Window class was perhaps poorly chosen.


As anyone who has ever tried knows, it is an effort of heroic proportions to implement a user interface that looks good on Windows, the Macintosh, and ten flavors of UNIX. Java 1. Unfortunately, the result was a library that, with a lot of work, could give barely acceptable results on different systems.


That initial user interface toolkit has since been replaced, and replaced again, and portability across platforms remains an issue. You can work with files, regular expressions, XML, dates and times, databases, network connections, threads, and so on, without worrying about the underlying operating system. Not only are your programs portable, but the Java APIs are often of higher quality than the native ones.


Since linking is a more incremental and lightweight process, the development process can be much more rapid and exploratory. This was a real stretch. You try out something, and you instantly see the result. The bytecodes can be translated on the fly at runtime into machine code for the particular CPU the application is running on.


For example, a just-in-time compiler can monitor which code is executed frequently and optimize just that code for speed. A more code is executed frequently and optimize just that code for speed.


The just-in-time compiler knows which classes have been loaded. It can use inlining when, based upon the currently loaded collection of classes, a particular function is never overridden, and it can undo that optimization later if necessary. Instead of faster processors, we just get more of them, and we have to keep them busy.


Yet when you look at most programming languages, they show a shocking disregard for this problem. Java was well ahead of its time. It was the first mainstream language to support concurrent programming. As you can see from the white paper, its motivation was a little different. At the time, multicore processors were exotic, but web programming had just started, and processors spent a lot of time waiting for a response from the server.


Concurrent programming is never easy, but Java has done a very good job making it manageable. It was designed to adapt to an evolving environment.


Libraries can freely add new methods and instance variables without any effect on their clients. In Java, finding out runtime type information is straightforward. This is an important feature in situations where code needs to be added to a running program. A prime example is code that is downloaded from the Internet to run in a browser. Their achievement was to bring this feature to a mainstream programming language. This effort failed to gain traction, and Microsoft followed through with another language called C that also has many similarities to Java but runs on a different virtual machine.


Java programs that work on web pages are called applets. To use an applet, you only need a Java-enabled web browser, which will execute the bytecodes for you. You need not install any software.


You get the latest version of the program whenever you visit the web page containing the applet. Most importantly, thanks to the security of the virtual machine, you never need to worry about attacks from hostile code. Inserting an applet into a web page works much like embedding an image. The applet becomes a part of the page, and the text flows around the space used for the applet.


The point is, this image is alive. It reacts to user commands, changes its appearance, and exchanges data between the computer presenting the applet and the computer serving it. Figure 1. By using the mouse, you can rotate and zoom each molecule to better understand its structure.


At the time that applets were invented, this kind of direct manipulation was not achievable with web pages—there was only rudimentary JavaScript and no HTML canvas. Many people believe that the lure of applets was responsible for the astonishing popularity of Java. However, the initial excitement soon turned into frustration. Various versions of the Netscape and Internet Explorer browsers ran different versions of Java, some of which were seriously outdated.


This sorry situation made it increasingly difficult to develop applets that took advantage of the most current Java version. Later, when Java was dogged by serious security issues, browsers and the Java browser plug-in became increasingly restrictive. Nowadays, it requires skill and dedication to get applets to work in your browser. Java goes back to , when a group of Sun engineers, led by Patrick Naughton and James Gosling a Sun Fellow and an all-around computer wizard , wanted to design a small computer language that could be used for consumer devices like cable TV switchboxes.


Since these devices do not have a lot of power or memory, the language had to be small and generate very tight code. Also, as different manufacturers may choose different central processing units CPUs , it was important that the language not be tied to any single architecture.


The people at Sun later realized that Oak was the name of an existing computer language, so they changed the name to Java. This turned out to be an inspired choice. Unfortunately, no one was interested in producing this at Sun, and the Green people had to find other ways to market their technology.


However, none of the standard consumer electronics companies were interested either. The group then bid on a project to design a cable TV box that could deal with emerging cable services such as video-ondemand.


They did not get the contract. Amusingly, the company that did was led by the same Jim Clark who started Netscape—a company that did much to make Java successful. No one was found. Patrick Naughton, one of the founders of the group and the person who ended up doing most of the marketing, claims to have accumulated , air miles in trying to sell the technology.


First Person was dissolved in While all of this was going on at Sun, the World Wide Web part of the Internet was growing bigger and bigger.


The key to the World Wide Web was the browser translating hypertext pages to the screen. In , most people were using Mosaic, a noncommercial web browser that came out of the supercomputing center at the University of Illinois in He moved on to fame and fortune as one of the cofounders and the chief of technology at Netscape.


So we built a browser. The browser was capable of executing Java code inside web pages. Sun released the first version of Java in early People quickly realized that Java 1. Sure, you could use Java 1. To be blunt, Java 1. Its successor, version 1. It was still rather limited, though. The big news of the JavaOne conference was the upcoming release of Java 1.


Three days! Besides the Standard Edition, two other editions were introduced: the Micro Edition for embedded devices such as cell phones, and the Enterprise Edition for server-side processing.


This book focuses on the Standard Edition. Versions 1. During this time, much of the performance, and, of course, quite a few bug fixes. During this time, much of the initial hype about Java applets and client-side applications abated, but Java became the platform of choice for server-side applications.


Version 5. This version was originally numbered 1. Version 6 without the. Again, there were no language changes but additional performance improvements and library enhancements. As datacenters increasingly relied on commodity hardware instead of specialized servers, Sun Microsystems fell on hard times and was purchased by Oracle in Development of Java stalled for a long time. In , Oracle released a new version, with simple enhancements, as Java 7. In , the release of Java 8 followed, with the most significant changes to the Java language in almost two decades.


All programming languages must evolve to stay relevant, and Java has shown a remarkable capacity to do so. The main feature of Java 9 goes all the way back to At that time, Mark Reinhold, the chief engineer of the Java platform, started an effort to break up the huge, monolithic Java platform. This was to be achieved by introducing modules, self-contained units of code that provide a specific functionality.


It took eleven years to design and implement a module system that is a good fit for the Java platform, and it remains to be seen whether it is also a good fit for Java applications and libraries.


Java 9, released in , has other appealing features that we cover in this book. Starting in , Java versions are released every six months, to enable faster introduction of features. Certain versions, such as Java 11, are designated as long-term support versions. Table 1. As you can see, the size of the application programming interface API has grown tremendously. Java is an extension of HTML.


Java is a programming language; HTML is a way to describe the structure of a web page. They have nothing in common except that there are HTML extensions for placing Java applets on a web page.


Java is a programming language; XML is a way to describe data. In addition, many important XML tools are implemented in Java. See Volume II for more information. Java is an easy programming language to learn. No programming language as powerful as Java is easy. You always have to distinguish between how easy it is to write toy programs and how hard it is to do serious work.


Also, consider that only seven chapters in this book discuss the Java language. The remaining chapters of both volumes show how to put the language to work, using the Java libraries. The Java libraries contain thousands of classes and interfaces and tens of thousands of functions.


Luckily, you do not need to know every one of them, but you do need to know surprisingly many to use Java for anything realistic. Java will become a universal programming language for all platforms. This is possible in theory. But in practice, there are domains where other languages are entrenched. Objective C and its successor, Swift, are not going to be replaced on iOS devices. Anything that happens in a browser is controlled by JavaScript. Java has the edge in server-side programming and in cross-platform client applications.


Java is just another programming language. The success of a programming language is determined far more by the utility of the support system surrounding it than by the elegance of its syntax. Are there useful, convenient, and standard libraries for the features that you need to implement?


Are there tool vendors that build great programming and debugging environments? Do the language and the toolset integrate with the rest of the computing infrastructure?


Java is successful because its libraries let you easily do things such as networking, web applications, and concurrency. The fact that Java reduces pointer errors is a bonus, so programmers seem to be more productive with Java—but these factors are not the source of its success. Java is proprietary, and should therefore be avoided. When Java was first created, Sun gave free licenses to distributors and end users.


Although Sun had ultimate control over Java, they involved many other companies in the development of language revisions and the design of new libraries. Source code for the virtual machine and the libraries has always been freely available, but only for inspection, not for modification and redistribution.


Oracle has committed to keeping Java open source. There is only one fly in the ointment—patents. Everyone is given a patent grant to use and modify Java, subject to the GPL, but only on desktop and server platforms. If you want to use Java in embedded systems, you need a different license and will likely need to pay royalties. However, these patents will expire within the next decade, and at that point Java will be entirely free.


Java is interpreted, so it is too slow for serious applications. In the early days of Java, the language was interpreted. Nowadays, the Java virtual machine uses a just-in-time compiler. All Java programs run inside a web page. All Java applets run inside a web browser. That is the definition of an applet—a Java program running inside a browser. But most Java programs are stand-alone applications that run outside of a web browser.


In fact, many Java programs run on web servers and produce the code for web pages. Java programs are a major security risk. In the early days of Java, there were some well-publicized reports of failures in the Java security system. Researchers viewed it as a challenge to find chinks in the Java armor and to defy the strength and sophistication of the applet security model.


The technical failures that they found have all been quickly corrected. Later, there were more serious exploits, to which Sun, and later Oracle, responded too slowly.


Browser manufacturers reacted, and perhaps overreacted, by deactivating Java by default. To keep this in perspective, consider the far greater number of virus attacks in Windows executable files that cause real grief but surprisingly little criticism of the weaknesses of the attacked platform.


Even 20 years after its creation, Java is far safer than any other commonly available execution platform. JavaScript is a simpler version of Java. JavaScript, a scripting language that can be used inside web pages, was invented by Netscape and originally called LiveScript. In particularly, Java is strongly typed—the compiler catches many errors that arise from type misuse.


In JavaScript, such errors are only found when the program runs, which makes their elimination far more laborious. Companies produced prototypes of Java-powered network computers, but users were not ready to give up a powerful and convenient desktop for a limited machine with no local storage.


Nowadays, of course, the world has changed, and for a large majority of end users, the platform that matters is a mobile phone or tablet. The majority of these devices are controlled by the Android platform, which is a derivative of Java.


Learning Java programming will help you with Android programming as well. You can run the JDK tools by typing commands in a terminal window. However, many programmers prefer the comfort of an integrated development environment.


You will learn how to use a freely available development environment to compile and run Java programs. Once you have mastered the techniques in this chapter and picked your development tools, you are ready to move on to Chapter 3, where you will begin exploring the Java programming language. Versions in various states of development exist for many other platforms, but those versions are licensed and distributed by the vendors of those platforms.


See Table 2. Table 2. Somewhat confusingly, versions 1. You will still find occasional references to the old term.


That is not what you want as a developer. It is intended for end users who have no need for the compiler. You might run into the term Java 2 that was coined in when the marketing folks at Sun felt that a fractional version number increment did not properly communicate the momentous advances of JDK 1. However, since they had that insight only after the release, they decided to keep the version number 1. Subsequent releases were numbered 1. The platform, however, was renamed from Java to Java 2.


Fortunately, in , the numbering was simplified. The next version of the Java Fortunately, in , the numbering was simplified.


This minor madness finally ran its course with Java SE 9, when the version number became 9, and then 9. Why not 9. To keep a modicum of excitement, the version number specification requires that trailing zeroes are dropped for the fleeting interval between a major release and its first security update.


Prior to Java 9, there were bit and bit versions of the Java Development Kit. The bit versions are no longer developed by Oracle. You need to have a bit operating system to use the Oracle JDK. With Linux, you have a choice between an RPM file and a. We recommend the latter—you can simply uncompress it anywhere you like. Now you know how to pick the right JDK. Linux: Pick the. Accept the license agreement and download the file. Note Depending on the constellation of the planets, Oracle may offer you a bundle that contains both the Java Development Kit and the NetBeans integrated development environment.


I suggest that you stay away from all bundles and install only the Java Development Kit at this time. Under Windows, launch the setup program. You will be asked where to install the JDK. Just take out the Program Files part of the path name. On the Mac, run the installer. Locate it with the Finder. On Linux, simply uncompress the. In this book, the installation directory is denoted as jdk. An Environment Variables dialog should appear. It may hide behind the Windows Settings dialog.


Locate and select a variable named Path in the User Variables list. Figure 2. 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 9. Unpack that file to get access to the source code. Simply do the following: 1. Make a directory javasrc in your home directory.


If you like, you can do this from a terminal window. Unzip the src. Tip The src. The documentation is contained in a compressed file that is separate from the JDK. You can download the documentation from www. Follow these steps: 1. Download the documentation zip file. It is called jdk Unzip the file and rename the doc directory into something more descriptive, like javadoc. You should also install the Core Java program examples. The programs are packaged into a zip file corejava.


Just unzip them into your home directory. They will be located in a directory corejava. The JDK contains nothing even remotely similar. You do everything by typing in commands in a terminal window. This sounds 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. Open a terminal window. The corejava directory is where you installed the source code for the book examples, as explained in Section 2. Enter the following commands: javac Welcome. You have just compiled and run your first Java program. What happened? The javac program is the Java compiler.


It compiles the file Welcome. 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, shown in Listing 2. You will see how it works in the next chapter. Listing 2. Any number of things can go wrong, leading to frustrating results. Pay attention to the following points: If you type in the program by hand, make sure you correctly enter the uppercase and lowercase letters. The compiler requires a file name Welcome. When you run the program, you specify a class name Welcome without a.


If javac reports that it cannot find the file Welcome. Under Linux, check that you used the correct capitalization for Welcome.


Under Windows, use the dir command, not the graphical Explorer tool. Some text editors in particular Notepad insist on adding an extension. If you use Notepad to edit Welcome.


Under the default Windows settings, Explorer conspires with Notepad and hides the. If you launch your program and get an error message complaining about a java. 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.


Reissue the command as java Welcome. It is not a good idea to set this variable globally, but some poorly written software installers in Windows do just that. Follow the same procedure as for setting the PATH environment variable, but this time, remove the setting. Note In JDK 11, the javac command is not required with a single source file. The Welcome program was not terribly exciting.


Next, try out a graphical application. This program is a simple image file viewer that loads and displays an image. As before, compile and run the program from the command line. Enter the following: javac ImageViewer. There are a couple of sample files in the same directory. The image is displayed see Figure 2.


That is a useful skill for troubleshooting, but for most day-today work, you should use an integrated development environment. In this chapter, you will learn how to get started with Eclipse. Of course, if you prefer a different development environment, you can certainly use it with this book. Here are the steps to write a program with Eclipse.


Click the Next button. Click the Finish button. The project is now created. Click on the triangles in the left pane next to the project until you locate the file Welcome. You should now see a pane with the program code see Figure 2.


With the right mouse button, click on the project name Welcome in the left pane. 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. 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 see Figure 2.


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. Click on the lightbulb to get a list of suggested fixes. Java 9 introduces another way of working with Java. You type a Java expression; JShell evaluates your input, prints the result, and waits for your next input. To start JShell, simply type jshell in a terminal window see Figure 2. JShell automatically prints the value of every expression that you enter.


However, you have to follow the Java syntax and specify both the type and the name. We will cover the syntax in Chapter 3. Type Math. Hit Enter when you are done. For example, hit and replace 0. In this chapter, you learned about the mechanics of compiling and running Java programs.


You are now ready to move on to Chapter 3 where you will start learning the Java language. This chapter shows you how the basic programming concepts such as data types, branches, and loops are implemented in Java. First and foremost, Java is case sensitive. If you made any mistakes in capitalization such as typing Main instead of main , the program will not run. The keyword public is called an access modifier; these modifiers control the level of access other parts of a program have to this code.


The keyword class reminds you that everything in a Java program lives inside a class. Although we will spend a lot more time on classes in the next chapter, for now think of a class as a container for the program logic that defines the behavior of an application. As mentioned in Chapter 1, classes are the building blocks with which all Java applications and applets are built.


Everything in a Java program must be inside a class. Following the keyword class is the name of the class. The rules for class names in Java are quite generous. Names must begin with a letter, and after that, they can have any combination of letters and digits. The length is essentially unlimited. You cannot use a Java reserved word such as public or class for a class name.


See the appendix for a list of reserved words. The standard naming convention which we follow in the name FirstSample is that class names are nouns that start with an uppercase letter. If a name consists of multiple words, use an initial uppercase letter in each of the words.


You need to make the file name for the source code the same as the name of the public class, with the extension. Thus, you must store this code in a file called FirstSample. If you have named the file correctly and not made any typos in the source code, then when you compile this source code, you end up with a file containing the bytecodes for this class. The Java compiler automatically names the bytecode file FirstSample. Finally, launch the program by issuing the following command: java FirstSample Remember to leave off the.


When the program executes, it simply displays the string We will not use 'Hello, World! When you use java ClassName to run a compiled program, the Java virtual machine always starts execution with the code in the main method in the class you indicate. Thus, you must have a main method in the source of your class for your code to execute. You can, of course, add your own methods to a class and call them from the main method.


We cover writing your own methods in the next chapter. Note According to the Java Language Specification, the main method must be declared public. The Java Language Specification is the official document that describes the Java language. However, several versions of the Java launcher were willing to execute Java programs even when the main method was not public. A programmer filed a bug report. The Java launcher in Java 1. There are a couple of interesting aspects about this story. On the one hand, it is frustrating to have quality assurance engineers, who are often overworked and not always experts in the fine points of Java, make questionable decisions about bug reports.


On the other hand, it is remarkable that Sun made the bug reports and their resolutions available for anyone to scrutinize, long before Java was open source. At one point, Sun even let programmers vote for their most despised bugs and used the vote counts to decide which of them would get fixed in the next JDK release. Brace styles have inspired an inordinate amount of useless controversy.


We follow a style that lines up matching braces. As whitespace is irrelevant to the Java compiler, you can use whatever brace style you like.


We will have more to say about the use of braces when we talk about the various kinds of loops. By the end of Chapter 4, you will understand this incantation completely. For example, in Java all functions are methods of some class.


The standard terminology refers to them as methods, not member functions. Thus, in Java you must have a shell class for the main method. These are member functions defined inside a class that do not operate on objects. The main method in Java is always static. If the main method exits normally, the Java program has the exit code 0, indicating successful completion.


To terminate the program with a different exit code, use the System. This method has only one statement in it. As with most programming languages, you can think of Java statements as sentences of the language.


In Java, every statement must end with a semicolon. In particular, carriage returns do not mark the end of a statement, so statements can span multiple lines if need be. The body of the main method contains a statement that outputs a single line of text to the console. Here, we are using the System. Notice the periods used to invoke a method. There's also live online events, interactive content, certification prep materials, and more.


Whatever version of Java you are using--up to and including Java this book will help you achieve a deep and practical understanding of the language and APIs. With hundreds of realistic examples, Cay S. Horstmann reveals the most powerful and effective ways to get the job done. This book is written for readers with prior programming experience who are looking for in-depth coverage of the Java language and platform.


You'll learn about all language features in detail, including the recent improvements in Java The applied chapters and code examples cover the most up-to-date capabilities of the vast Java library. For 25 years, Core Java has prepared serious programmers for serious Java programming. This first of two volumes offers in-depth coverage of fundamental Java programming, including object-oriented programming, generics, collections, lambda expressions, concurrency, and functional programming.


Classic material for Swing UI programming is included for those who need it. This edition's new content covers text blocks, switch enhancements, records, pattern matching for instanceof, sealed classes, and more.