JAVA
Creation Of Java:
Java was conceived by James Gosling, Patrick Naughton, Chris Wrath, Ed Frank and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. The 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, 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.
Primary Goal of the java Programming Language:
The Java programming language provides the following:
- A language that is easy to program because it:
- Eliminates the pitfalls of other languages such as pointer arithmetic and memory management that affect code robustness.
- Is object-oriented to help the programmer visualize the program in real-life terms.
- Provides a means to make code as streamlined and clear as possible.
- An interpreted environment resulting in the
following two benefits:
- Speed of development - eliminates the compile-link-load-test cycle.
- Code portability -Enables the operating system to make system level calls on behalf of the runtime environment.
- A way for programs to run more than one thread of activity.
- A means to change programs dynamically during their runtime life by allowing them to download code modules.
- A means of checking code modules that are loaded to ensure security.
The Java technology architecture uses the following features to fulfil the previously listed goals:
- The Java virtual machine.
- Garbage collection.
- Code security
Java Virtual Machine:
The Java virtual machine specification defines the Java Virtual machine (JVM) as: "An imaginary machine that is implemented by encoding it in software on a real machine. Code for the Java Virtual Machine is stored in .class files, each of which contains code for at most one public class." The Java virtual machine specification provides the hardware platform specification to which all Java technology code is compiled. This specification enables Java software to be platform independent because the compilation is done for a generic machine know as the Java virtual machine (JVM). You can emulate this "generic machine" in software to run on various existing computer systems or implemented in hardware. The compiler takes the Java application source code and generates bytecodes. Bytecodes are machine code instructions for JVM. Every Java interpreter, regardless of whether it is a Java technology development tool or a Web browser that can run applets, has an implementation of the JVM.
The JVM specification provides concrete definitions for the implementation of the following:
- Instruction set (equivalent to that of a central processing unit [CPU])
- Register set
- Class file format
- Stack
- Garbage-collected heap
- Memory area
The code format of the JVM consists of compact and efficient bytecodes. Programs represented by JVM bytecodes must maintain proper type discipline. The majority of type checking is done at compile time. Any compliant Java technology interpreter must be able to run any program with class files that conform to the class file format specified in The Java virtual machine specification.
Garbage Collection:
Many programming languages allow the dynamic allocation of memory at runtime. The process of allocating memory varies based on the syntax of the language, but always involves returning a pointer to the starting address of a memory block. Once the allocated memory is no longer required (the pointer that references the memory has gone out of scope), the program or runtime environment should deallocate the memory.
In other languages, the program developer is responsible for deallocating the memory. This can be a difficult exercise at times, because it is not always known in advance when memory should be released. Programs that do not deallocate when memory can eventually crash when there is no memory left on the system to allocate. These programs are said to have memory leaks. The Java programming language removes the responsibility for deallocating memory from the programmer. It provides a system-level thread that tracks each memory allocation. During idle cycles in the Java virtual Machine, the garbage collection thread checks for and frees any memory that can be freed.
Garbage collection happens automatically during the lifetime of a Java technology program, eliminating the need to deallocate memory and avoiding memory leaks. However, garbage collection schemes can vary dramatically across JVM implementations.
Code Security:
Java software source files are "compiled" in the sense that they are converted into a set of bytecodes from the text format in which programmers write them. The bytecodes are stored in .class files. At runtime, the bytecode that make up a Java software program are loaded, checked and run in an interpreter. In case of applets, the bytecodes can be downloaded and then interpreted by JVM built into the browser. The interpreter has two functions: it executes bytecodes and makes the appropriate calls to the underlying hardware.
Overview: In some Java technology runtime environments, a portion of the verified bytecode is compiled to native machine code and executed directly on the hardware platform. This allows Java software code to allow compilation to the native machine code.
The Java Runtime Environment:
A Java technology runtime environment runs code complied for JVM and
performs three main tasks:
- Loads code - Performed by class loader
- Verifies code - Performed by the bytecode verifier
- Executes code - Performed by the runtime interpreter
Class Loader:
The class loader loads all classes needed for the execution of a program. The class loader adds security by separating the namespaces for the classes of the local files system from those imported from network sources. This limits any Trojan horse applications because local classes are always loaded first. Once all of the classes have been loaded, the memory layout of the executable file is determined. At this point specific memory addresses are assigned to symbolic references and lookup table is created. Because memory layout occurs at runtime, the Java technology interpreter adds protection against unauthorized access into the restricted areas of code.
Bytecode Verifier:
Java software code passes several tests before actually running on your machine. The JVM puts the code fragments and checks code fragments for illegal code - code that forges pointers, violates access rights on objects, or attempts to change object type.
Verification Process:
The bytecode verifier makes four passes on the code in a program. It ensures that the code adhere to JVM specifications and does not violate system integrity. If the verifier completes all four passes without returning an error messages, then the following is ensured:
- The classes adhere to the class file format of the JVM specification.
- There are no access restriction violations.
- The code causes no operand stack overflows or underflows.
- The types of parameters for all operational codes are known to always be correct.
- No illegal data conversions, such as converting integers to object references, have occurred.
Java Applets And Application:
Java can be used to create two types of programs: applications and applets. An Application is a program that runs on your computer, under operating system of that computer. That is, an application created by Java is more or less like one created using C or C++. When used to create applications, Java is not much different from any other computer language. Rather, it is Java's ability to create applets that makes it important.
An Applet is an application (program) designed to be transmitted over the internet and executed by a Java - compatible Web browser. An applet is actually a tiny Java program, dynamically downloaded across the network, just like an image, sound file or video clip. The important difference is that an applet is an intelligent program, not just an animation or media file. In other words, an applet is a program that can react to user input and dynamically change - not just run the same animation or sound over and over.
Object Oriented Programming:
Object-oriented programming is at the core of Java. In fact, all Java programs are object-oriented - this isn't an option the way that it is in C++, for example. OOP is so integral to Java that you must understand its basic principle before you can write even simple Java programs. Therefore, this chapter begins with a discussion of the theoretical aspects of OOP.
1 Two Program solving techniques:
As you know, all computer programs consist of two elements: code and data. Furthermore, a program can be conceptually organised around its code or around its data. That is, some programs are written around "what is happening" and others are written around "who is being affected". These are two techniques that govern how a program is constructed. The first way is called the process - oriented model this approach characterizes a program as a series of linear steps (i.e. code). The process - oriented model can be thought of as code acting on data. Procedural language such as C employ this model to considerable success. However, problem with this approach appear as programs grow larger and more complex.
To manage increasing complexity, the second approach called object - oriented programming, was conceived. Object - oriented programming organizes a program around its data (i.e. objects) and a set of well defined interfaces to the data.
An object - oriented program can be characterised as data controlling access to code. As you will see, by switching the controlling entity to data, you can achieve several organisational benefits.
Abstraction:
An essential element of Object - oriented programming is abstraction. Humans manage complexity through abstraction. For example, people do not think of car as set of tens of thousands of individual parts. They think of it as well - defined object with its own unique behaviour. They can ignore the details of how engine, transmission and braking systems work. Instead they are free to utilize the object as a whole. A powerful way to manage abstraction is through the use of hierarchical classification. This allows you to layer the semantics of complex systems, breaking them into more manageable pieces. Hierarchical abstraction of complex systems can also be applied to computer programs. The data from a traditional process - oriented program can be transformed by abstraction into its components objects. A sequence of process steps can become a collection of messages between these objects. Thus, each of these objects describes its own unique behavior. You can treat these objects as concrete entities that respond to messages telling them to do something. This is the essence of object - oriented programming. Object - oriented concepts form the heart of Java just as they form the basis for human understanding. It is important that you understand how these concepts translate into programs. As Object - oriented programming is a powerful and natural paradigm for creating programs that survive the inevitable changes accompanying the life cycle of any major software project, including conception, growth and aging. For example, once you have well - defined objects and clean, reliable interfaces to those objects, you can gracefully decommission or replace parts of an older system without fear.
Three Principles of OOP:
Encapsulation:
Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. One way to think about encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper. Access to code and data inside the wrapper is tightly controlled through a well - defined interface.
In Java the basis of encapsulation is the class. A class defines the structure and behavior (data and code) that will be shared by set objects. Each object of a given class contains the structure and behavior defined by the class, as if they were stamped out by a mold in the shape of the class. For this reason, objects are sometimes referred to as class. Thus, a class is logical construct; an object has physical reality.
When you create a class, you will specify the code and data that constitute that class. Collectively, these elements 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.
In properly written Java programs, the methods define how the member variables can be used. This means that the behavior and interface of a class are defined by the methods that operate on its instance data.Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the complexity of the implementation inside the class. Each method or variable in a class may be marked private or public. The public interface of a class represents everything that external users of the class need to know, or may know. The private methods and data can only be accessed by code that is member of the class. Therefore any other code that is not a member of the class cannot access a private method or variable. Since the private members of the class may only be accessed by other parts of your program through the class public methods, you can ensure that no improper actions take place. This means that the public interface should be carefully designed not to expose too much of the inner workings of class.
Inheritance:
Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. Most knowledge is made manageable by hierarchical (that is top - down) classifications. For example, a Golden Retriever is part of the classification dog, which in turn is part of the mammal class, which is under the larger class animal. Without the use of hierarchies, each object need to only define all of its characteristics explicitly. However, by use of inheritance an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. Thus it is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case.
Inheritance interacts with encapsulation as well. If a given class encapsulates some attributes, then any subclass will have the same attributes plus any that it adds as part of its specialization. This is a key concept which lets object - oriented programs grow in complexity linearly rather than geometrically. A new subclass inherits all of the attributes of all its ancestors. It does not have unpredictable interactions with majority of the rest of the code in the system.
Polymorphism:
Polymorphism (many forms) is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. More generally the concept of polymorphism is often expressed by the phrase "one interface multiple methods". This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is, method) as it applies to each situation. You the programmer do not need to make this selection manually. You need only remember and utilize the general interface.
When properly applied, polymorphism, encapsulation, and inheritance combine to produce a programming environment that supports the development of far more robust and scaleable programs than does the process - oriented model. A well-designed hierarchy of classes is the basis for reusing the code in which you have invested time and effort developing and testing. Encapsulation allows you to migrate your implementations over time without breaking the code that depends on the public interface of your classes. Polymorphism allows you to create clean, sensible, readable and resilient code.
Simple Program:
/* This is a Simple Java program.
Call this file "Example.java"
*/
class Example {
// Your program begins with a call to main( ).
public static void main(String args[ ]){
System.out.println("Hello world");
System.out.print("This is my First ");
System.out.print("Java Program");
}
}
The first thing that you must learn about Java is that the name you give to a source file is very important. For this example, the name of the source file should be Example.java.
In Java, a source file is officially called a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that a source file use the .java filename extension. Notice that the file extension is four characters long. As you can see by looking at the program, the name of the class defined by the program is also Example. This not a coincidence. In Java, all code must reside inside a class. By convention, the name of that class should match the name of the file that holds the program. You should also make sure that the capitalization of the filename matches the class name. The reason for this is that Java is case-sensitive. At this point the convention that filenames correspond to class names may seem arbitrary. However, this convention makes it easier to maintain and organize your programs.
How To Compile a Program:
To compile Example.java program, execute the compiler, javac, specifying the name of the source file on the command line, as shown here:
Syntax c:\>javac < source filename >.java
For example :
c:\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of the program. As discussed earlier, the Java bytecode is the intermediate representation of your program that contains instructions the Java interpreter will execute. Thus the output of javac is not code that can be directly executed.
To actually run the program, you must use
the Java interpreter, called java. To do so, pass the class name Example
as a command-line argument as shown here:
C:\>java Example
When the program is run, the following output is displayed:
Hello world This is my First Java program
When Java source code is compiled, each individual class is put into its own output file named after the class and using the .class extension. This is why it is a good idea to your Java source files the same name as the class they contain - the name of the source file will match the name of the .java file. When you execute the Java interpreter as just shown, you are actually specifying the name of the class that you want the interpreter to execute. It will automatically search for a file by that name that has the .class extension.
If it finds the file, it
will execute the code contained in the specified class.
Program Description:
The program begins with the following lines
/* This is a Simple Java program.
Call this file "Example.java"
*/
This is a comment. Like most other programming language, lets you enter a remark into a program's source file. The compiler ignores the contents of a comment. Instead, a comment describes or explains the operation of the program to anyone who is reading its source code.
Java supports three styles of comments. The one at the top is called multiline comment. This type of comment must begin with /* and ends with */. Any thing in between is ignored by compiler.
The next line
class Example {
This line uses the keywords class to declare that a new class is defined. Example is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly braces, in Java they are identical to the way they are used in C and C++.
The next line is single - line comment
// Your program begins with a call to main( ).
This is the second type of comment supported by Java. A single - line
comment begins with
a // and ends at the end of the line.
The next line of code
public static void main(String args[ ]){
This line begins the main( ) method. As the comment preceding it suggests, this is the line at which the program will begin executing. All Java applications begin execution by calling main( ).
The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When public precedes a class member, then that member may be accessed by code outside the class in which it is declared. In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values. And also keep in mind Java is case - sensitive, thus Main is different from main. In main( ), there is only one parameter, String args[ ] declares a parameter named args, which is an array of instances of the class String.
(Arrays are collection of similar objects ). The last character on the line is the {. This signals the start of main( )'s body. All of the code that comprises a method will occur between the method's opening curly brace and its closing curly brace.
The next three lines of
code are those that occur inside the main( ).
System.out.println("Hello world");
System.out.print("This is my First ");
System.out.print("Java Program");
This first line will output the string of characters "Hello world", followed by a new line on the screen. Then the second line will output the string "This is my First". In the same line "Java Program" will appear on the screen. The line begins with System.out, System is predefined class that provides access to the system and out is the output stream that s connected to the console. println( ) statement is the built in function that will print in a new line and print( ) statement is also a built in function that will print in the same line.
The first } in the program ends main( ), and the last } ends the Example class. Notice that the print statement ends with a semicolon (;). All statements in Java end with a semicolon.
Lexical Issues:
Java programs are collection of whitespaces, identifiers, comments, operators, keywords, separators, literals, etc;
Whitespaces:
Java is a free - form language. This means that you do not need follow any special indentation rules (but it is recommended). For eg the Example.java program could have been written all on one line or any other way as long as one whitespace character between each token that was not already delineated by an operator or separator. In Java, whitespace is space, tab, or newline.
Identifiers:
Identifiers are used for class names, methods names, variables names. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers or the underscore and dollar-sign characters. They must not begin with a number. Again, Java is case - sensitive, so VALUE is a different identifier than Value.
For example :
Avg, count, a4, $trail, me_ok. (VALID)
2count, high-temp, not/ok (INVALID)
Literals:
A constant value in Java is created by using literals representation of
it.
For example :
100 (Integer) 98.6 (Floating point) 'X'
(Character)
"This is a trail" (String)
A literal can be used anywhere a value of its type is allowed.
Comments:
As mentioned there are three types of comment. Single line, multiple line and documentation comment. The third type is used to produce an HTML file that documents your program.
Separators:
In Java there are a few character that are used as separators. The most commonly used separator in Java is the semicolon. It is used to terminate statements.
The following the other separators used.
|
Symbol |
Name |
Purpose |
|
( ) |
Parentheses |
Used to contain lists of parameters in method definition and invocation. Also used for defining precedence in expressions, containing expressions in control statements and surrounding cast types. |
|
{ } |
Braces |
Used to contain the values of automatically initialised arrays. Also used to define a block of code, for classes, methods and local scopes. |
|
[ ] |
Brackets |
Used to declare array types. Also used when dereferencing array values. |
|
; |
Semicolon |
Terminates statements |
|
, |
Comma |
Separates consecutive identifiers in a variable declaration. Also used to chain statements together inside a 'for' statement. |
|
. |
Period |
Used to separate package names from sub packages and classes. Also used to separate a variable or method from a reference variable. |
Keywords:
The keywords combined with the syntax of the operators and separators, form the definition of the Java language. These keywords cannot be used for a variable, class or methods. In addition to the key words Java reserves the following: true, false, null. These are values defined by Java.
|
Abstract |
const |
finally |
int |
public |
this |
|
Boolean |
continue |
float |
interface |
return |
throw |
|
Break |
default |
for |
long |
short |
Throws |
|
Byte |
do |
goto |
native |
static |
Transient |
|
Case |
double |
if |
new |
strictfp |
Try |
|
Catch |
else |
implements |
package |
super |
void |
|
Char |
extends |
import |
private |
switch |
volatile |
|
Class |
final |
instanceof |
protected |
synchronized |
while |
Java class libraries:
The Java environment relies on several built-in class libraries that contain many built - in methods that provide support for such things as I/O, string handling, networking and graphics. The standard classes also provide support for windowed output. Thus, java as a totality is a combination of the Java language itself, plus its standard classes.