Welcome PradhiKarthik: Java

Sunday, September 19, 2010

Java

Java


The Java Programming Language
The Java programming language is a high-level language that can be characterized by all of the following buzzwords:
  Simple
  Architecture neutral
  Object oriented
  Portable
  Distributed
  High performance
  Multithreaded
  Robust
  Dynamic
  Secure
Each of the preceding buzzwords is explained in The Java Language Environment , a white paper written by James Gosling and Henry McGilton.
In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.




An overview of the software development process.
Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.
Through the Java VM, the same application is capable of running on multiple platforms.
The Java Platform
A platform is the hardware or software environment in which a program runs. We've already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.
The Java platform has two components:
·         The Java Virtual Machine

·         The Java Application Programming Interface (API)
You've already been introduced to the Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware-based platforms.
The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The next section, What Can Java Technology Do? highlights some of the functionality provided by the API.
The API and Java Virtual Machine insulate the program from the underlying hardware.

As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.


Overview of Java
A computer language is a series of words used to give instructions to the computer, telling it what to do, how to do it, and when to do it. Just like there are various human languages used to communicate, there are also various computer languages. One of these computer languages is called Java. The purpose of this site is to study this language.
In our lessons, we will learn Java as a computer language not as a development environment. This means that we will primarily build applications that show how this language functions, not how to create graphical applications. The types of programs we will create on this site are called console applications. By default, a console application displays its result(s) in a black window. To make it a little easier, we will use an environment that displays a window but with a different background color.
Language Fundamentals
Introduction to Classes
Imagine you want to create a list of books of your personal library. To characterize each book, you can create a list of words that describe it. This list would be made of general characteristics of each book. Here is an example:
Book
Book Title
Author
Publisher
Year Published
In the computer world, the work Book in the above example is referred to as a class: A class is a list of criteria used to describe something. Each word or group of words, in bold in the above example, is called a property of the class. In our example, Book Title is a property of the Book class. In the same way, Author is another property of the of the Book class. In Java, there is never space between two words that represent the same entity. This means that the above list is better represented as follows:
Book
BookTitle
Author
Publisher
YearPublished
One class can also be a property of another class (unfortunately, we need to mention these issues in our introduction but don't make too much effort to understand them: everything will be clearer in future lessons). For example, imagine you create another class that can be used to describe each author of a book. The list of properties can be created as follows:
Author
Name
Nationality
You can then use this class to define a criterion in the Book class, exactly as done above: only the Author word is necessary in the Book class, its Name and Nationality criteria are directly represented.
Every property that is created in the class is referred to as its member. For example, in the above lists, Nationality is a member of the Author class while Publisher is a member of the Book class.
Introduction to Objects
To describe a particular book of your collection, you can provide information for each characteristic of the class used to describe it. Here is an example:
Author: Mojang
Name: FerdinandOyono
Nationality: Cameroon
In the same way, you can describe each author of the collection by filling out its characteristics using the above criteria. When describing an object as done in this example, you must first give a name to the object (this is not always necessary as we will see in future lessons). In the above example, Modjang is the name of the object. Author is (still) the name of the class. This name is necessary because you would need it in a class where Author must be used as a member. Based on this, you can use the name of the above class when describing a Book object. Here is an example:
Book: First Item
Book Title: Houseboy
Author: Modjang
Publisher: Heinemann
Year Published: 1991
It is important to understand the difference between a class and an object. An object is the result of describing something using the preset criteria of a (known) class. In the strict sense, you must first create a class by specifying each criterion you want to use to eventually describe some objects. On the other hand, you can create an object only that is based on an existing class.
Everything statement in Java must end with a semi-colon. This results in the following:
Book: First Item;
Book Title: Houseboy;
Author: Modjang;
Publisher: Heinemann;
Year Published: 1991;
Methods
In many cases, only characteristics are necessary to have a class on which complete objects can be described. Still, an object may be expected to perform one or more assignments or actions. An assignment that an object can perform is called a method.
Imagine you have books that that can open or close themselves when asked to do so (Sci-Fi anyone?). The action used to open may be called Open. To differentiate an assignment, or method, from a property, the name of a method must be followed with parentheses. Here are two examples:
Book
BookTitle
Author
Publisher
YearPublished
Open()
Close()
Although this list shows the methods last, this is not a rule, the methods can be the first, the last, or included between, as long as they belong to the class. In the same way, a class that is made a property (member) of a class can also have its own methods.
Every item that is created in a class is referred to as its member.
Introduction to Built-In Classes
A computer language is developed from scratch. Then other languages can be developed using its existing rules. This is also a rule that people who developed Java followed. One of the assignments they performed was to create many classes that you can directly use in your program to lay a solid foundation and work on top of that. The classes that already exist with Java are referred to as built-in classes. To make it easy to "catalog" the various built-in classes, they were created in libraries called packages and there are various of them.
One of the classes that ship with Java is called System. One of the jobs of the System class is to display something on the screen. To perform this job, the System class is equipped with a property called out. Actually, out itself is a class as we mentioned earlier that one class can be used as a property of another class. To actually display something on the screen, the out class is equipped with a method called println (read Print
Line). To display something, you can write it between the parentheses of this method. If the item to display is a word, you must include it between double-quotes.
 
Variables and Data Types
The Name of a Variable


assert

const


finally


instanceof
native


strictfp
super

synchronized

transient
volatile


Escape Sequences
Escape Sequence
Name
Description
\a
Bell (alert)
Makes a sound from the computer
\b
Backspace
Takes the cursor back
\t
Horizontal Tab
Takes the cursor to the next tab stop
\n
New line
Takes the cursor to the beginning of the next line
\v
Vertical Tab
Performs a vertical tab
\f
Form feed
\r
Carriage return
Causes a carriage return
\"
Double Quote
Displays a quotation mark (")
\'
Apostrophe
Displays an apostrophe (')
\?
Question mark
Displays a question mark
\\
Backslash
Displays a backslash (\)
\0
Null
Displays a null character

Bytes
A byte is series of 8 bits. It is used to represent small numbers. To declare a variable that would hold a natural number between -128 and 127, you can use the byte data type.
Regular Integers
The word integer is also used for a natural number. An integer is simply a natural number. Many, if not most, languages provide different data types for various categories of integers. In Java, an integer is variable whose values are between -2,147,483,648 and 2,147,484,647. The value is also said to fit in a 32-bit range. To declare a variable that would hold numbers of that range, use the int keyword.
Short Integers
An integer is referred to as short if its value is between -32768 and 32767. This number can fit in 16 bits. To declare a variable that would hold numbers in that range, you can use the short data type.
Long Integers
A number that is higher than a regular integer can hold is called a long integer. To support this type of number, the Java language provides the long data type. A long integer is a variable that can hold a very large number that may require 64 bits to be stored accurately. To declare a variable for such a number, use the long keyword.
To retrieve a long value, apply nextLong to the Scanner variable.
Double-Precision Values
One of the main concerns with decimal values used in mathematics is their level of accuracy: the number needs to be as precise as possible. To declare a variable used to hold such a decimal number, you can use the double keyword.
To retrieve a double-precision value, you apply nextDouble to your Scanner variable.
Single-Precision Values
A real number qualifies as single-precision when it needs only a limited number of bits, typically half of what is needed for a double, to show its value. The value typically fits in 32 bits and the precision is not a significant factor. To declare a variable that would hold decimal values with little to no concern with precision, you can use the float data type.
To retrieve a float value, apply nextFloat to your Scanner variable.
Because accuracy and precision are an important factor in mathematics, by default, when you declare a variable as float, you must explicitly let the compiler know that you are not concerned with precision and that the value would be dealt with single-precision. To specify this, when initializing the variable, type F to the left of the value.
A Byte for a Character
When introducing natural numbers, we saw that you could use the byte data type to declare a variable that would hold small numbers. Actually the value used for a byte variable represents code for a character. The character is internally recognized by its ASCII number. For this reason, you can use the byte data type to declare a variable that would be used to hold a single character. To initialize such a variable, assign a single-quoted character to it.


Java Basic Operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
·         Arithmetic Operators
·         Relational Operators
·         Bitwise Operators
·         Logical Operators
·         Assignment Operators
·         Misc Operators

The Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
+
Addition - Adds values on either side of the operator
A + B will give 30
-
Subtraction - Subtracts right hand operand from left hand operand
A - B will give -10
*
Multiplication - Multiplies values on either side of the operator
A * B will give 200
/
Division - Divides left hand operand by right hand operand
B / A will give 2
%
Modulus - Divides left hand operand by right hand operand and returns remainder
B % A will give 0
++
Increment - Increase the value of operand by 1
B++ gives 21
--
Decrement - Decrease the value of operand by 1
B-- gives 19

The Relational Operators:

There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
> 
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
< 
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.

The Bitwise Operators:

Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Operator
Description
Example
&
Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) will give 12 which is 0000 1100
|
Binary OR Operator copies a bit if it exists in eather operand.
(A | B) will give 61 which is 0011 1101
^
Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) will give 49 which is 0011 0001
~
Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.
(~A ) will give -60 which is 1100 0011
<< 
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
A << 2 will give 240 which is 1111 0000
>> 
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
A >> 2 will give 15 which is 1111
>>> 
Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.
A >>>2 will give 15 which is 0000 1111

The Logical Operators:

The following table lists the logical operators:
Assume boolean variables A holds true and variable B holds false then:
Operator
Description
Example
&&
Called Logical AND operator. If both the operands are non zero then then condition becomes true.
(A && B) is false.
||
Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is true.

The Assignment Operators:

There are following assignment operators supported by Java language:
Operator
Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assigne value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A
<<=
Left shift AND assignment operator
C <<= 2 is same as C = C << 2
>>=
Right shift AND assignment operator
C >>= 2 is same as C = C >> 2
&=
Bitwise AND assignment operator
C &= 2 is same as C = C & 2
^=
bitwise exclusive OR and assignment operator
C ^= 2 is same as C = C ^ 2
|=
bitwise inclusive OR and assignment operator
C |= 2 is same as C = C | 2

Misc Operators

There are few other operators supported by Java Language.         

Conditional Operator ( ? : ):

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as :
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {
   public static void main(String args[]){
      int a , b;
      a = 10;
      b = (a == 1) ? 20: 30;
      System.out.println( "Value of b is : " +  b );
 
      b = (a == 10) ? 20: 30;
      System.out.println( "Value of b is : " + b );
   }
}
This would produce following result:
Value of b is : 30
Value of b is : 20

instanceOf Operator:

This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceOf operator is wriiten as:
( Object reference variable ) instanceOf  (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side then the result will be true. Following is the example:
String name = = 'James';
boolean result = s instanceOf String;  
// This will return true since name is type of String
This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example:
class Vehicle {}
 
public class Car extends Vehicle {
   public static void main(String args[]){
      Vehicle a = new Car();
      boolean result =  a instanceof Car;
      System.out.println( result);
   }
}
This would produce following result:
true

Precedence of Java Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.
Category 
Operator 
Associativity 
Postfix 
() [] . (dot operator)
Left to right 
Unary 
++ - - ! ~
Right to left 
Multiplicative  
* / % 
Left to right 
Additive  
+ - 
Left to right 
Shift  
>> >>> <<  
Left to right 
Relational  
> >= < <=  
Left to right 
Equality  
== != 
Left to right 
Bitwise AND 
Left to right 
Bitwise XOR 
Left to right 
Bitwise OR 
Left to right 
Logical AND 
&& 
Left to right 
Logical OR 
|| 
Left to right 
Conditional 
?: 
Right to left 
Assignment 
= += -= *= /= %= >>= <<= &= ^= |= 
Right to left 
Comma 
Left to right