Sunday, 23 March 2014

core java

HISTORY
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, many more people contributed to the designand 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.Somewhat 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 in variousconsumer electronic devices, such as microwave ovens and remote controls.
 As you can probably guess, many different types of CPUs are used as controllers. The trouble with C and C++ (and most other languages) is that they are designed to be compiled for a specific target. Although it is possible to compile a 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. An easier—and more cost-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 CPUs under differing environments. This effort ultimately led to the creation of Java.
The Internet helped catapult Java to the forefront of programming, and Java, in turn,has had a profound effect on the Internet. The reason for this is quite simple: Javaexpands the universe of objects that can move about freely in cyberspace. In a network,two very broad categories of objects are transmitted between the server and your personal computer: passive information and dynamic, active programs.
THE JAVA LANGUAGE
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. However, a second type of object can be transmitted to your computer: a dynamic, self-executing program. Such a program is an active agent on the client computer, yet is initiated by the server.
 For example, a program might be provided by the server to display properly the data that the server is sending.As desirable as dynamic, networked programs are, they also present serious problems in the areas of security and portability. Prior to Java, cyberspace was effectively closed to half the entities that now live there. As you will see, Java addresses those concerns and, by doing so, has opened the door to an exciting new form of program: the applet.
The Java Buzzwords
No discussion of the genesis of Java is complete without a look at the Java buzzwords.Although the fundamental forces that necessitated the invention of Java are portabilityand 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

A First Simple Program
Now that the basic object-oriented underpinning of Java has been discussed, let’s look at some actual Java programs. Let’s start by compiling and running the short sample program shown here. As you will see, this involves a little more work than you might imagine.
/*
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("This is a simple Java program.");
}
}

Compiling the Program
To compile the Example program, execute the compiler, javac, specifying the name of the source file on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file calledExample.classthat 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 ofjavac 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 nameExample as a command-line argument, as shown here:
C:\>java Example
When the program is run, the following output is displayed:
This is a simple 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 give your Java source files the same name as the class they contain—the name of the source file will match the name of the .class 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.
Two Control Statements
The if Statement
The Java if statement works much like the IF statement in any other language. Further, it is syntactically identical to the if statements in C, C++, and C#. Its simplest form is shown here:
if( condition ) statement ;
Here,condition is a Boolean expression. If condition is true, then the statement is executed. Ifcondition is false, then the statement is bypassed. Here is an example:
if(num < 100) println("num is less than 100");
In this case, ifnumcontains a value that is less than 100, the conditional expression is true, and println( )will execute. Ifnumcontains a value greater than or equal to 100,then the println( )method is bypassed.
Here are a few:
Operator Meaning
< Less than
> Greater than
== Equal to
Notice that the test for equality is the double equal sign.
Here is a program that illustrates theif statement:
/*
Demonstrate the if.
Call this file "IfSample.java".
*/
class IfSample {
public static void main(String args[]) {
int x, y;
x = 10;
y = 20;
if(x < y) System.out.println("x is less than y");
x = x * 2;
if(x == y) System.out.println("x now equal to y");
x = x * 2;
if(x > y) System.out.println("x now greater than y");
// this won't display anything
if(x == y) System.out.println("you won't see this");
}
}
The output generated by this program is shown here:
x is less than y
x now equal to y
x now greater than y
Notice one other thing in this program. The line
int x, y;
declares two variables,x and y, by use of a comma-separated list.

The for Loop
for( initialization; condition; iteration ) statement ;
In its most common form, theinitialization portion of the loop sets a loop control
variable to an initial value. The condition is a Boolean expression that tests the loop
control variable. If the outcome of that test is true, the for loop continues to iterate. If it
is false, the loop terminates. The iteration expression determines how the loop control
variable is changed each time the loop iterates. Here is a short program that illustrates
the for loop:
/*
Demonstrate the for loop.
Call this file "ForTest.java".
*/
class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}
This program generates the following output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9

Lexical Issues
Whitespace
Java is a free-form language. This means that you do not need to follow any special indentation rules. For example, the Example program could have been written all on one line or in any other strange way you felt like typing it, as long as there was at least one whitespace character between each token that was not already delineated by an operator or separator. In Java, whitespace is a space, tab, or newline.
Identifiers
Identifiers are used for class names, method names, and variable 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, lest they be confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value. Some examples of valid identifiers are:
AvgTemp count a4 $test this_is_ok Invalid variable names include:
2count high-temp Not/ok
Literals
A constant value in Java is created by using a literal representation of it.
For example,
here are some literals:
100 98.6 ‘X’ “This is a test”
Left to right, the first literal specifies an integer, the next is a floating-point value, the
third is a character constant, and the last is a string. A literal can be used anywhere
a value of its type is allowed.
Comments
As mentioned, there are three types of comments defined by Java. You have already seen two: single-line and multiline. The third type is called a documentation comment.
This type of comment is used to produce an HTML file that documents your program.
The documentation comment begins with a /** and ends with a */ . Documentation
comments are explained in Appendix A.
Separators
In Java, there are a few characters that are used as separators. The most commonly used separator in Java is the semicolon. As you have seen, it is used to terminate statements. The separators are shown in the following table:
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 initialized 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 subpackages and classes. Also used to separate a variable or method from a reference variable.
The Java Keywords
There are 49 reserved keywords currently defined in the Java language .These keywords, combined with the syntax of the operators and separators, form the definition of the Java language. These keywords cannot be used as names for a variable,class, or method.
The keywordsconst and gotoare reserved but not used. In the early days of Java,several other keywords were reserved for possible future use. However, the current specification for Java only defines the keywords . The assert keyword was added by Java 2, version 1.4
abstract     continue      goto      package    synchronized
assert        default            if          private      this
Boolean   do             implements   protected   throw
break        double    import           public         throws
byte       else              instanceof       return    transient
case     extends            int         short  try
catch     final            interface    static    void
char     finally   long      strictfp     volatile
class     float   native   super    while
const     for    new    switch

The Java Class Libraries
The sample programs shown in this chapter make use of two of Java’s built-in methods:println( )and print( ). As mentioned, these methods are members of the Systemclass,which is a class predefined by Java that is automatically included in your programs. In the larger view, 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. As you will see, the class libraries provide much of the functionality that comes with Java. Indeed, part of becoming a Java programmer is learning to use the standard Java classes. Throughout Part I of this book, various elements of the standardlibrary classes and methods are described as needed.
Java Is a Strongly Typed Language
It is important to state at the outset that Java is a strongly typed language. Indeed, part of Java’s safety and robustness comes from this fact. Let’s see what this means. First, every variable has a type, every expression has a type, and every type is strictly defined.
 Second,all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. There are no automatic coercions or conversions of conflicting types as in some languages.
The Java compiler checks all expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be corrected before the compiler will finish compiling the class.
The Simple Types
Java defines eight simple (or elemental) types of data: byte, short, int, long, char , float,double, and boolean . These can be put in four groups:
Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers.
Floating-point numbers This group includesfloatand double, which representnumbers with fractional precision.
Characters This group includes char , which represents symbols in a character set, like letters and numbers.
Boolean This group includes boolean , which is a special type for representing true/false values.
You can use these types as-is, or to construct arrays or your own class types. Thus,they form the basis for all other types of data that you can create.
Arrays
Anarrayis a group of like-typed variables that are referred to by a common name. Arraysof any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
A one-dimensional arrayis, essentially, a list of like-typed variables. To create an array,you first must create an array variable of the desired type. The general form of a one-dimensional array declaration is
type var-name [ ];
Here,type declares the base type of the array. The base type determines the data type of each element that comprises the array. Thus, the base type for the array determines what type of data the array will hold. For example, the following declares an array namedmonth_dayswith the type “array of int”:
int month_days[];
Although this declaration establishes the fact thatmonth_daysis an array variable,no array actually exists. In fact, the value of month_daysis set to null , which represents an array with no value.
Multidimensional Arrays
In Java, multidimensional arraysare actually arrays of arrays. These, as you mightexpect, look and act like regular multidimensional arrays. However, as you will see, there are a couple of subtle differences. To declare a multidimensional array variable,specify each additional index using another set of square brackets.
example, the following declares a two-dimensional array variable called twoD .
int twoD[][] = new int[4][5];
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type [ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
 For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form is included as a convenience, and is also useful when specifying an array as a return type for a method.




No comments:

Post a Comment