Monday, 4 February 2013

PROGRAMMING STRUCTURES | J2EE Tutorial pdf

PROGRAMMING STRUCTURES

=> A Simple Java Program
=> Comments
=> Data Types
=> Variables
=> Assignments and Initializations
=> Operators
=> Arrays
Before we get into the details of the language, a brief overview would be of benefit. This section gives a very quick look at the main features of the language, without going too far into the details or showing us any actual syntax, to give us a feel for the main concepts behind Object-Oriented programming in Java.
A Java program is a collection of classes. Some of these we write; some are provided as a part of the java language.
A Simple Java Program
Let's look more closely at about the simplest Java program we can have one that simply prints a message to the console window:
public class FirstSample
{
public static void main(String[] args)
{
System.out.println("We will not use 'Hello, World!'");
}}
Now let's look at this source code line by line. The keyword public is called an access modifier; these modifiers control what other parts of a program can use this code. The keyword class is there to remind us that everything in a Java program lives inside a class. Classes are the uilding blocks with which all Java applications and applets are built. Everything in a Java program must be inside a class.
Following the keyword class is the name of the class. The rules for class names in Java are quite generous. Names must begin with a letter, and after that, they can have any combination of letters and digits. The length is essentially unlimited. We cannot use a Java reserved word (such as public or if) for a class name.
COMMENTS
Comments in Java, like comments in most programming languages, do not show up in the executable program. Java has three ways of showing comments. The most common method is a //. We use this for a comment that will run from the // to the end of the line.
System.out.println("We will not use 'Hello world!'");
// is this too cute?
When longer comments are needed, we can mark each line with a //. Or we can use the /* and */
comment delimiters that let we block off a longer comment.
DATA TYPES
Java is a strongly typed language. This means that every variable must have a declared type.
There are eight primitive types in Java. Four of them are integer types; two are floating-point number types; one is the character type char, used for characters in the Unicode encoding and one is a boolean type for truth values.
INTEGERS
The integer types are for numbers without fractional parts. Negative values are allowed. Java
provides the four integer types
JAVA INTEGER TYPES
Type                Storage                               Requirement Range (inclusive)
Int                     4 bytes          2,147,483,648 to 2,147,483, 647 (just over 2 billion)
short                 2 bytes           -32,768 to 32,767
Long                 8 bytes            9,223,372,036,854,775,808L to 9,223,372,036,854,775,807L
Byte                  1 byte             -128 to 127
FLOATING-POINT TYPES
The floating-point types denote numbers with fractional parts. There are two floating-point Types
Type                Storage                                Requirement Range (inclusive)
Float                 4 bytes               ±3.40282347E+38F (6–7 significant decimal digits)
double               8 bytes               ±1.79769313486231570E+308 (15 significant decimal digits)
THE CHARACTER TYPE
First, single quotes are used to denote char constants. For example, 'H' is a character. It is different from "H", a string containing a single character. Second, the char type denotes characters in the Unicode encoding scheme.
Special characters
Escape             Sequence            Name Unicode Value
\b                    Backspace                      \u0008
\t                     Tab                                  \u0009
\n                     Linefeed                          \u000a
\r                     Carriage return                 \u000d
\”                     Double quote                    \u0022
\’                     Single quote                       \u0027
\\                     Backslash                           \u005c
THE BOOLEAN TYPE
The boolean type has two values, false and true. It is used for evaluating logical conditions. We cannot convert between integers and boolean values.
VARIABLES
In Java, every variable has a type. We declare a variable by placing the type first, followed by the name of the variable. Here are some examples:
double salary;
int vacationDays;
long earthPopulation;
char yesChar;
boolean done;
Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement.
OPERATORS
An operator takes one or more arguments and produces a new value. The arguments are in a different form than ordinary method calls, but the effect is the same. There are different types of operators are there. They are
=> Arithmetic Operators
=> Assignment Operators
=> Unary minus and plus Operators
=> Auto increment and Decrement Operators
=> Relational Operators
=> Logical Operators
=> Bitwise Operators
=> Ternary Operators
=> Arithmetic Operators
The following are the arithmetic operators :
addition (+), subtraction (-), division (/), multiplication (*) and modulus (%, which produces the remainder from integer division). Integer division truncates, rather than rounds, the result.
=> Assignment Operators
Assignment is performed with the operator =. It means “take the value of the right-hand side (often called
the rvalue) and copy it into the left-hand side (often called the lvalue). An rvalue is any constant, variable or expression that can produce a value, but an lvalue must be a distinct, named variable.
For instance;
A = 5;
Java also uses a shorthand notation to perform an operation and an assignment at the same time.
This is denoted by an operator followed by an equal sign, and is consistent with all the operators in the language
Instead of writing x = x + 4; we can write x+=4;
=> Unary minus and plus Operators
The unary minus (-) and unary plus (+) are the same operators as binary minus and plus. The compiler figures out which use is intended by the way we write the expression. For instance, the statement
x = -a;
has an obvious meaning. The compiler is able to figure out:
x = a * -b;
but the reader might get confused, so it is clearer to say:
=> AUTO INCREMENT AND DECREMENT OPERATORS
The increment and decrement operators are the two of the nicer shortcuts. The decrement operator is -- and means “decrease by one unit.” The increment operator is ++ and means “increase by one unit.” If a is an int, for example, the expression ++a is equivalent to (a = a + 1).
Increment and decrement operators produce the value of the variable as a result.
There are two versions of each type of operator, often called the prefix and postfix versions. Pre-increment means the ++ operator appears before the variable or expression, and post-increment means the ++ operator appears after the variable or expression. Similarly, predecrement means the -- operator appears before the variable or expression, and post-decrement means the -- operator appears after the variable or expression. For pre-increment and predecrement, (i.e., ++a or --a), the operation is performed and the value is produced. For postincrement and post-decrement (i.e. a++ or a--), the value is produced, then the operation is performed.
=> Relational Operators
Relational operators generate a boolean result. They evaluate the relationship between the values of the operands. A relational expression produces true if the relationship is true, and false if the relationship is untrue.
The relational operators are less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equivalent (==) and not equivalent (!=). Equivalence and nonequivalence works with all built-in data types, but the other comparisons won’t work with type boolean. The relational operators == and != also work with all objects, but their meaning often confuses the first-time Java programmer.
=> Logical OperatorsThe logical operators AND (&&), OR (||) and NOT (!) produce a boolean value of true or false based on the logical relationship of its arguments.
=> Bitwise Operators
The bitwise operators allow us to manipulate individual bits in an integral primitive data type.
Bitwise operators perform boolean algebra on the corresponding bits in the two arguments to produce the result.
The bitwise AND operator (&) produces a one in the output bit if both input bits are one; otherwise it produces a zero. The bitwise OR operator (|) produces a one in the output bit if either input bit is a one and produces a zero only if both input bits are zero. The bitwise EXCLUSIVE OR, or XOR (^), produces a one in the output bit if one or the other input bit is a one, but not both. The bitwise NOT (~, also called the ones complement operator) is a unary operator; it takes only one argument. (All other bitwise operators are binary operators.) Bitwise NOT produces the opposite of the input bit—a one if the input bit is zero, a zero if the input bit is one.
=> Ternary operators
This operator is unusual because it has three operands. The expression is of the form: booleanexp ? value0 : value1
If boolean-exp evaluates to true, value0 is evaluated and its result becomes the value produced by the operator. If boolean-exp is false, value1 is evaluated and its result becomes the value produced by the operator.
The conditional operator can be used for its side effects or for the value it produces, but in general we want the value since that’s what makes the operator distinct from the if-else.
Here’s an example:
static int ternary(int i)
{
return i < 10 ? i * 100 : i * 10;
}
We can see that this code is more compact than what we’d need to write without the ternary operator:
static int alternative(int i)
{
if (i < 10)
return i * 100;
else
return i * 10;
}
=> Control flow
Java, like any programming language, supports both conditional statements and loops to determine control flow. We start with the conditional statements and then move on to loops. We end with the somewhat cumbersome switch statement that we can use when we have to test for many values of a single expression.
CONDITIONAL STATEMENTS
The conditional statement in Java has the form
if statement
if ( condition ) statement
In Java, as in most programming languages, we will often want to execute multiple statements when a single condition is true.
For example:
if (ourSales >= target)
{ performance = "Satisfactory"; bonus = 100; }
if/else statement
if ( condition )
statement 1
else
statement 2;
For example:
if (ourSales >= target) { performance = "Satisfactory"; bonus = 100 + 0.01 *
(ourSales - target); } else { performance = "Unsatisfactory"; bonus = 0; }
if / elseif (multiple branches) statement
Repeated if . . . else if . . . alternatives are very common
For example:
if (ourSales >= 2 * target)
{ performance = "Excellent"; bonus = 1000; }
else if (ourSales >= 1.5 * target)
{ performance = "Fine"; bonus = 500; }
else if (ourSales >= target)
{ performance = "Satisfactory"; bonus = 100; }
else
{ System.out.println("We're fired"); }
Indeterminate Loops
In Java, as in all programming languages, there are control structures that let us repeat
statements. There are two forms for repeating loops that are best when we do not know how
many times a loop should be processed (these are “indeterminate loops”). First, there is the while
loop that only executes the body of the loop while a condition is true . The general form is:
while ( condition )
statement
The while loop will never execute if the condition is false.
For example:
while (balance < goal)
{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
A while loop tests at the top. Therefore, the code in the block may never be executed. If we want to make sure a block is executed at least once, we will need to move the test to the bottom. This is done with the do / while loop. Its syntax looks like this:
do
statement
while ( condition );
do
{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest; year++;
// print current balance . . .
// ask if ready to retire and get input . . .
} while (input.equals("N"));

DETERMINATE LOOPS
The for loop is a very general construct to support iteration that is controlled by a counter or similar variable that is updated after every iteration. The following is the syntax :
for ( statement 1; expression 1; expression 2)
statement 2;
The following loop prints the numbers from 1 to 10 on the screen.
for (int i = 1; i <= 10; i++)
System.out.println(i);
Multiple Selections—the switch Statement
The if/else construct can be cumbersome when we have to deal with multiple selections with
many alternatives. Java has a switch statement that is exactly like the switch statement. The syntax,
switch (choice)
{
case 1: . . . break;
case 2: . . . break;
case 3: . . . break;
case 4: . . . break;
default: // bad input . . . break;
}

Arrays
An array is a data structure that stores a collection of values of the same type. We access each individual value through an integer index. For example, if a is an array of integers, then a[i] is the ith integer in the array. We declare an array variable by specifying the array type—which is the element type followed by []—and the array variable name.
 For example, here is the declaration of an array a of integers:
int[] a;
However, this statement only declares the variable a. It does not yet initialize a with an actual array. We use the new operator to create the array.
int[] a = new int[100];
This statement sets up an array that can hold 100 integers. The array entries are numbered from 0 to 99 (and not 1 to 100). Once the array is created, we can fill the entries in an array, for example, by using a loop:
int[] a = new int[100];
for (int i = 0; i < 100; i++)
a[i] = i; // fills the array with 0 to 99
We can define an array variable either as
int[] a;
or as
int a[];
Most Java programmers prefer the former style because it neatly separates the type int[] (integer array) from the variable name.
Array Initializers and Anonymous Arrays
Java has a shorthand to create an array object and supply initial values at the same time.
Here's an example of the syntax at work:
int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };
Array Inititalization with new operator. The syntax is
Datatype arrayname[] = new datatype[arraysize];
For Example:
int[] a = new int[10]; . . .
Program
//To get string values from the command prompt and to display the values
public class array1
{
public static void main(String arg[])
{
int size = arg.length;
System.out.println(“The Elements are”);
for(int i=0;i<size;i++)
System.out.println(arg[i]);
}}
output:

c:\>javac array1.java
c:\>java array1 C C++ PASCAL COBOL JAVA
The Elements are
CC
++
PASCAL
COBOL
JAVA
=> Multidimensional Arrays
Multidimensional arrays use more than one index to access array elements. They are used for tables and other more complex arrangements.
Declaring a matrix in Java is simple enough.
For example:
double[][] matrix;
As always, we cannot use the array until we initialize it with a call to new . In this case, we can do the initialization as follows:
matrix = new double[5][5];
In other cases, if we know the array elements, we can use a shorthand notion for initializing multidimensional arrays without needing a call to new .
For example;
int[][] magicSquare = {
{16, 3, 2, 13},
{5, 10, 11, 8},
{9, 6, 7, 12},
{4, 15, 14, 1}
};
program
// To print a multidimensional arrays
public class array2
{
public static void main(String arg[])
{
int[][] matrix = { {16, 3, 2, 13},
{5, 10, 11, 8},
{9, 6, 7, 12},
{4, 15, 14, 1} };
System.out.println("The given matrix is\n\n");
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
System.out.print(matrix[i][j]+"\t");
}
System.out.println("\n");
}}
}
output
c:\>javac array2.java
c:\>java array2
The given matrix is
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

No comments: