Перевод материала "The history and evolution of Java" по книге "Java: the complete reference, seventh edition» by Herbert Schildt"
The birth of modern programming. The creation of Java. Апплеты языка Джава. Безопасность, мобильность, магические свойства, сервлеты. Терминология Джава: простота, объектная ориентированность, надежность, многопоточность, архитектурная нейтральность.
Рубрика | Иностранные языки и языкознание |
Вид | курсовая работа |
Язык | русский |
Дата добавления | 06.11.2020 |
Размер файла | 63,5 K |
Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже
Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.
Размещено на http://www.allbest.ru/
[Введите текст]
МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ
НАБЕРЕЖНОЧЕЛНИНСКИЙ ИНСТИТУТ (ФИЛИАЛ)
ФЕДЕРАЛЬНОГО ГОСУДАРСТВЕННОГО АВТОНОМНОГО ОБРАЗОВАТЕЛЬНОГО УЧРЕЖДЕНИЯ ВЫСШЕГО ОБРАЗОВАНИЯ
«КАЗАНСКИЙ (ПРИВОЛЖСКИЙ) ФЕДЕРАЛЬНЫЙ УНИВЕРСИТЕТ»
ЦЕНТР ДОПОЛНИТЕЛЬНОГО ОБРАЗОВАНИЯ
Зачетная работа
по дисциплине «Практикум по спецпереводу»
перевод материала«The history and evolution of Java»
по книге«Java: the complete reference, seventh edition» by Herbert Schildt
Выполнил студент гр.
Махмутова Алина Ильнуровна
Руководитель: Д.О.Жданов
Набережные Челны
2020
ОГЛАВЛЕНИЕ
1. THE HISTORY AND EVOLUTION OF JAVA
1.1 Java's Lineage
1.1.1 The birth of modern programming: C
1.1.2 С++: the next step
1.1.3 The stage is set for Java
1.2 The creation of Java
1.2.1 The C# connection
1.3 How Java changed the Internet
1.3.1 Java applets
1.3.2 Security
1.3.3 Portability
1.4 Java's magic: the bytecode
1.5 Servlets: Java on the server side
1.6 The Java Buzzwords
1.6.1 Simple
1.6.2 Object-oriented
1.6.3 Robust
1.6.4 Multithreaded
1.6.5 Architecture-Neutral
1.6.6 Interpreted and High Performance
1.6.7 Distributed
1.6.8 Dynamic
1.7 The Evolution of Java
1.7.1 Java SE 6
2. ИСТОРИЯ И ЭВОЛЮЦИЯ ПРОГРАММЫ ДЖАВА
2.1 Происхождение языка Джава
2.1.1 Рождение современного программирования: С
2.1.2 С++: следующий этап
2.1.3 Предпосылки к созданию Джава
2.2 Создание языка Джава
2.2.1 Связь с языком С#
2.3 Джава изменил интернет
2.3.1 Апплеты языка Джава
2.3.2 Безопасность
2.3.3 Мобильность
2.4 Магические свойства Джава: байт-код
2.5 Сервлеты: Джава на сервере
2.6 Терминология Джава
2.6.1 Простота
2.6.2 Объектная ориентированность
2.6.3 Надежность
2.6.4 Многопоточность
2.6.5 Архитектурная нейтральность
2.6.6 Интерпретация и высокая производительность
2.6.7 Распределенность
2.6.8 Динамичность
2.7 Эволюция Джава
2.7.1 Java SE 6
1. THEHISTORYANDEVOLUTIONOFJAVA
To fully understand Java, one must understand the reasons behind its creation, the forces that shaped it, and the legacy that it inherits. Like the successful computer languages that came before, Java is a blend of the best elements of its rich heritage combined with the innovative concepts required by its uniquemission. While there maining chapters of this book describe the practical aspects of Java--including its yntax, key libraries, and applications--this chapter explains how and why Java came about, what makes it so important, and how it has evolved over the years.
Although Java has become inseparably linked with the online environment of the Internet, it is important to remember that Java is first and fore most aprogramming language. Computer language innovation and development occurs for two fundamental reasons:
To adapt to changing environments and uses;
To implement refinements and improvements in the art of programming.
As you will see, the development of Java was driven by both elements in nearly equal measure.
1.1 Java's Lineage
Java is related to C++, which is a direct descendant of C. Much of the character of Java is inherited from these two languages. From C, Java derives its syntax. Many of Java's object-oriented features were influenced by C++. In fact, several of Java's defining characteristics come from--or are responses to--its predecessors. Moreover, the creation of Java was deeply rooted in the process of refinement and adaptation that has been occurring in computer programming languages for the past several decades. For these reasons, this section reviews the sequence of events and forces that led to Java. As you will see, each innovation in language design was driven by the need to solve a fundamental problem that the preceding languages could not solve. Java is no exception.
1.1.1 The birth of modern programming: C
The Clanguages hook the computer world. Its impacts hould not be underestimated, because it fundamentally changed the way programming was approached and thought about. The creation of C was a direct result of the need for a structured, efficient, high-level language that could replace assembly code when creating systems programs. As you probably know, when a computer language is designed, trade-offs are often made, such as the following:
Ease-of-use versus power;
Safety versus efficiency;
Rigidity versus extensibility.
Prior to C, programmers usually had to choose between languages that optimized one set of traits or the other. For example, although FORTRAN could be used to write fairly efficient programs for scientific applications, it was not very good for system code. And while BASIC was easy to learn, it wasn't very powerful, and its lack of structure made its usefulness questionable for large programs. Assembly language can be used to produce highly efficient programs, but it is not easy to learn or use effectively. Further, debugging assembly code can be quite difficult.
Another compounding problem was that early computer languages such as BASIC, COBOL, and FORTRAN were not designed around structured principles. Instead, they relied upon the GOTO as a primary means of program control. As a result, programs written using these languages tended to produce “spaghetti code”--a mass of tangled jumps and conditional branches that make a program virtually impossible to understand. While languages like Pascal are structured, they were not designed for efficiency, and failed to include certain features necessary to make them applicable to a wide range of programs. (Specifically, given the standard dialects of Pascal available at the time, it was not practical to consider using Pascal for systems-level code.)
So, just prior to the invention of C, no one language had reconciled the conflicting attributes that had dogged earlier efforts. Yet the need for such a language was pressing. By the early 1970s, the computer revolution was beginning to take hold, and the demand for software was rapidly outpacing programmers' ability to produce it. A great deal of effort was being expended in academic circles in an attempt to create a better computer language. But, and perhaps most importantly, a secondary force was beginning to be felt. Computer hardware was finally becoming common enough that a critical mass was being reached. No longer were computers kept behind locked doors. For the first time, programmers were gaining virtually unlimited access to their machines. This allowed the freedom to experiment. It also allowed programmers to begin to create their own tools. On the eve of C's creation, the stage was set for a quantum leap forward in computer languages.
Invented and first implemented by Dennis Ritchie on a DEC PDP-11 running the UNIX operating system, C was the result of a development process that started with an older language called BCPL, developed by Martin Richards. BCPL influenced a language called B, invented by Ken Thompson, which led to the development of C in the 1970s. For many years, the de facto standard for C was the one supplied with the UNIX operating system and described in The C Programming Language by Brian Kernighan and Dennis Ritchie (Prentice-Hall, 1978). C was formally standardized in December 1989, when the American National Standards Institute (ANSI) standard for C was adopted.
The creation of C is considered by many to have marked the beginning of the modern age of computer languages. It successfully synthesized the conflicting attributes that had so troubled earlier languages. The result was a powerful, efficient, structured language that was relatively easy to learn. It also included one other, nearly intangible aspect: it was a programmer's language. Prior to the invention of C, computer languages were generally designed either as academic exercises or by bureaucratic committees. C is different. It was designed, implemented, and developed by real, working programmers, reflecting the way that they approached the job of programming. Its features were honed, tested, thought about, and rethought by the people who actually used the language. The result was a language that programmers liked to use. Indeed, C quickly attracted many followers who had a near-religious zeal for it. As such, it found wide and rapid acceptance in the programmer community. In short, C is a language designed by and for programmers. As you will see, Java inherited this legacy.
1.1.2 С++: the next step
During the late 1970s and early 1980s, C became the dominant computer programming language, and it is still widely used today. Since Cisa successful and useful language, you might task why a need for something else existed. The answer is complexity. Throughout the history of programming, the increasing complexity of programs has driven the need for better ways to manage that complexity. C++is are sponge to that need. To better understand why managing gprogram complexity is fundamental to the creation no f C++, consider the following.
Approaches to programming have changed dramatically since the invention of the computer. For example, when computers were first invented, programming was done by manually toggling in the binary machine instructions by use of the front panel. As long as programs were just a few hundred instructions long, this approach worked. As programs grew, assembly language was invented so that a programmer could deal with larger, increasingly complex programs byu sing symbolic representations of the machine instructions. As programs continued to grow, high-level languages were introduced that gave the programmer more tools with which to handle complexity.
The first wide spread language was, of course, FORTRAN. While FORTRAN was an impressive firststep, it is hardly a language that encourages clear and easy-to-understand programs. The 1960s gave birth to structured programming. This is the method of programming championed by languages such as C. The use of structured languages enabled programmers to write, for the first time, moderately complex programs fairly easily. However, even with structured programming methods, once a project reaches a certain size, its complex it exceeds what a programmer can manage. By the early 1980s, many projects were pushing the structured approach past its limits. To solve this problem, a new way to program was invented, called object-oriented programming(OOP). Object-oriented programming is discussed in detail later in this book, but here is a brief definition: OOP is a programming methodology that helps organize complex programs through the use of inheritance, encapsulation, and polymorphism.
In the final analysis, although C is one of the world's great programming languages, there is a limit to its ability to handle complexity. Once the size of a program exceeds a certain point, it becomes so complex that it is difficult to grasp as a totality. While the precise size at which this occurs differs, depending upon both the nature of the program and the programmer, there is always a threshold at which a program becomes unmanageable. C++ added features that enabled this threshold to be broken, allowing programmers to comprehend and manage larger programs.
C++ was invented by Bjarne Stroustrup in 1979, while he was working at Bell Laboratories in Murray Hill, New Jersey. Stroustrupinitially called the new language “Cwith Classes.” However, in1983, the name was changed to C++.C++ extends C by adding object-oriented features. Because C++ is built on the foundation of C, it includes all of C's features, attributes, and benefits. This is a crucial as on for the success of C++as a language. The invention of C++ was not an attempt to create a completely new programming language. Instead, it was an enhancement to an already highly successful one.
1.1.3 The stage is set for Java
By the end of the 1980s and the early 1990s, object-oriented programming using C++ took hold. Indeed, for a brief moment it seemed as if programmers had finally found the perfect language. Because C++ blended the high efficiency and stylistic elements of C with the object-oriented paradigm, it was a language that could be used to create a wide range of programs. However, just as in the past, forces were brewing that would, once again, drive computer language evolution forward. Within a few years, the World Wide Web and the Internet would reach critical mass. This event would precipitate another revolution in programming.
1.2 The creation of Java
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called “Oak,” but was renamed “Java” in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, v many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype.
Some what surprisingly, the original impetus for Java was not the Internet! Instead, the primary motivation was the need for a platform-independent (that is, architecture-neutral) language that could be used to create software to be embedded invarious consumer electronic devices, such as microwave oven sand remote controls. As you can probably guess, many different types of CPU sare used as controllers. The trouble with C and C++ (and most of her languages) is that they are designed to be compiled for as pacific argent. Although it is possible to compile C++program for just about any type of CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is that compilers are expensive and time-consuming to create. Aneasier--andmorecost-efficient--solution was needed. In an attempt to find such a solution, Gosling and others began work on a portable, platform-independent language that could be used to produce code that would run on a variety of CPU sunder differing environments. This effort ultimately led to the creation of Java.
About the time that the details of Java were being worked out, a second, and ultimately more important, factor was emerging that would play a crucial role in the future of Java. This second force was, of course, the World Wide Web. Had the Web not taken shape at about the same time that Java was being implemented, Java might have remained a useful but obscure language for programming consumer electronics. However, with the emergence of the World Wide Web, Java was propelled to the forefront of computer language design, because the Web, too, demanded portable programs.
Mostprogrammerslearnearlyintheircareersthatportableprogramsareaselusiveasthey aredesirable.Whilethequestforawaytocreateefficient,portable(platform-independent) programs is nearly as old as the discipline of programming itself, it had taken a back seat to other, more pressing problems. Further, because (at that time) much of the computer world had divided itself into the three competing camps of Intel, Macintosh, and UNIX, most programmers stayed within their fortified boundaries, and the urgent need for portable code was reduced. However, with the advent of the Internet and the Web, the old problem of portability returned with a vengeance. After all, the Internet consists of a diverse, distributed universe populated with various types of computers, operating systems, and CPUs. Even though many kinds of platforms are attached to the Internet, users would like them all to be able to run the same program. What was once an irritating but low-priority problem had become a high-profile necessity.
By 1993, it became obvious to members of the Java design team that the problems of portability frequently encountered when creating code for embedded controllers are also found when attempting to create code for the Internet. In fact, the same problem that Java was initially designed to solve on a small scale could also be applied to the Internet on a large scale. This realization caused the focus of Java to switch from consumer electronics to Internet programming. So, while the desire for an architecture-neutral programming language provided the initial spark, the Internet ultimately led to Java's large-scale success.
As mentioned earlier, Java derives much of its character from C and C++. This is by intent. The Java designers knew that using the familiar syntax of C and echoing the object-oriented features of C++ would make their language appealing to the legions of experienced C/C++ programmers. In addition to the surface similarities, Java shares some of the other attributes that helped make C and C++ successful. First, Java was designed, tested, and refined by real, working programmers. It is a language grounded in the needs and experiences of the people who devised it. Thus, Java is a programmer's language. Second, Java is cohesive and logically consistent. Third, except for those constraints imposed by the Internet environment, Java gives you, the programmer, full control. If you program well, your programs reflect it. If you program poorly, your programs reflect that, too. Put differently, Java is not a language with training wheels. It is a language for professional programmers.
Because of the similar ivies between Java and C++, it is tempting to think of Java as simply the “Internet version of C++.” However, to do so would be a large mistake. Java has significant practical and philosophical differences. While it is true that Java was influenced by C++, it is not an enhanced version of C++. For example, Java is neither up wardly nor down wardly compatible withC++.Ofcourse, the similarities with C++are significant, and if you area C++programmer, then you will feel right at home with Java. One other point: Java was not designed to replace C++. Java was designed to solve a certain set of problems. C++ was designed to solve a different set of problems. Both will coexist for many years to come.
As mentioned at the start of this chapter, computer languages evolve for two reasons: to adapt to changes in environment and to implement advances in the art of programming. The environmental change that prompted Java was the need for platform-independent programs destined for distribution on the Internet. However, Java also embodies changes in the way that people approach the writing of programs. For example, Java enhanced and refined the object-oriented paradigm used by C++, added integrated support for multithreading, and provided a library that simply feed Internet access. In the final analysis, though, it was not the individual features of Java that made it so remarkable. Rather, it was the language as a whole. Java was the perfect response to the demand soft he then newly emerging, highly distributed computing universe. Java was to Internet programming what C was to system programming: a revolutionary force that changed the world.
1.2.1 The C# connection
The reach and power of Java continues to be felt in the world of computer language development. Many of its innovative features, constructs, and concepts have become part of the baseline for any new language. The success of Java is simply too important to ignore.
Perhaps the most important example of Java's influence is C#. Created by Microsoft to support the .NET Framework, C# is closely related to Java. For example, both share the same general syntax, support distributed programming, and utilize the same object model. There are, of course, differences between Java and C#, but the overall “look and feel” of these languages is very similar. This “cross-pollination” from Java to C# is the strongest testimonialtodatethatJavaredefinedthewaywethinkaboutanduseacomputerlanguage.
1.3 How Java changed the Internet
The Internet helped catapult Java to the forefront of programming, and Java, in turn, had a profound effect on the Internet. In addition to simplifying web programming in general, Java innovated a new type of networked program called the applet that changed the way the online world thought about content. Java also addressed some of the thorniest issues associated with the Internet: portability and security. Let's look more closely at each of these.
1.3.1 Java applets
An applet is a special kind of Java program that is designed to be transmitted over the Internet and automatically executed by a Java-compatible web browser. Furthermore, an applet is downloaded on demand, without further interaction with the user. If the user clicks a link that contains an applet, the applet will be automatically downloaded and run in the browser. Applets are intended to be small programs. They are typically used to display data provided by the server, handle user input, or provide simple functions, such as a loan calculator, that execute locally, rather than on the server. In essence, the applet allows some functionality to be moved from the server to the client.
The creation of the applet changed Internet programming because it expanded the universe of objects that can move about freely in cyberspace. In general, there are two very broad categories of objects that are transmitted between the server and the client: passive information and dynamic, active programs. For example, when you ready our e-mail, you are viewing passive data. Even when you down load a program, the program's code is still only passive data until you execute it. By contrast, the apple t is a dynamic, self-executing program. Such a program is an active gent on the client computer, yet it is initiated by the server.
As desirable as dynamic, networked programs are, they also present serious problems in the areas of security and portability. Obviously, a program that downloads and executes automatically on the client computer must be prevented from doing harm. It must also be able to run in a variety of different environments and under different operating systems. As you will see, Java solved these problems in an effective and elegant way. Let's look a bit more closely at each.
1.3.2 Security
As you are likely aware, every time you download a “normal” program, you are taking a risk, because the code you are downloading might contain a virus, Trojan horse, or other harmful code. At the core of the problem is the fact that malicious code can cause its damage because it has gained un authorized access to system resources. For example, a virus program might gather private information, such as credit card numbers, bank account balances, and passwords, by searching the contents of your computer's local file system. In order for Java to enable applets to be downloaded and executed on the client computer safely, it was necessary to prevent an applet from launching such an attack.
JavaachievedthisprotectionbyconfininganapplettotheJavaexecutionenvironment and not allowing it access to other parts of the computer. (You will see how this is accomplished shortly.) The ability to download applets with confidence that no harm will be done, and that no security will be breached is considered by many to be the single most innovative aspect of Java.
1.3.3 Portability
Portability is a major aspect of the Internet because there are many different types of computers and operating systems connected to it. If a Java program were to be run on virtually any computer connected to the Internet, there needed to be some way to enable that program to execute on different systems. For example, in the case of an applet, the same applet must be able to be downloaded and executed by the wide variety of CPUs, operating systems, and browsers connected to the Internet. It is not practical to have different versions of the applet for different computers. The same code must work on all computers. Therefore, some means of generating portable executable code was needed. As you will soon see, the same mechanism that help censure security also helps create portability.
1.4 Java's magic: the byte code
ThekeythatallowsJavatosolveboththesecurityandtheportabilityproblemsjustdescribed is that the output of a Java compiler is not executable code. Rather, it is byte code. Byte code is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). In essence, the original JVM was designed as an interpreter for byte code. This may come as a bit of a surprise since many modern languages are designed to be compiled into executable code because of performance concerns. However, the fact that a Java program is executed by the JVM helps solve them a jor problems associated with web-based programs. Here is why.
Translating a Java program into by te code makes it much easier to run a program in a wide variety of environments because only the JVM needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. Remember, although the details of the JVM will differ from platform to platform, all understand the same Java by tecode. If a Java program were compiled to native code, then different versions of the same program would have to exist for each type of CPU connected to the Internet. This is, of course, not a feasible solution. Thus, the execution of by tecode by the JVM is the easiest way to create truly portable programs.
The fact that a Java program is executed by the JVM also helps to make it secure. Because the JVM is in control, it can contain the program and prevent it from generating side effects outside of the system. As you will see, safety is also enhanced by certain restrictions that exist in the Java language.
In general, when a program is compiled to an intermediate form and then interpreted by a virtual machine, it runs slower than it would run if compiled to executable code. However, with Java, the differential between the two is not so great. Because by tecode has been highly optimized, the use of by tecode enables the JVM to execute programs much faster than you might expect.
AlthoughJavawasdesignedasaninterpretedlanguage,thereisnothingaboutJava that prevents on-the-fly compilation of by tecode into native code in order to boost performance. For this reason, Sun began supplying its HotSpot technology not long after Java's initial release. Hot Spot provides a Just-In-Time (JIT) compiler for by tecode. When a JIT compiler is part of the JVM, selected portions of by tecode are compiled into executable code in real time, on a piece-by-piece, demand basis. It is important to understand that it is not practical to compile an entire Java program into executable code all at once, because Java performs various run-time checks that can be done only at run time. Instead, a JIT compiler compiles code as it is needed, during execution. Furthermore, not all sequences of by tecode are compiled--only those that will benefit from compilation. The remaining code is simply interpreted. However, the just-in-time approach still yields a significant performance boost. Even when dynamic compilation is applied to by tecode, the portability and safety features still apply, because the JVM is still in charge of the execution environment.
1.5 Serv lets: Java on the server side
As useful as applets can be, they are just one half of the client/server equation. Not long after the initial release of Java, it became obvious that Java would also be useful on the server side. The result was the servlet. Aserv let is a small program that executes on the server. Just as applets dynamically extend the functionality of a web browser, serv lets dynamically extend the functionality of a web server. Thus, with the advent of the serv let, Java spanned both sides of the client/server connection.
Serv lets are used to create dynamically generated content that is then served to the client. For example, an online store might use a serv let to look up the price for an item in a database. The price information is then used to dynamically generate a web page that is sent to the browser. Although dynamically generated content is available through mechanisms such as CGI (Common Gateway Interface), the servlet offers several advantages, including increased performance.
Because servlets (like all Java programs) are compiled into bytecode and executed by the JVM, they are highly portable. Thus, the same servlet can be used in a variety of different server environments. The only requirements are that the server support the JVM and a servlet container.
1.6 The Java Buzzwords
No discussion of Java's history is complete without a look at the Java buzzwords. Although the fundamental forces that necessitated the invention of Java are portability and security, other factors also played an important role in molding the final form of the language. The key considerations were summed up by the Java team in the following list of buzzwords:
Simple;
Secure;
Portable;
Object-oriented;
Robust;
Multithreaded;
Architecture-neutral;
Interpreted;
High performance;
Distributed;
Dynamic.
Two of these buzzwords have already been discussed: secure and portable. Let's examine what each of the others implies.
1.6.1 Simple
Java was designed to be easy for the professional programmer to learn and use effectively. Assuming that you have some programming experience, you will not find Java hard to master. If you already understand the basic concepts of object-oriented programming, learning Java will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java.
1.6.2 Object-oriented
Although influenced by its predecessors, Java was not designed to be source-codecompatible with any other language. This allowed the Java team the freedom to design with a blank slate. One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing liberally from many seminal object-software environments of the last few decades, Java manages to strike a balance between the purist's “everything is an object” paradigm and the pragmatist's “stay out of my way” model. The object model in Java is simple and easy to extend, while primitive types, such as integers, are kept as high-performance no objects.
1.6.3 Robust
The multiplatform environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of Java. To gain reliability, Java restricts you in a few key areas to force you to find your mistakes early in program development. At the same time, Java frees you from having to worry about many of the most common causes of programming errors. Because Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time. Many hard-to-track-down bugs that often turn up in hard-to-reproduce run-time situations are simply impossible to create in Java. Knowing that what you have written will behave in a predictable way under diverse conditions is a key feature of Java.
To better understand how Java is robust, consider two of the main reasons for program failure: memory management mistakes and mishandled exceptional conditions (that is, run-time errors). Memory management can be a difficult, tedious task in traditional programming environments. For example, in C/C++, the programmer must manually allocate and free all dynamic memory. This some times leads top рproblems, because programmers will either forget to free memory that has been previously allocated or, worse, try to free some memory that another part of their code is still using. Java virtually eliminateshese problems by managing memory allocation and dislocation for you. (Infact, deallocationis completely automatic, because Java provides garbage collection for unused objects.) Exceptional conditions intraditional environments often a rise in situations such as division by zeroor “file not found,” and they must be managed with clumsy and hard-to-read constructs. Java helps in this area byprovidingobject-oriented exception handling. Inawell-written Javaprogram, allrun-time errorscan--and should--bemanaged by your program.
1.6.4 Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneously. The Java run-time system comes with an elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems. Java's easy-to-use approach to multithreading allows you to think about the specific behavior of your program, not the multitasking subsystem.
1.6.5 Architecture-Neutral
Acentral issue for the Java designers was that of code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow--even on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java designers made several hard decisions in the Java language and the Java Virtual Machine in an attempt to alter this situation. Their goal was “write once; run anywhere, anytime, forever.” To a great extent, this goal was accomplished.
1.6.6 Interpreted and High Performance
As described earlier, Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java by tecode. This code can be executed on any system that implements the Java Virtual Machine. Most previous attempts at cross-platform solutions have done so at the expense of performance. As explained earlier, the Java by tecode was carefully designed so that it would be easy to translate directly into nativemachinecodeforveryhighperformancebyusingajust-in-timecompiler.Javarun-time systems that provide this feature lose none of the benefits of the platform-independent code.
1.6.7 Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. In fact, accessing a resource using a URLis not much different from accessing a file. Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke methods across a network.
1.6.8 Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the Java environment, in which small fragments of by tecode may be dynamically updated on a running system.
1.7 The Evolution of Java
The initial release of Java was nothing short of revolutionary, but it did not mark the end of Java's era of rapid innovation. Unlike most other software systems that usually settle into a pattern of small, incremental improvements, Java continued to evolve at an explosive pace. Soon after the release of Java 1.0, the designers of Java had already created Java 1.1. The features added by Java 1.1 were more significant and substantial than the increase in the minor revision number would have you think. Java 1.1 added many new library elements, redefined the way events are handled, and reconfigured many features of the 1.0 library. It also deprecated (rendered obsolete) several features originally defined by Java 1.0. Thus, Java 1.1 both added to and subtracted from attributes of its original specification.
The next major release of Java was Java 2, where the “2” indicates “second generation.” The creation of Java 2 was a watershed event, marking the beginning of Java's “modern age.” The first release of Java 2 carried the version number 1.2. It may seem odd that the first release of Java 2 used the 1.2 version number. The reason is that it originally referred to the internal version number of the Java libraries, but then was generalized to refer to the entire release. With Java 2, Sun repackaged the Java product as J2 SE (Java 2 Platform Standard Edition), and the version numbers began to be applied to that product.
Java 2 added support for a number of new features, such as Swing and the Collections Framework, and it enhanced the Java Virtual Machine and various programming tools. Java 2 also contained a few deprecations. The most important affected the Thread class in which the methods suspend( ), resume( ), and stop( ) were deprecated.
J2 SE 1.3 was the first major upgrade to the original Java 2 release. For the most part, it added to existing functionality and “tightened up” the development environment. In general, programs written for version 1.2 and those written for version 1.3 are source-code compatible. Although version 1.3 contained a smaller set of changes than the preceding three major releases, it was nevertheless important.
The release of J2 SE 1.4 further enhanced Java. This release contained several important upgrades, enhancements, and additions. For example, it added the new keyword assert, chained exceptions, and a channel based I/O subsystem. It also made changes to the Collections Framework and the networking classes. In addition, numerous small changes were made throughout. Despite the significant number of new features, version 1.4 maintained nearly 100 percent source-code compatibility with prior versions.
Then extrelease of Java was J2 SE5, and it was revolutionary. Unlike most of the previous Javaupgrades,whichofferedimportant,butmeasuredimprovements,J2 SE5fundamentally expanded the scope, power, and range of the language. To grasp the magnitude of the changes that J2 SE 5 made to Java, consider the following list of its major new features:
Generics;
Annotations;
Autoboxing and auto-unboxing;
Enumerations;
Enhanced, for-each style for loop;
Variable-length arguments (varargs);
Static import;
Formatted I/O;
Concurrency utilities;
This is not a list of minor tweaks or incremental upgrades. Each item in the list represents a significant addition to the Java language. Some, such as generics, the enhanced for, and varargs, introduce new syntax elements. Others, such as auto boxing and auto-unboxing, alter the semantics of the language. Annotations add an entirely new dimension to programming. In all cases, the impact of these additions went beyond their direct effects. They changed the very character of Java itself.
The importance of these new features is reflected in the use of the version number “5.” The next version number for Java would normally have been 1.5. However, the new features were so significant that a shift from 1.4 to 1.5 just didn't seem to express the magnitude of the change. Instead, Sun elected to increase the version number to 5 as a way of emphasizing that a major event was taking place. Thus, it was named J2 SE 5, and the developer's kit was called JDK 5. However, in order to maintain consistency, Sun decided to use 1.5 as its internal version number, which is also referred to as the developer version number. The “5” in J2 SE 5 is called the product version number.
1.7.1 Java SE 6
ThenewestreleaseofJavaiscalledJavaSE6,andthematerialinthisbookhasbeenupdated to reflect this latest version of Java. With the release of Java SE 6, Sun once again decided to change the name of the Java platform. First, notice that the “2” has been dropped. Thus, the platform now has the name Java SE, and the official product name is Java Platform, Standard Edition 6. As with J2 SE 5, the 6 in Java SE 6 is the product version number. The internal, developer version number is 1.6.
Java SE 6 builds on the base of J2 SE 5, adding incremental improvements. Java SE 6 adds no major features to the Java language proper, but it does enhance the API libraries, add several new packages, and offer improvements to the run time. As it relates to this book, it is the changes to the core API that are the most notable. Many of the packages have new classes, and many of the classes have new methods. These changes are indicated throughout the book. In general, the release of Java SE 6 serves to further solidify the advances made by J2 SE 5.
2. ИСТОРИЯ И ЭВОЛЮЦИЯ ПРОГРАММЫ ДЖАВА
Для полного понимания программы Джава необходимо изучить причины создания, процесс формирования и наследие данной программы. Также как и многие другие удачные компьютерные языки, предшествовавшие ей, Джава включает в себя лучшие элементы из своего богатого наследия в сочетании с инновационными концепциями, предусмотренными для его уникальной миссии. В то время как остальные главы данной книги описывают практические аспекты Джава - включая ее синтаксис, ключевую библиотеку и приложения - в этой главе объясняется, как и почему Джава появилась, что делает ее столь важной и как она развивалась на протяжении многих лет.
Несмотря на то, что язык Джава неразрывно связана со средой интернета, очень важно помнить: Джава - это прежде всего язык программирования. Развитие компьютерных языков происходит по двум основным причинам:
Адаптация к постоянно меняющейся среде;
Улучшение навыков в области программирования.
Позже вы увидите, что развитие Джава зависело от обоих этих причин в равной мере.
2.1 Происхождение языка Джава
Джава связана с языком С++, который в свою очередь является прямым потомком программы С. Большую часть своих особенностей Джава приобрела от этих двух языков. Причем от С Джава получает свой синтаксис, а многие объектно-ориентированные функции от С++. На самом деле, несколько определяющих особенностей изучаемая нами программа унаследовала от ее предшественников. Кроме того, создание Джава глубоко укоренилось в процессе доработки и адаптации, происходящем в компьютерных языках программирования на протяжении последних нескольких десятилетий. Именно по этим причинам в этом разделе рассматривается последовательность событий, приведших к появлению Джава. И каждое новшество в структуре языка было обусловлено необходимостью решения фундаментальных проблем, которые не могли решить предшествующие ей языки. И Джава также не исключение.
Рождение современного программирования: С
Язык С стал потрясениям для всего компьютерного мира. Его влияние нельзя недооценивать, поскольку он кардинально изменил подход к программированию. Создание C стало прямым ответом на потребность в структурированном, эффективном языке высокого уровня, который мог бы заменить код сборки при создании системных программ. Как вы, вероятно, уже знаете, при разработке компьютерного языка часто приходится идти на компромиссы между:
Легкостью использования и экономией энергопотребления;
Безопасностью и эффективностью;
Устойчивостью и расширяемостью.
До языка С, программистам обычно приходилось выбирать между языками, оптимизирующими один или другой набор характеристик. К примеру, хотя язык программирования Фортран использовали для написания достаточно эффективных программ с применением в науке, для написания системного кода это был не очень хороший вариант. Также простой в изучении язык Бейсик мощностью значительно отставал, а отсутствие структуры ставило под сомнение его полезность для написания крупных программ. Язык сборки можно использовать для создания высокоэффективных программ, но его непросто изучить и эффективно использовать. Кроме того, отладка кода сборки может стать довольно сложной задачей.
Еще одной сложной проблемой было то, что ранние компьютерные языки, такие как Бейсик, Кобол и Фортран, не были разработаны на основе структурированных принципов. Вместо этого они полагались на оператор «goto» как на основное средство управления программами. В результате, написанные на этих языках, программы, как правило, выдавали, так называемые, «макаронные коды» - массу запутанных переходов и условных ветвей, благодаря которым программу практически невозможно было прочесть. И в то время как языки, подобные Паскалю, структурированы, они не были рассчитаны на эффективность, и не включали определённые функции, необходимые для применения к широкому спектру программ. (В частности, учитывая имеющиеся в то время стандартные диалекты Паскаля, было нецелесообразно рассматривать использование Паскаля для кода системного уровня.)
Таким образом, до изобретения языка C ни одному языку не удавалось разрешить существовавшие в то время противоречия в программировании. Тем не менее необходимость в таком языке возрастала. В начале 1970-х годов вспыхнула компьютерная революция, и спрос на программное обеспечение быстро превзошел возможности программистов по его производству. В академических кругах прилагались огромные усилия для создания лучшего компьютерного языка. И наконец, начинала ощущаться влияние еще одного важного фактора. Компьютерное оборудование стало, наконец, достаточно распространенным, чтобы достичь «критической массы». Компьютеры больше не хранились за закрытыми дверями. Впервые программисты получили открытый доступ к своим вычислительным машинам. Это позволило многим свободно проводить свои эксперименты. А программисты начали создавать собственные инструменты. На кануне создания языка C произошел большой скачок в области в программирования.
Язык С, придуманный и впервые реализованный Деннисом Ритчи на мини-ЭВМDEC PDP-11,работавшей под управлением операционной системы UNIX, стал результатом процесса разработки, начавшегося с раннего языка под названием BCPL, разработанного Мартином Ричардсом. BCPL повлиял на язык под названием B, изобретённый Кеном Томпсоном, что привело к развитию C в 1970-х годах. В течение многих лет фактическим стандартом для C была версия, поставляемая вместе с операционной системой UNIX и описанная в книге «Язык программирования С» Брайаном Керниганом и Деннисом Ритчи. Язык C был официально стандартизирован в декабре 1989 года, когда Американский национальный институт стандартов принял стандарт на C.
Создание C многие считают началом новой эпохи развития программирования. С успешно соединил в себе противоречащие друг другу особенности, которые доставляли неприятности в более ранних языках. Результатом стал мощный, эффективный, структурированный и в то же время легкий для изучения язык. Он также включал в себя еще одну, почти недостижимую, особенность: это был язык специально для программистов. До появления С, компьютерные языки в основном разрабатывались либо как академические упражнения, либо комитетами бюрократии. Язык С совсем другой. Он был разработан, внедрен и усовершенствован реальными программистами, размышлявшими о пути подхода к работе программистов. Его характеристики были отточены, протестированы и переосмыслены пользователями данного языка. В итоге появился язык, который был по нраву многим программистам. И действительно, С быстро привлек к себе внимание последователей, которые имели почти религиозное рвение к нему. Он приобрел широкое признание в мире программистов. В общем, язык С представляет собой язык созданный программистами и для программистов. Как вы увидите в дальнейшем, Джава унаследует это от языка С.
С++: следующий этап
В конце 1970-х и в начале 1980-х годов С обрел статус самого значимого компьютерного языка, и по сей день этот язык широко известен среди программистов. Наверняка, вы задались вопросом, раз существует такой совершенный язык как С, зачем нам нужен какой-то другой. Ответ - сложность. На протяжении всей истории создания программных языков увеличение сложности программ привело к необходимости поиска более усовершенствованных и упрощенных способов их написания. Язык С++ стал решением этой проблемы. Чтобы лучше понять почему сложность программ стала фундаментальной причиной разработки языка С++, читайте ниже.
Подход к программированию кардинально изменился со времен создания компьютера. К примеру, когда компьютеры были только изобретены, программирование заключалось в ручном наборе двоичного машинного кода, используя переднюю панель. Пока программы содержали всего несколько сотен кодов, этот подход работал. По мере роста кодов были изобретены программы сборки, так программисты смогли работать с более большим и сложным набором кодов, за счет использования символических представлений кодов машины. Чем сложнее становились коды, тем более качественные программы разрабатывались программистами, предоставлявшие больше возможностей для написания сложных кодов.
Фортран - это первый язык, ставший известным во всем мире. Хоть Фортран и стал первым впечатляющим этапом в программировании, его вряд ли можно считать языком, который создает ясные и простые для понимания программы.1960-е года известны созданием структурного программирования. Наиболее ярко эта методика проявилась в языках С. Использование структурированных языков позволило программистам легко создавать программы средней сложности. Однако даже при таких методах программирования, как только проект достигал определенных масштабов, программисты не могли справиться с управлением. В начале 1980-х годов для многих проектов применение структурированного подхода было уже недостаточно. Для решения этой проблемы изобрели новый способ программирования, называемый объектно-ориентированным программированием (ООП).В последующих главах мы подробно обсудим объектно-ориентированное программирование, а пока его краткое определение: OOП - это методика программирования, которая помогает организовывать сложные программы через использование наследования, инкапсуляции и полиморфизма.
...Подобные документы
Joseph Niepce as the first photograph. The birth of modern photography. Negative to positive process. The first camera with a uniform mirror lens. Evolution and color photographs. Digital camera, modern functions and main technological boundary.
презентация [1,2 M], добавлен 25.02.2012Acquaintance with history of creation of the British army, its fighting achievements in wars in the Gulf, Afghanistan, Northern Ireland. The characteristic of a modern condition of Army: formation, structure, categories, distinctions, special forces.
реферат [82,0 K], добавлен 14.04.2010Развитие дипломатического языка на территории Сербии. Структурно-семантический и функциональный анализ дипломатической лексики. Понятие термина и терминологии. Дипломатическая лексика сербского языка - часть административно-делового функционального стиля.
курсовая работа [114,6 K], добавлен 21.03.2011Historical background of the History of English. Assimilative Vowel Changes: Breaking and Diphthongisation. Old English phonetics and grammar. Morphological classification of nouns. Evolution of the grammatical system. Personal and possessive pronouns.
курс лекций [104,6 K], добавлен 23.07.2009The old Germanic languages, their classification and principal features. The chronological division of the History of English. The role of the Wessex dialect. The Norman Conquest and its effect on English. The Germanic languages in the modern world.
контрольная работа [34,7 K], добавлен 17.01.2010Borrowing as a method of new word formation. History of military borrowing from Latin and Old Norse. The etymology and modern functions of military loanwords. The use of borrowed terms in historical fiction and fantasy genre. Non-military modern meanings.
курсовая работа [274,2 K], добавлен 08.05.2016Терминология как особый пласт языка. Место термина в языковой системе, его структура. Терминообразование, многозначность и вариантность соответствий в переводе терминов в сфере внешней торговли с английского на русский язык. Термины без эквивалента.
курсовая работа [87,7 K], добавлен 03.12.2011Перевод предложений с английского языка на русский. Функции окончаний, их грамматические признаки. Определения, выраженные именем существительным. Формы сравнения, перевод неопределенные местоимений. Видовременные формы глаголов и их инфинитивы.
контрольная работа [15,8 K], добавлен 29.05.2012Чтение, письменный и устный перевод текста с английского языка на русский, с русского языка на английский. Составление англо-русского словаря по специальности. Написание сочинения на тему "At the Barber's". Письменные ответы на вопросы на ангийском языке.
контрольная работа [19,3 K], добавлен 16.04.2010Терминология как особая подсистема лексического состава языка. Определение, выражение и специфика спортивной терминологии. Структурно–семантические характеристики спортивных терминов. Особенности функционирования терминов в русском и польском языках.
дипломная работа [65,6 K], добавлен 26.04.2014Терминология как лексическая категория. Эволюция терминосистем, свойства термина. Особенности перевода терминов. Приемы перевода терминов нефтегазовой сферы как одного из сложных видов технического перевода с точки зрения узкоспециальной терминологии.
курсовая работа [81,6 K], добавлен 14.03.2015Basic stages of creation and development of web site, his structure and setting, features and component parts. The shortest ways are creations of web site on this stage, necessary for this knowledge and skills. Resources for creation of web site.
реферат [30,1 K], добавлен 08.03.2010Сущность терминологии как особой лексической подсистемы языка. Лексико-грамматические особенности и адекватность перевода сельскохозяйственной терминологии и аббревиатур на примере документов международного союза по охране новых сортов растений.
курсовая работа [59,4 K], добавлен 15.04.2011Concept, history of development and sources of forming of slang as a language of modern youth. Linguistic description of modern slang and ductings of his distribution. Features of functioning of university jargon and slang of the American students.
курсовая работа [47,8 K], добавлен 23.07.2015Рассмотрение профессионального языка как дисциплинарного феномена, обслуживающего сферу человеческой деятельности. Основные различия профессионализмов от другой лексикологии. Анализ особенностей формирования и использования химической терминологии.
презентация [749,2 K], добавлен 05.11.2015The early twentieth century literature, modernism. Virginia Woolf, James Joyce, David Herbert Lawrence. New period, prose and drama. Angry young men writers. The generation of general discontent. American literature of the middle of the XX-th century.
учебное пособие [174,2 K], добавлен 09.04.2013Traditional periodization of historical stages of progress of English language. Old and middle English, the modern period. The Vocabulary of the old English language. Old English Manuscripts, Poetry and Alphabets. Borrowings in the Old English language.
презентация [281,2 K], добавлен 27.03.2014Перевод пассивных конструкций с английского языка на русский. Пассив и пассивные конструкции в английском языке. Заголовки и заголовочные комплексы. Перевод страдательного залога с английского языка на русский. Сфера употребления пассивных конструкций.
курсовая работа [42,9 K], добавлен 31.10.2011Сущность и существующие классификации спортивной терминологии, ее структура и компоненты. Специфика и механизм спортивного перевода, соответствующей лексики с английского языка на русский. Анализ возможных способов и выбор наиболее адекватного перевода.
дипломная работа [110,5 K], добавлен 08.09.2016The linguistic status of the article. Noun: the category of determination. Indefinite meaning expressed by a/an. The definite article the. Cataphoric the as heavily concentrated in non-fiction writing. Percentage use of reference for definite phrases.
курсовая работа [357,9 K], добавлен 27.04.2015