-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava fundamental
More file actions
97 lines (93 loc) · 28.9 KB
/
java fundamental
File metadata and controls
97 lines (93 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
Chapters 1
“JAVA FUNDAMENTAL”
ln computing few technologies have had the impact of java. Its creation in the early days of the Web helped shape the modern from of the Internet, Including both the client and server sides Its innovative features advanced the art and science of programming. setting a new standard in computer language design, the forward-thinking culture that grew up around java ensured It would remain vibrant and alive, adapting to the often rapid and varied changes in the computing landscape, Simply put: not only is java one of the worlds most important computer langauges it is a force that revolutionized programming and, in the process, changed the world.
Although java is a langauge often associated with internet programming, it is by no means limited in that regard Java is a powerful, Full-featured, general-purpose programming language, Thus, if you are new to programming, Java is an excellent langauge to learn. Moreover, to be a professional programmer today impilies the ability to program inJava—it is that important. In the course of this book. you will learn the busic skills that will help you master it.
the purpose of this chapter is to introduce you to java. beginning wtih is history, its design philosophy and several of its most important features.By far, hardest thing about learning a prigramming langauge is the fact that no element exsists in isolation. Instead. The components of the language work in conjunction with each other. This interrelatedness is espeially pronounced in java. In fact, it is difficult to dicuss one aspect of java without involving others. To help overcome this problem, This chapter provides a brief overview of several Java features, Including the general form of a java program, some basic control structures, and simple operators, It does not go into too many details, but, rather, concentrates on general concepts common to any Java program.
" THE HISTORY AND PHILOSOPHY OF JAVA"
before one can fully appreciate the unique aspects of Java. It is necessary to understand the forces that drove its creation. the programming philosophy that it embodies. and key concepts of its design. As you advance through this book, you will see that many aspects of java are either a direct or indirect result of the historical forces that shaped the language. Thus. It is Fitting that we begin our examminations of java by exploring how java relates to the larger programming universe.
“THE ORIGINS OF JAVA”
Java was conceived by James Gosling Patrick Naughton, Chris Warth, Ed frank, and Mike Sheridan at sun Microsystems in 1991. this language was initially called “Oak” but was renamed “ Java” in 1995, Somewhat surprisingly, the original impetus for java was not the Internet! instead, the primary motivation was the need for a platform-independent langauge that could be used to create software to be embedded in various consumer electronic devices, such as toasters. Microwave ovens and remote controls, As you can probably guess, many different Types of CPU are used as controllers. the trouble was that ( at the time) most computer languages were designed to be compiled into machine code that was targeted for a specific type of CPU. For Example, consider the C++ language
although it was possible to compile a C++ program for just about any type of CPU, to do so required a full C++ compiler targeted for that CPU. the problem, However. Is that compilers are expensive and time consuming to create. in an attempt to find a better solution. Gosling and the others worked on a portable, cross-platform language that could produce code that would run on a variety of CPUs Under 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 emerged 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 programmers consumer electronics, however, with the emergence of the web, Java was propelled to the forefront of computer languages design, because the Web, too, demanded portable programs.
most programmers learns early in their careers that portable programs are as elusive as they are desirable. while the quest for a way to create efficient. 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 However, with the advent of the Internet and the web, the old problem of portability returned with a vengeance, after all, the Internet consisted of a diverse, distributed universe populated with many types of computers, operating systems, and CPUs,
What was once an irritating but now- priority problems had become a high-profile necessity. by 1993 it become obvious to remember 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. this realization caused the focus of java to switch from consumer electronics to internet programming. So, although it was the desire for an architecture-neutral programming language that provided the initial spark, it was the Internet that ultimately led to Java’s large-scale success.
“JAVA’s Lineage: C AND C++”
The history of computer languages is not one of isolated events. Rather, it is a continuum in which each new language’s is influenced in one way or another by what has come before.In this regard. Java is no exception. before moving on. It is useful to understand where Java fits into the family tree of computer languages.
the two languages that form Java’s closest ancestors are C and C++. as you may know, C and CA++ are among the most important computer languages ever invented and are still in widespread use today. from C. Java inherits its syntax. javas object model is adapted from C++. Java’s relationship to C and C++ is important for a number of reasons First, at time of Java’s creation, many programmers were familiar with t he C/C++ syntax. because Java uses a similar syntax, it was relatively easy for a C/C++ programmer to learn Java . This made it possible for java to be readily utilized by the pool of existing programmers, thus facilitating Java’s acceptance by the programming communities.
Second, Java’s designers did not “ reinvent the wheel” Instead they further refined an already highly successful programming paradigm. the modern age of programming began with C. it moved C++ and then to java . by inheriting and building on that rich heritage, Java provides a powerful , logically consistent programming environment that takes the best of the past and adds new features related to the online environment and advances in the art of programming. Perhaps most important, because of their similarities, C, C++, and java define a common, conceptual framework for the professional programmer. programner do not face major rifts when switching from one language to another.
Java has another attribute in common with C and C ++ it 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 . there is no better way to produce a top-flight professional programming language.
One last point: although C++ and java are related. Especially in their support for object-oriented programming,Java is not simply the “Internet version of C++. “ Java has significant practical and philosophical differences from C++. Furthermore. java is not an enchanted version of C++. For example. it is neither upwardly nor downwardly compatible with C++. moreover. 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 problem. they will coexist for many years to come.
"HOW JAVA IMPACTED THE INTERNET"
the Internet helped catapult Java to the forefront of programming and java in return, had a produced effect on the Internet first, the creation of java simplified Internet programming in general acting as a catalyst that drew legions of programmers to the Web. Second. Java inmovated a new type of networked program called the applet that changed the way the online world thought about content. Finally, and perhaps most importantly, Java addressed some of the thorniest issues associated with the Internet: portability and security.
"JAVA SIMPLIFIED WEB BASE PROGGRAMMING"
from the start, java simplified web-based programming in a number of ways. Arguably the most important is found in its ability to create potable, cross-platform programs. Of nearly equal importance is Java's support fot Networking.Its library of ready-to-use functionality enabled programmers to easily write program that accessed or made use of the internet. It also provided mechanism the enabled programs to be readily delivered over the Internet. Although the details are beyond the scope of this book. it is sufficient to know that Java's support for networking was key factor in its rapid rise.
JAVA APPLETS;
At the time of java's creation, one of its most exciting Features was the applets. An applet is a special kinf a java program that is designed to be transmitted over s internet and automatically executed inside a Java- compatible web browser. If the user clicks a link that contains an applet, the applet will download and run in the browser automatically. applets were intended to be small programs, typically used to display data provided by the server, handle user input. or provide simple functions. such as s loan calculator. The key feature of applets is that they execute locally, rather than on the server. In essence, the applet allowed some Functionality to be moved from the server to be client.
The creation of the applet was important because. at the time. it expanded the universe of objects that could move about freely in cyberspace. In general, there are two very broad categories of objects that the transmited between the server and the client passive information and dynamic active programs for exmaple, when you read your e-mail, you are viewing passive data. Even when you download a program, the program's code is still only passive data until you execute it. By contrast, the applet is a dynamic, self- executing programs. Such a program is an active agent on the client computer. yet it is delivered by the server.
In the early days of java, Applets were a curcial part of java programming. They illustrated the power and benefits of Java, added an exciting dimension to web pages, and enabled programmers to explore the full extent of what was possible with java. Although it id likely that there are still applets in use today, over time they become less important, and for reasons that will be explained shortly, JDK 9 began their phase- out process. Finally, applet support was removed by JDK 11.
Ask The Expert?
ANswer:
Q: what is C# and how does it relate to java?
A few years after the creation of java, Microsoft developed the C# language. This is important because C# is closely related to Java. In fact, many of C #'s features directly parralel java. Both java and C#, but the overall " look and feel" of these languages is very similar. This means that if you already know C#, then learning Java will be especially easy, Conversely, if C# is in your future, then your knowledge of java will come in handly.
SECURITY;
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 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 system. As you will see. Java addressed these problems in an effective and elegant way, Let's look a bit more closely at each, beginning with security.
as you are likely aware, every time that you download a 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 damage because it has gained unauthorized 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 programs to be safely downloaded and executed on the client computer, It was necessary to prevent them from launching such an attack.
java archieved this protection by enabling you to confine an application to the java execution environment and prevent it from accessing other parts of the computer. ( You will see how this is accomplished shortly.) The ability to download an application with a high level of confidence that no harm will be done contributed significantly to Java's early success.
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 types of system. In other words. a mechanism that allows the same application to be downloded and executed by a wide variety of CPU's operating Systems, and browsers is required. It is not practical to have different versions of the same application for different computers. The same application code must work in all computers. Therefore, some means of generating portable code was needed. As you will soon see, the same mechanism that helps ensure security also helps create portability.
JAVA'S MAGIC: The Bytecode:
They key that allowed java to address both the security and portability problem just described is that the output of a java compiler is not executable code. Rather, It is bycode. Bytecode is a highly optimized set a instructions designed to be executed by what is called the Java virtual Machine ( JVM ) , which is part of the java Runtime Environment (JRE). In essence, the original JVM was designed as an interpreter for Bytecode. This many come as a bit of a surprise because many modern languages are designed to be compiled into CPU-specific, executable code due to performance concerns, However, the fact that a java program is executef by the JVM helps solve the major problems associated with web-based programs.,Here is why.
Translating a java program into bytecode makes it much easier to run a program in a wide variety of environments because only the JRE ( which includes the JVM) needs to be implemented for each platform.One aJREC exists for a given system. any java program can run on it . Remember, although the details of the JRE will differ from platform to platform, all JRE's Understand the same Java Bytecode. If a java progran 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 bytecode by the JVM is the easiest way to create truly potable programs.
The fact that a java program Is executed by the JVM also helps to make it secure. Becacuse the JVM is in control, it manager program execution. Thus, it was possible. for the JVM to create a restricted execution environment. called the sandbox. That contains the program. preventing unrestricted access to the machine. Safety is also enchanced by certain restrictions that exist in the java language.
When a program is interpreted, it generally runs slower than the same program would run if compiled to executable code. However, with java. the differential between the two is not so great. Because bytecode has been highly optimized, the use of bytecode enables the JVM to execute programs much faster than you might expect.
Although Java was designed as an interpreted language, there is nothing about java that prevent on - the- fly compilation of bytecode into native code in order to boost performane. for this reason, the HOTspot JVM was introduced not long after java's initial release. Hotspot includes a just-in- time (JIT) compiler for bytecode. when a JIT compiler is part of the JVM, selected portions of bytecode are compiler into executable code in real time on a piece-by- piece demand basis.that is s JIT compiler compiles code as it is needed during execution. Furthermore, not all sequences of bytecode 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 complilationc is applied to bytecode, the portability and safety features still apply because the JVM is still in charge of the execution environment.
On other point: there has been experimentation with an ahead-of -time compiler for java. Such a compiler can be used to compile bytecode into native code prior to execution by the JVM, rather than on-the-fly. Some previous versions of the JDK supplied an experimental ahead-of-time compiler, however, JDK 17 has removed it. Ahead-of-time compilation is a specialized feature and it does not replace Java's traditional approach just described. Because of the highly sophisticated nature of ahead-of-time compilation. it is not something that you will use when learning Java, and it is not discussed further in this book.
Ask the Expert
Answer:
Q: I have heard about a special type of java program called a servlet. what is it?
A java servlet is a small program that executes on a server. Servlet dynamically extend the functionality of a web server. It is hepful to understand that as useful as client-side applications can be, they are just one half of the client/ server equation. Not long after the initial release of java. it become obvious that java would also be useful on the server side One result was the servlet. Thus, with the advent of the servlet. Java spanned both sides of the client/server connection. Although the topic of servlet, and server-side programming in general, is beyond the scope of this beginner's guide, they are something that you will likely find of interest asls you advance in java programming.
MOVING BEYOND APPLETS
at the time of this writing, it has been more than two decades since java's original release Over those years, many changes have taken place. At the time of java's creation, the Internet was a new and exciting innovation; web browsers were undergoing rapid development and refinement; the modern from of the smartphone had not yet been invented: and the near ubiquitous use of computers was still a few years off. As you would expects. Java has also changed and so, too, has the way that java is used. Perhaps nothing illustrates the ongoing evolution of java better than applet.
As explained previously, in the early years of java, applets were a crucial part of java programming. They noy only added excitement to a web page, they were a highly visibel part of java. which added to its charisma. However, applets rely on a Java browser plug-in Thus, for an applet to work. It must be supported by the browser. Over the past few years support for the java browser plug-in has been waning. Simply put, without browser support, applets are not visible. Because of this, beginning with JDK 9, the phase-out of applets was begun, with support for applets being deprecated. In the language of Java. deprecated means that a feature is still available but flagged as obsolete. Thus, a deprecated feature should not be used for now code. the phase- out became complete with the release of JDK 11 because run-time support for applets was removed. Beginning with JDK 17, the entire Applet API was deprecated for removal, which means that it will be removed from the JDK at some point in the future.
As a point of interest, a few years after java's creation an alternative to applets was added. Called java web start, it enabled an application to be dynamically downloaded from a web page. It was a deployment mechanism that was esprcially useful for larger Java applications that were not appropriate for applets. The difference between an applet and a web Start application is that a web Start application runs on its own. not inside the browser. Thus, it look much like a "normal" application. It does, however. require that a stand-alone JRE that supports web start is available on the host system. Beginning with JDK 11, support for java Web Start has been removed.
Given that neither applets nor java Web Start are visible options for modern version of Java, you might wonder what mechanism should be used to deploy s Java application. at the time of this writing, one part of the answer is to use the Jlink tool added by JDK 9. it can create a complete run-time- image that includes all necesarry support for your program. including the JRE. Another part of the answer is the Jpackage tool. Added by the JDK 16. it can be used to create a ready- to- install application. As you might guess, deployment is a rather advanced topic that is outside the scope of this book. Fortunately, you won't need to worry about deployment to use this book because all of the sample program run directly on your computer. They are not deployed over the Internet.
THE JAVA BUZZWORDS;
No history of java 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 played an important role in molding the final form of the language. The key considerations were summed up by the java design team in the following list of BUZZWORDS.
Simple
Java has a concise, cohesive set of features that make it easy to learn and use.
Secure
java provides a secure means of creating Internet applications
Portable
Java programs can execute in any environment for which there is a java run time system.
Object-oriented
Java embodies the modern object-oriented programming philosophy.
Robust
java encourages error-free programming by being strickly typed and performing run-time checks.
Multithreaded
Java provides integrated support for mutlithreaded programming.
Architecture-neutral
Java is not tied to a specific machine or operating system architecture.
Interpreted
Java supports crosd-platform code through the use of java bytecode.
High performance
The java bytecode is highly optimized for speed of execution.
Distributed
Java was designed with the distributed environment of the Internet in mind.
Dynamic
java programs carry with them substantial amounts of nun-time type information that is used to verify and solve access to objects at run time.
OBJECT-ORIENTED PROGRAMMING;
at the center of java is objec-oriented programming (OOP). the object-oriented methodology is inseparable from java, and all java programs are, to at least same extent, object-oriented. Because of OOP's importance to java. It is useful to understand in a general way OOP's basic principles before you write even a simple Java program. later in this book, you will see how to put these concepts into practice.
OOP is a powerful way to approach the job of programming, Programming methodolgies have changed dramatically since the invention of the computer, primarily to accommodate the increasing complexity of programs, For example, when computers were first invented programming was done by toggling in the binary machine instructions using the computers 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, using 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 widespread language was, of course, FORTRAN. Although FORTRAN was a very impressive first step. it was hardly a langauge that encouraged clear. easy-to- understand programs.
The 1960s gave birth to structured programming. This is the method encouraged by languages such as C and Pascual. The use of structured languages are characterized by their support for stand-alone subroutines, local variables, rich control constructs, and their lack of reliance upon the GOTO. Although structured languages are a powerful tool. even they reach their limit when a project becomes too large.
Consider this: At each milestone in the development of programming, techniques and tools were created to allow the programmer to deal with increasingly greater complexity. each step of the way, the new approach took the best elements of the previous methods and moved forward. Prior to the invention of OOP, many projects were nearing ( or exceeding) the point where the structured approach no longer works. Objects-oriented methods were created to help programmers break through these barriers.
Object-oriented programming took the best ideas of structured programming and combined them with several new concepts. The result was a different way ot organizing a program. In the most general sense. a program can be organized in one of two ways: around it code ( what is happening) or around its data ( what is being affected). Using only structured programming techniques, programs are typically organized around code. This approach can be thought of as " code acting on data"
Object-oriented programs work the other way around., They are organized around data with the key principle being "data controlling access to code" In an object-oriented language, you defines precisely what sort of operations can be applied to that data.
to support the principles of object-oriented programming. all OOP languages, including Java, have three traits in comment: encapsulation, polymorphism, and inheritance.Let's examine each.
ENCAPSULATION;
Encapsulation is a programming mechanism that binds together code and the data it manipulates, and that keeps both safe from outside interference and misuse. In an object-oriented language, code and data can be bound together in such a way that a self- contained black box is created. Within the box are all necessary data and code. when code and data are linked together in this fashion, object is created. In other words. an object is the device that supportd encapsulation.
within an object. code, data, or both may be private to that object or public. Private code or data is known to and accessible by only another part of the object. That is, private code or data cannot be accessed by piece of the program that exists outside. the object. When code or data is public, other parts of your program can access it even though it is defined within an object. Typically, the public parts of an object are used to provide a controlled interface to the private elements ot the objects.
Java's basic unit of encapsulation is the class. Although the class will be examined in great details later in this book, the following brief discussion will be helpful now. A class defines the form of an object. It specifies both the data and the code that will operate on that data. java uses a class specification to construct objects are instances of a class. Thus, a class is essentially a set of plans that specify how to build an object.
The code and data that constitute a class are called members of the class. Specifically. the data defined by the class are referred to as member variables or instance variables.The code that operates on that data is referred to as member methods or just methods. Method is java's term for a subroutine. If you are familiar with C/C++, it may help to know that what a java programmer calls a method, a C/C++ programer calls a function.
POLYMORPHISM;
Polymorphism ( form Greek meaning "many forms") is the quality that allows one interface to access a general class of actions., The specifics action is determined by the extract nature of the situation. A simple example of polymorphism is found in the steering wheel of an automobile. the steering wheel ( i.e., the interface) is the same no matter what type of actual steering mechansim is used. That is, the steering wheel works the same whether you car has manual steering, power steering, or rack -and- opinion steering. Therefore, once you know how to operate the steering wheel, you can drive any type of car.
the same principle can also apply to programming.,for example, consider a stack( which is a first- in, Last-out list). You might have a program that requires three different types of stacks. one stack is used for integer values, one for floating-point values, and one for characters. In this case, the algorithm that implements each stack is the same, even though the data being stored. differs, in a non- object- oriented language. you would be required to create three different sets of stack routines,with each set of stack. you