Search This Blog

Monday, 9 January 2012

Combine An Arithmetic Operation With An Assignment Operator


Java provides special operators that can be used to combine an arithmetic operation
with an assignment. As you probably know, statements like the following are quite
common in programming:
a = a + 4;
In Java, you can rewrite this statement as shown here:


a += 4;
This version uses the += assignment operator. Both statements perform the same
action: they increase the value of a by 4.
Here is another example,
a = a % 2;
which can be expressed as
a %= 2;
In this case, the %= obtains the remainder of a/2 and puts that result back into a.
There are assignment operators for all of the arithmetic, binary operators. Thus,
any statement of the form
var = var op expression;
can be rewritten as
var op= expression;
The assignment operators provide two benefits. First, they save you a bit of typing,
because they are “shorthand” for their equivalent long forms. Second, they are
implemented more efficiently by the Java run-time system than are their equivalent
long forms. For these reasons, you will often see the assignment operators used in
professionally written Java programs.
Here is a sample program that shows several op= operator assignments in action:
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;

c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
The output of this program is shown here:
a = 6
b = 8
c = 3


Modulus Operator In Java


The modulus operator, %, returns the remainder of a division operation. It can be
applied to floating-point types as well as integer types. (This differs from C/C++, in
which the % can only be applied to integer types.)

The following example program demonstrates the %:

// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program you will get the following output:
x mod 10 = 2
y mod 10 = 2.25

Arithmetic Operators in Java


Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra.
 The following table lists the arithmetic operators:

Operator                                     Result


+                                               Addition
–                                    Subtraction (also unary minus)
*                                            Multiplication
/                                                 Division
%                                              Modulus
++                                            Increment
+=                                    Addition assignment
–=                                  Subtraction assignment
*=                                 Multiplication assignment
/=                                       Division assignment
%=                                  Modulus assignment
– –                                          Decrement


Arithmetic Operators With Example



The basic arithmetic operations—addition, subtraction, multiplication, and division—
all behave as you would expect for all numeric types. The minus operator also has
a unary form which negates its single operand. Remember that when the division

operator is applied to an integer type, there will be no fractional component attached to
the result.
The following simple example program demonstrates the arithmetic operators. It
also illustrates the difference between floating-point division and integer division.




// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}


When you run this program, you will see the following output:
Integer Arithmetic
a = 2
b = 6
c = 1

d = -1
e = 1


Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5




Sunday, 8 January 2012

Operator in Java


Java provides a rich operator environment. Most of its operators can be divided
into the following four groups:


  •  arithmetic
  •  bitwise
  • relational
  •  logical.
 Java also defines some additional operators that handle certain special situations.


If you are familiar with C/C++/C#, then you will be pleased to know that most operators
in Java work just like they do in those languages. However, there are some subtle differences,
so a careful reading is advised




Java cannot allow pointers


If you are an experienced C/C++ programmer, then you know that these languages
provide support for pointers. The reason for this is simple: Java does not support or allow pointers. (Or
more properly, Java does not support pointers that can be accessed and/or modified
by the programmer.) Java cannot allow pointers, because doing so would allow Java
applets to breach the firewall between the Java execution environment and the host
computer. (Remember, a pointer can be given any address in memory—even addresses
that might be outside the Java run-time system.) Since C/C++ make extensive use of
pointers, you might be thinking that their loss is a significant disadvantage to Java.
However, this is not true. Java is designed in such a way that as long as you stay within
the confines of the execution environment, you will never need to use a pointer, nor would
there be any benefit in using one. For tips on converting C/C++ code to Java


Saturday, 7 January 2012

Strings Introduction


As you may have noticed, in the preceding discussion of data types and arrays there
has been no mention of strings or a string data type. This is not because Java does not
support such a type—it does. It is just that Java’s string type, called String, is not a
simple type. Nor is it simply an array of characters (as are strings in C/C++). Rather,
String defines an object, and a full description of it requires an understanding of several
object-related features. After objects are described. However, so that you can use simple strings in example programs, the following brief introduction is in order.
The String type is used to declare string variables. You can also declare arrays of
strings. A quoted string constant can be assigned to a String variable. A variable

of type String can be assigned to another variable of type String. You can use an object of
type String as an argument to println( ). For example, consider the following fragment:

String str = "this is a test";
System.out.println(str);

Here, str is an object of type String. It is assigned the string “this is a test”. This string
is displayed by the println( ) statement.


Arrays in Java and Different Types of Array


Arrays in Java and Different Types of Array

An array is a group of like-typed variables that are referred to by a common name. Arrays
of 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.


If you are familiar with C/C++, be careful. Arrays in Java work differently than they do
in those languages....



  • One-Dimensional Arrays
  • Multidimensional Arrays

One-Dimensional Arrays

A one-dimensional array is, 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 onedimensional
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
named month_days with the type “array of int”:

                                                   int month_days[];

Although this declaration establishes the fact that month_days is an array variable,
no array actually exists. In fact, the value of month_days is set to null, which represents
an array with no value. To link month_days with an actual, physical array of integers,
you must allocate one using new and assign it to month_days. new is a special operator
that allocates memory.
new is used to allocate memory for arrays. The general form of new as it applies to one-dimensional
arrays appears as follows:

                                              array-var = new type[size];

Here, type specifies the type of data being allocated, size specifies the number of elements
in the array, and array-var is the array variable that is linked to the array. That is, to use
new to allocate an array, you must specify the type and number of elements to allocate.
The elements in the array allocated by new will automatically be initialized to zero.
This example allocates a 12-element array of integers and links them to month_days.

                                               month_days = new int[12];

After this statement executes, month_days will refer to an array of 12 integers. Further,
all elements in the array will be initialized to zero.
Let’s review: Obtaining an array is a two-step process. First, you must declare a
variable of the desired array type. Second, you must allocate the memory that will hold
the array, using new, and assign it to the array variable. Thus, in Java all arrays are
dynamically allocated. If the concept of dynamic allocation is unfamiliar to you, don’t
worry. It will be described at length later in this book.
Once you have allocated an array, you can access a specific element in the array by
specifying its index within square brackets. All array indexes start at zero.

 For example,
this statement assigns the value 28 to the second element of month_days.

month_days[1] = 28;

The next line displays the value stored at index 3.
System.out.println(month_days[3]);
Putting together all the pieces, here is a program that creates an array of the
number of days in each month.

// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}

When you run this program, it prints the number of days in April. As mentioned, Java
array indexes start with zero, so the number of days in April is month_days[3] or 30.
It is possible to combine the declaration of the array variable with the allocation of
the array itself, as shown here:

int month_days[] = new int[12];

This is the way that you will normally see it done in professionally written Java
programs.
Arrays can be initialized when they are declared. The process is much the same as
that used to initialize the simple types. An array initializer is a list of comma-separated
expressions surrounded by curly braces. The commas separate the values of the array
elements. The array will automatically be created large enough to hold the number of
elements you specify in the array initializer. There is no need to use new. For example,
to store the number of days in each month, the following code creates an initialized
array of integers:


// An improved version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

When you run this program, you see the same output as that generated by the
previous version.
Java strictly checks to make sure you do not accidentally try to store or reference
values outside of the range of the array. The Java run-time system will check to be sure
that all array indexes are in the correct range. (In this regard, Java is fundamentally
different from C/C++, which provide no run-time boundary checks.) For example, the
run-time system will check the value of each index into month_days to make sure that
it is between 0 and 11 inclusive. If you try to access elements outside the range of the
array (negative numbers or numbers greater than the length of the array), you will
cause a run-time error.
Here is one more example that uses a one-dimensional array. It finds the average of
a set of numbers.
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}

Multidimensional Arrays

In Java, multidimensional arrays are actually arrays of arrays. These, as you might
expect, 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. For example, the
following declares a two-dimensional array variable called twoD.

                                                  int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented
as an array of arrays of int.

The following program numbers each element in the array from left to right, top to
bottom, and then displays these values:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

This program generates the following output:

0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension. You can allocate the remaining dimensions
separately. For example, this following code allocates memory for the first dimension of
twoD when it is declared. It allocates the second dimension manually.

int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];

While there is no advantage to individually allocating the second dimension arrays
in this situation, there may be in others. For example, when you allocate dimensions
manually, you do not need to allocate the same number of elements for each dimension.
As stated earlier, since multidimensional arrays are actually arrays of arrays, the length
of each array is under your control. For example, the following program creates a twodimensional
array in which the sizes of the second dimension are unequal.


// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

This program generates the following output:

0
1 2
3 4 5
6 7 8 9
The array created by this program looks like this:



The use of uneven (or, irregular) multidimensional arrays is not recommended
for most applications, because it runs contrary to what people expect to find when
a multidimensional array is encountered. However, it can be used effectively in some
situations. For example, if you need a very large two-dimensional array that is sparsely
populated (that is, one in which not all of the elements will be used), then an irregular
array might be a perfect solution.
It is possible to initialize multidimensional arrays. To do so, simply enclose each
dimension’s initializer within its own set of curly braces. The following program creates
a matrix where each element contains the product of the row and column indexes. Also
notice that you can use expressions as well as literal values inside of array initializers.


// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}

When you run this program, you will get the following output:

0.0         0.0           0.0            0.0
0.0        1.0            2.0            3.0
0.0        2.0           4.0             6.0
0.0        3.0           6.0             9.0

As you can see, each row in the array is initialized as specified in the initialization lists.
Let’s look at one more example that uses a multidimensional array. The following
program creates a 3 by 4 by 5, three-dimensional array. It then loads each element with
the product of its indexes. Finally, it displays these products.


// Demonstrate a three-dimensional array.
class threeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}

This program generates the following output:

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12


0 0 0 0 0
0 2 4 6 8
0 4 8 12 16
0 6 12 18 24

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.


Thursday, 5 January 2012

Java Type Conversion and Casting


If you have previous programming experience, then you already know that it is fairly
common to assign a value of one type to a variable of another type. If the two types are
compatible, then Java will perform the conversion automatically. For example, it is always
possible to assign an int value to a long variable. However, not all types are compatible,
and thus, not all type conversions are implicitly allowed. For instance, there is no
conversion defined from double to byte. Fortunately, it is still possible to obtain a
conversion between incompatible types. To do so, you must use a cast, which performs
an explicit conversion between incompatible types. Let's look at both automatic type
conversions and casting.

Java's Automatic Conversions


When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:

             • The two types are compatible.
             • The destination type is larger than the source type.

When these two conditions are met, a widening conversion takes place. For example, the
int type is always large enough to hold all valid byte values, so no explicit cast statement
is required.
For widening conversions, the numeric types, including integer and floating-point types,
are compatible with each other. However, the numeric types are not compatible with char
or boolean. Also, char and boolean are not compatible with each other.

As mentioned earlier, Java also performs an automatic type conversion when storing a
literal integer constant into variables of type byte, short, or long.



Casting Incompatible Types


Although the automatic type conversions are helpful, they will not fulfill all needs. For
example, what if you want to assign an int value to a byte variable? This conversion will
not be performed automatically, because a byte is smaller than an int. This kind of
conversion is sometimes called a narrowing conversion, since you are explicitly making
the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast is
simply an explicit type conversion. It has this general form:

(target-type) value

Here, target-type specifies the desired type to convert the specified value to. For
example, the following fragment casts an int to a byte. If the integer's value is larger than
the range of a byte, it will be reduced modulo (the remainder of an integer division by
the) byte's range.

int a;
byte b;
// ...
b = (byte) a;

A different type of conversion will occur when a floating-point value is assigned to an
integer type: truncation. As you know, integers do not have fractional components. Thus,
when a floating-point value is assigned to an integer type, the fractional component is
lost. For example, if the value 1.23 is assigned to an integer, the resulting value will
simply be 1. The 0.23 will have been truncated. Of course, if the size of the whole
number component is too large to fit into the target integer type, then that value will be
reduced modulo the target type's range.

The following program demonstrates some type conversions that require casts:

// Demonstrate casts.
        class Conversion {
                 public static void main(String args[]) {
                                  byte b;
                                  int i = 257;
                                 double d = 323.142;
                                 System.out.println("\\nConversion of int to byte.");
                                 b = (byte) i;
                                 System.out.println("i and b " + i + " " + b);
                                 System.out.println("\\nConversion of double to int.");
                                 i = (int) d;
                                System.out.println("d and i " + d + " " + i);
                                System.out.println("\\nConversion of double to byte.");
                                b = (byte) d;
                               System.out.println("d and b " + d + " " + b);
                                                                        }
                                   }


This program generates the following output:


                           Conversion of int to byte.
                            i and b 257 1
                          Conversion of double to int.
                           d and i 323.142 323
                         Conversion of double to byte.
                          d and b 323.142 67

Let's look at each conversion. When the value 257 is cast into a byte variable, the result is
the remainder of the division of 257 by 256 (the range of a byte), which is 1 in this case.
When the d is converted to an int, its fractional component is lost. When d is converted to
a byte, its fractional component is lost, and the value is reduced modulo 256, which in this
case is 67.

Wednesday, 4 January 2012

Variables In Java And Declaration


The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables
have a scope, which defines their visibility, and a lifetime.

Declaring a Variable


In Java, all variables must be declared before they can be used. The basic form of a

variable declaration is shown here:


type identifier [ = value][, identifier [= value] ...] ;


The type is one of Java's atomic types, or the name of a class or interface. The identifier is the name of the
variable. You can initialize the variable by specifying an equal sign and a value. Keep in
mind that the initialization expression must result in a value of the same (or compatible)
type as that specified for the variable. To declare more than one variable of the specified
type, use a comma-separated list.


Here are several examples of variable declarations of various types. Note that some
include an initialization.


int a, b, c;                                          // declares three ints, a, b, and c.
int d = 3, e, f = 5;                             // declares three more ints, initializing
                                                          // d and f.
byte z = 22;                                      // initializes z.
double pi = 3.14159;                        // declares an approximation of pi.
char x = 'x';                                     // the variable x has the value 'x'.


The identifiers that you choose have nothing intrinsic in their names that indicates their
type. Many readers will remember when FORTRAN predefined all identifiers from I
through N to be of type INTEGER while all other identifiers were REAL. Java allows any
properly formed identifier to have any declared type.




Dynamic Initialization



Although the preceding examples have used only constants as initializers, Java allows
variables to be initialized dynamically, using any expression valid at the time the variable
is declared.
For example, here is a short program that computes the length of the hypotenuse of a
right triangle given the lengths of its two opposing sides:


// Demonstrate dynamic initialization.
class DynInit {
         public static void main(String args[]) {
                          double a = 3.0, b = 4.0;
         // c is dynamically initialized
                        double c = Math.sqrt(a * a + b * b);
                        System.out.println("Hypotenuse is " + c);
                                                                  }
                        }




Here, three local variables—a, b,and c—are declared. The first two, a and b, are
initialized by constants. However, c is initialized dynamically to the length of the
hypotenuse (using the Pythagorean theorem). The program uses another of Java's builtin
methods, sqrt( ), which is a member of the Math class, to compute the square root of
its argument. The key point here is that the initialization expression may use any element
valid at the time of the initialization, including calls to methods, other variables, or literals.


Variables  Scope and Lifetime 


So far, all of the variables used have been declared at the start of the main( ) method.

However, Java allows variables to be declared within any block. A block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope. Thus, each time you start a new block, you are creating a new scope. As you probably know from your previous programming experience, a scope
determines what objects are visible to other parts of your program. It also determines the
lifetime of those objects. Most other computer languages define two general categories of scopes: global and
local. However, these traditional scopes do not fit well with Java's strict, object-oriented model. While it is possible to create what amounts to being a global scope, it is by far the exception, not the rule. In Java, the two major scopes are those defined by a class and those defined by a method. Even this distinction is somewhat artificial. However, since the class scope has several unique properties and attributes that do not apply to the scope defined by a method, this distinction makes some sense. Because of the
differences,  when classes are described. For now, we will only examine the scopes
defined by or within a method. The scope defined by a method begins with its opening curly brace. However, if that method has parameters, they too are included within the method's scope. They work the same as any other method variable. As a general rule, variables declared inside a scope are not visible (that is, accessible) to code that is defined outside that scope. Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access and/or modification. Indeed, the scope rules provide the foundation for encapsulation. Scopes can be nested. For example, each time you create a block of code, you are creating a new, nested scope. When this occurs, the outer scope encloses the inner
scope. This means that objects declared in the outer scope will be visible to code within
the inner scope. However, the reverse is not true. Objects declared within the inner scope
will not be visible outside it.


To understand the effect of nested scopes, consider the following program:


// Demonstrate block scope.
class Scope {
              public static void main(String args[]) { 
                           int x;                             // known to all code within main
                           x = 10;
                                  if(x == 10) {          // start new scope
                                              int y = 20; // known only to this block
                                                              // x and y both known here.
                                              System.out.println("x and y: " + x + " " + y);
                                              x = y * 2;
                                       }
                                                              // y = 100; // Error! y not known here
                                                              // x is still known here.
                          System.out.println("x is " + x);
                                }
                        }
As the comments indicate, the variable x is declared at the start of main( )'s scope and is
accessible to all subsequent code within main( ). Within the if block, y is declared. Since
a block defines a scope, y is only visible to other code within its block. This is why outside
of its block, the line y = 100; is commented out. If you remove the leading comment
symbol, a compile-time error will occur, because y is not visible outside of its block.
Within the if block, x can be used because code within a block (that is, a nested scope)
has access to variables declared by an enclosing scope.
Within a block, variables can be declared at any point, but are valid only after they are
declared. Thus, if you define a variable at the start of a method, it is available to all of the
code within that method. Conversely, if you declare a variable at the end of a block, it is
effectively useless, because no code will have access to it. For example, this fragment is
invalid because count cannot be used prior to its declaration:


// This fragment is wrong!
count = 100; // oops! cannot use count before it is declared!
int count;


Here is another important point to remember: variables are created when their scope is
entered, and destroyed when their scope is left. This means that a variable will not hold
its value once it has gone out of scope. Therefore, variables declared within a method will
not hold their values between calls to that method. Also, a variable declared within a
block will lose its value when the block is left. Thus, the lifetime of a variable is confined
to its scope.
If a variable declaration includes an initializer, then that variable will be reinitialized each
time the block in which it is declared is entered. For example, consider this program:


                                                                                 // Demonstrate lifetime of a variable.
                     class LifeTime {
                                    public static void main(String args[]) {
                                                      int x;
                                                      for(x = 0; x < 3; x++) {
                                                      int y = -1;          // y is initialized each time block is entered
                                                      System.out.println("y is: " + y); // this always prints -1
                                                       y = 100;
                                                      System.out.println("y is now: " + y);
                                                                   }
                                                      }
                                               }
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100




As you can see, y is always reinitialized to –1 each time the inner for loop is entered.
Even though it is subsequently assigned the value 100, this value is lost.
One last point: Although blocks can be nested, you cannot declare a variable to have the
same name as one in an outer scope. In this regard, Java differs from C and C++. Here
is an example that tries to declare two separate variables with the same name. In Java,
this is illegal. In C/C++, it would be legal and the two bars would be separate.


                                    // This program will not compile
                                                 class ScopeErr {
                                                         public static void main(String args[]) {
                                                                        int bar = 1;
                                                                                  { // creates a new scope
                                                                              int bar = 2; // Compile-time error – bar already defined!
                                                                                   }
                                                                              }
                                                                          }



Monday, 2 January 2012

Closer In Java, Its Look Like Literals


By literal we mean any number, text, or other information that represents a value. This means what you type is what you get. We will use literals in addition to variables in Java statement.
  • Integer Literals
  • Floating-Point Literals
  • Boolean Literals
  • Character Literals

Integer Literals

Integers are probably the most commonly used type in the typical program. Any whole
number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal
values, meaning they are describing a base 10 number. There are two other bases which
can be used in integer literals, octal (base eight) and hexadecimal (base 16). Octal
values are denoted in Java by a leading zero. Normal decimal numbers cannot have a
leading zero. Thus, the seemingly valid value 09 will produce an error from the compiler,
since 9 is outside of octal's 0 to 7 range. A more common base for numbers used by
programmers is hexadecimal, which matches cleanly with modulo 8 word sizes, such as
8, 16, 32, and 64 bits. You signify a hexadecimal constant with a leading zero-x, (0x or
0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are
substituted for 10 through 15.
Integer literals create an int value, which in Java is a 32-bit integer value. Since Java is
strongly typed, you might be wondering how it is possible to assign an integer literal to
one of Java's other integer types, such as byte or long, without causing a type mismatch
error. Fortunately, such situations are easily handled. When a literal value is assigned to
a byte or short variable, no error is generated if the literal value is within the range of the
target type. Also, an integer literal can always be assigned to a long variable. However,
to specify a long literal, you will need to explicitly tell the compiler that the literal value is
of type long. You do this by appending an upper- or lowercase L to the literal. For
example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long.

659L Decimal integer literal of type long integer
 0x4a Hexadecimal integer literal of type integer
 057L Octal integer literal of type long integer


Character Literals

Characters in Java are indices into the Unicode character set. They are 16-bit values that
can be converted into integers and manipulated with the integer operators, such as the
addition and subtraction operators. A literal character is represented inside a pair of
single quotes. All of the visible ASCII characters can be directly entered inside the
quotes, such as 'a', 'z', and '@'. For characters that are impossible to enter directly, there
are several escape sequences, which allow you to enter the character you need, such as
'\\'' for the single-quote character itself, and '\\n' for the newline character. There is also a
mechanism for directly entering the value of a character in octal or hexadecimal. For octal
notation use the backslash followed by the three-digit number. For example, '\\141' is the
letter 'a'. For hexadecimal, you enter a backslash-u (\\u), then exactly four hexadecimal
digits. For example, '\\u0061' is the ISO-Latin-1 'a' because the top byte is zero. '\\ua432'
is a Japanese Katakana character. 


Character Escape Sequences


Escape Sequence                                              Description


\ddd                                                               O ctal character (ddd)
\uxxxx                                                 Hexadecimal UNICODE character (xxxx)
\'                                                                           Single quote
\"                                                                          Double quote
\\                                                                             Backslash
\r                                                                        Carriage return
\n                                                         New line (also known as line feed)
\f                                                                            Form feed
\t                                                                                 Tab
\b                                                                           Backspace





Lets see the table below in which the character literals use Unicode escape sequence to represent printable and nonprintable characters both.

 'u0041' Capital letter A
 '\u0030' Digit 0
 '\u0022' Double quote "
 '\u003b' Punctuation ;
 '\u0020' Space
 '\u0009' Horizontal Tab 
Floating-Point Literals


Floating-point numbers represent decimal values with a fractional component. They can
be expressed in either standard or scientific notation. Standard notation consists of a
whole number component followed by a decimal point followed by a fractional
component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation
floating-point numbers. Scientific notation uses a standard-notation, floating-point number
plus a suffix that specifies a power of 10 by which the number is to be multiplied. The
exponent is indicated by an E or e followed by a decimal number, which can be positive
or negative. Examples include 6.022E23, 314159E–05, and 2e+100.
Floating-point literals in Java default to double precision. To specify a float literal, you
must append an F or f to the constant. You can also explicitly specify a double literal by
appending a D or d. Doing so is, of course, redundant. The default double type
consumes 64 bits of storage, while the less-accurate float type requires only 32 bits.

 The default type when you write a floating-point literal is double.
Type
Size
Range
Precision
name
bytes
bits
approximate
in decimal digits
float
4
32
+/- 3.4 * 1038
6-7
double
8
64
+/- 1.8 * 10308
15
The following floating-point literals represent double-precision floating-point and floating-point values.
 6.5E+32 (or 6.5E32) Double-precision floating-point literal
 7D Double-precision floating-point literal
 .01f Floating-point literal
Boolean Literals

Boolean literals are simple. There are only two logical values that a boolean value can
have, true and false. The values of true and false do not convert into any numerical
representation. The true literal in Java does not equal 1, nor does the false literal equal
0. In Java, they can only be assigned to variables declared as boolean, or used in
expressions with Boolean operators.

We have to use the values true and false to represent a Boolean value. Like boolean chosen = true;

String Literals

The string of characters is represented as String literals in Java. In Java a string is not a basic data type, rather it is an object. These strings are not stored in arrays as in C language. There are few methods provided in Java to combine strings, modify strings and to know whether to strings have the same value.
We represent string literals asString myString = "How are you?";
The above example shows how to represent a string. It consists of 
a series of characters inside double quotation marks.
Lets see some more examples of string literals:
""    // the empty string
"\""   // a string containing "
"This is a string"   // a string containing 16 characters
"This is a " +   // actually a string-valued constant expression,
"two-line string"   // formed from two string literals
Strings can include the character escape codes as well, as shown here:String example = "Your Name, \"Sumit\"";
System.out.println("Thankingyou,\nRichards\n");

Null Literals

The final literal that we can use in Java programming is a Null literal. We specify the Null literal in the source code as 'null'. To reduce the number of references to an object, use null literal. The type of the null literal is always null. We typically assign null literals to object reference variables. For instance

s = null;
An this example an object is referenced by s. We reduce the number of references to an object by assigning null to s. Now, as in this example the object is no longer referenced so it will be available for the garbage collection i.e. the compiler will destroy it and the free memory will be allocated to the other object. Well, we will later learn about garbage collection.
 
The final literal that we can use in Java programming is a Null literal. We specify the Null literal in the source code as 'null'. To reduce the number of references to an object, use null literal. The type of the null literal is always null. We typically assign null literals to object reference variables. For instance

s = null;
An this example an object is referenced by s. We reduce the number of references to an object by assigning null to s. Now, as in this example the object is no longer referenced so it will be available for the garbage collection i.e. the compiler will destroy it and the free memory will be allocated to the other object. Well, we will later learn about garbage collection.

Sunday, 1 January 2012

Data Types Comes Under Java

Overview


three of Java's most fundamental elements: data types, variables, and arrays. As with all modern programming languages, Java supports several types of data. You may use these types to declare variables and to create arrays. As you will see, Java's approach to these items is clean, efficient, and cohesive.


Note
If you come from a C or C++ background, keep in mind that Java is more strictly
typed than either language. For example, in C/C++ you can assign a floating-point
value to an integer. In Java, you cannot. Also, in C there is not necessarily strong
type-checking between a parameter and an argument. In Java, there is. You might
find Java's strong type-checking a bit tedious at first. But remember, in the long run
it will help reduce the possibility of errors in your code.

Java 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 includes float and double, which represent
numbers 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.

The simple types represent single values—not complex objects. Although Java is
otherwise completely object-oriented, the simple types are not. They are analogous to the
simple types found in most other non–object-oriented languages. The reason for this is
efficiency. Making the simple types into objects would have degraded performance too
much.
The simple types are defined to have an explicit range and mathematical behavior.
Languages such as C and C++ allow the size of an integer to vary based upon the
dictates of the execution environment. However, Java is different. Because of Java's
portability requirement, all data types have a strictly defined range. For example, an int is
always 32 bits, regardless of the particular platform. This allows programs to be written
that are guaranteed to run without porting on any machine architecture. While strictly
specifying the size of an integer may cause a small loss of performance in some
environments, it is necessary in order to achieve portability.
Let's look at each type of data in turn.


Integers


Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only integers.
Many other computer languages, including C/C++, support both signed and unsigned
integers. However, Java's designers felt that unsigned integers were unnecessary.
Specifically, they felt that the concept of unsigned was used mostly to specify the
behavior of the high-order bit, which defined the sign of an int when expressed as a
number. Java manages the meaning of the high-order bit
differently, by adding a special "unsigned right shift" operator. Thus, the need for an
unsigned integer type was eliminated.
The width of an integer type should not be thought of as the amount of storage it
consumes, but rather as the behavior it defines for variables and expressions of that type.
The Java run-time environment is free to use whatever size it wants, as long as the types
behave as you declared them. In fact, at least one implementation stores bytes and
shorts as 32-bit (rather than 8- and 16-bit) values to improve performance, because that
is the word size of most computers currently in use.
The width and ranges of these integer types vary widely, as shown in this table:

Name          Width                           Range   
      
long                6              –9,223,372,036,854,775,808 to
                                          9 ,223,372,036,854,775,807
int                  32               –2,147,483,648 to 2,147,483,647

short              16                     - 32,768 to 32,767

byte                8                           – 128 to 127

 look at each type of integer.

byte


The smallest integer type is byte. This is a signed 8-bit type that has a range from –128
to 127. Variables of type byte are especially useful when you're working with a stream of
data from a network or file. They are also useful when you're working with raw binary
data that may not be directly compatible with Java's other built-in types.
Byte variables are declared by use of the byte keyword. For example, the following
declares two byte variables called b and c:

byte b, c;

short


short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the
least-used Java type, since it is defined as having its high byte first (called big-endian
format). This type is mostly applicable to 16-bit computers, which are becoming
increasingly scarce.
Here are some examples of short variable declarations:
short s;
short t;

Note
"Endianness" describes how multibyte data types, such as short, int, and
long, are stored in memory. If it takes 2 bytes to represent a short, then
which one comes first, the most significant or the least significant? To say that
a machine is big-endian, means that the most significant byte is first, followed
by the least significant one. Machines such as the SPARC and PowerPC are
big-endian, while the Intel x86 series is little-endian.

int


The most commonly used integer type is int. It is a signed 32-bit type that has a range
from –2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are
commonly employed to control loops and to index arrays. Any time you have an integer
expression involving bytes, shorts, ints, and literal numbers, the entire expression is
promoted to int before the calculation is done.
The int type is the most versatile and efficient type, and it should be used most of the
time when you want to create a number for counting or indexing arrays or doing integer
math. It may seem that using short or byte will save space, but there is no guarantee
that Java won't promote those types to int internally anyway. Remember, type
determines behavior, not size. (The only exception is arrays, where byte is guaranteed to
use only one byte per array element, short will use two bytes, and int will use four.)

long


long is a signed 64-bit type and is useful for those occasions where an int type is not
large enough to hold the desired value. The range of a long is quite large. This makes it
useful when big, whole numbers are needed. For example, here is a program that
computes the number of miles that light will travel in a specified number of days.
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}


This program output:


In 1000 days light will travel about 16070400000000 miles.

Clearly, the result could not have been held in an int variable.

Floating-Point Types


Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square
root, or transcendentals such as sine and cosine, result in a value whose precision
requires a floating-point type. Java implements the standard (IEEE–754) set of floatingpoint
types and operators. There are two kinds of floating-point types, float and double,
which represent single- and double-precision numbers, respectively. Their width and
ranges are shown here:
Name                          Width in Bits                            Range
double                                64                          1.7e–308 to 1.7e+308
float                                    32                          3.4e–038 to 3.4e+038

Each of these floating-point types is examined next.

float.


The type float specifies a single-precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double
precision, but will become imprecise when the values are either very large or very small.
Variables of type float are useful when you need a fractional component, but don't
require a large degree of precision. For example, float can be useful when representing
dollars and cents.
Here are some example float variable declarations:

float hightemp, lowtemp;


double


Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Double precision is actually faster than single precision on some modern processors that
have been optimized for high-speed mathematical calculations. All transcendental math
functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to
maintain accuracy over many iterative calculations, or are manipulating large-valued
numbers, double is the best choice.
Here is a short program that uses double variables to compute the area of a circle:
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
- 40 -
System.out.println("Area of circle is " + a);
}
}

Characters


In Java, the data type used to store characters is char. However, C/C++ programmers
beware: char in Java is not the same as char in C or C++. In C/C++, char is an integer
type that is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to
represent characters. Unicode defines a fully international character set that can
represent all of the characters found in all human languages. It is a unification of dozens
of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and
many more. For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The
range of a char is 0 to 65,536. There are no negative chars. The standard set of
characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit
character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow applets
to be written for worldwide use, it makes sense that it would use Unicode to represent
characters. Of course, the use of Unicode is somewhat inefficient for languages such as
English, German, Spanish, or French, whose characters can easily be contained within 8
bits. But such is the price that must be paid for global portability.
Note More information about Unicode can be found at http://www.unicode.org.
Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
This program output:

ch1 and ch2: X Y

Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127
values in the Unicode character set. For this reason, all the "old tricks" that you have
used with characters in the past will work in Java, too.
Even though chars are not integers, in many cases you can operate on them as if they
were integers. This allows you to add two characters together, or to increment the value
of a character variable. For example, consider the following program:
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
The output  program is shown here:

ch1 contains X
ch1 is now Y

In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1
containing Y, the next character in the ASCII (and Unicode) sequence.

Booleans:


Java has a simple type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, such
as a < b. boolean is also the type required by the conditional expressions that govern the
control statements such as if and for.
Here is a program that demonstrates the boolean type:
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
The output shown here:

b is false
b is true
This is executed.
10 > 9 is true


There are three interesting things to notice about this program. First, as you can see,
when a boolean value is output by println( ), "true" or "false" is displayed. Second, the
value of a boolean variable is sufficient, by itself, to control the if statement. There is no
need to write an if statement like this:

if(b == true) ...


Third, the outcome of a relational operator, such as <, is a boolean value. This is why the
expression 10 > 9 displays the value "true." Further, the extra set of parentheses around 10
> 9 is necessary because the + operator has a higher precedence than the >.