Wednesday, November 13, 2013

Flow Controls - Jump Statements

java supports three jump statements : break, continue, and return,These statements transfer control to another part of your program, Each is examined here.

Note: in additional to the jump statements discussed here, java supports one other way by which you can change your program flow of execution, through exception handling,Exception handling provides a structured method by which run-time error can be trapped and handled by your program, it is supported by the keywords try, catch ,throw , throws and finally 

Using break 

in java the break statement has three users, First, as you have seen, it terminates a statement sequence in a switch statement, Second, it can be used to exit a loop, Third it can be used ad a "civilized " form of goto. the last two uses are explained here,

Using break to exit a loop 

By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop, when a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop
class UsingBreak {

    public static void main(String[] args) throws IOException {

       for(int i=0; i<100; i++){
           if (i==10) break;
           System.out.println("i is :"+i);
       }
        System.out.println("loop Complete.");
    }
}
OUTPUT 
i is :0
i is :1
i is :2
i is :3
i is :4
i is :5
i is :6
i is :7
i is :8
i is :9

loop Complete.

As you can see, although the for loop is designed to run form 0 to 99 the break statement causes it to terminated early, when i equals 10
the break statement can be used with any of java's loop, including intentionally infinite loops for example here is the preceding program coded by use of while loop, The output if this is the same as just shown
class UsingBreak {

    public static void main(String[] args) throws IOException {
        int i = 0;
        while (i<100) {
            if (i == 10) break;
            System.out.println("i is :" + i);
            i++;
        }
        System.out.println("loop Complete.");
    }
}
When used inside a set of nested loop, the break statement will only break out of the innermost loop.
class UsingBreak {

    public static void main(String[] args) throws IOException {
        for(int i =0; i<3; i++){
            System.out.print("pass "+i+" : ");
            for(int j=0; j<100; j++){
                if(j==10)break;
                System.out.print(j+" ");
            }
            System.out.println("");
        }
        System.out.println("Loops Complete.");
    }
}
OUTPUT
pass 0 : 0 1 2 3 4 5 6 7 8 9 
pass 1 : 0 1 2 3 4 5 6 7 8 9 
pass 2 : 0 1 2 3 4 5 6 7 8 9 

Loops Complete.

As you can see, the break statement in the inner loop only causes termination of the loop, the outer loop is unaffected,
Here are two other points to remember about break, first more then one break may appear in a loop.
However be careful too many break statements have the tendency to restructure you code, Second the break, that terminates a switch statement affects only the switch statement and not any enclosing loop.

Using continue

Sometime it is useful to force an early iteration of a loop that is, you might to continue running the loop but stop processing the remainder of the code in its body for this particular iteration, this is, in effect, a goto just past the body of the loop, to the loop's end the continue statement performs such an action. In while and do while loops a continue statement causes control to be transferred directly to the conditional expression that controls the loop, in a for loop , control goes first to the iteration portion of the for statement and then to the conditional expression, for statement loops. any intermediate code is by passed, 
Here is an example program that uses continue to cause two numbers to be printed on each line: this code use the % operator to check if i is even, if it is the loop continues without printing a new line .
class UsingContinue {

    public static void main(String[] args) throws IOException {
        for(int i=0; i<10; i++){
            System.out.print(i+" ");
            if(i%2 == 0)continue;
            System.out.println("");
        }
    }
}
OUTPUT
0 1 
2 3 
4 5 
6 7 

8 9 

return 

The return statement is used to explicitly return from a method. That is it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. Although for a full discussion of return, You must until methods are discussed, we present a brief look at return, 
At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed, The following examples illustrates this point. Here return causes execution to return to the java run-time system,Since it is the run time system that calls main method (  public static void main(String[] args) )
class UsingReturn {

    public static void main(String[] args) throws IOException {
        boolean t = true;
        System.out.println("Befor the return ");
        if(t) return;
        System.out.println("this is not executed");
    }
}

Monday, November 11, 2013

Flow Controls - for Loop

General form of the traditional for statement :
for( initialization; condition; iteration ){
               // body
}
if only one statements is being repeated, there is no need for the curly braces.
The for loop operates as follows. when the loop first starts, the initialization portion of the loop is executed.Generally , this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop. it is important to understand that the initialization expression is only executed once, Next condition is evaluated, this must be a boolean expression, it usually tests loop control variable against a target value, if this expression is true , then the body of the loop is executed, if it is false, the loop terminates. next the iteration portion of the loop is executed. this is usually an expression that increments or decrements the loop control variable, the loop then iterates, first evaluation the conditional expression, then executing the body of the loop , and then executing the iteration expression with each pass, this process repeats until the controlling expression is false.
here is a version of the "tick " program that uses a for loop.

Declaring Loop Control variables inside the for loop

class ForLoopTest {

    public static void main(String[] args) throws IOException {
     
        int n;
        for(n=10; n>0; n--){
            System.out.println("tick "+n);
        }
    }
}
Often the variable that controls a for loop is only needed for the purpose of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for. For example, here is the preceding program re-coded so that the loop control variable n is declared as an int inside the for:
when you declare a variable inside a for loop, there is one important point to remember, the scope of the
class ForLoopTest {

    public static void main(String[] args) throws IOException {
     
        for(int n=10; n>0; n--){
            System.out.println("tick "+n);
        }
    }
}
variable ends when the for statement does, (that is, the scope of the variable is limited to the for loop) Outside the for loop, the variable will cease to exist, if you need to use the loop control variable elsewhere in your program, you will not be able to do it inside the for loop.
when the loop control variable will not be needed elsewhere, most java programmers declare it inside the for.EX : the following program tests for prime numbers Notice that the loop control variable, i is declared inside the for since it is not needed elsewhere,
class ForLoopTest {

    public static void main(String[] args) throws IOException {

        int num;
        boolean isPrime = true;
        num = 14;
        for (int i = 2; i < num / i; i++) {
            if ((num % i) == 0) {
                isPrime = false;
                break;
            }

            if (isPrime) {
                System.out.println("Prime");
            } else {
                System.out.println("Not Prime");
            }
        }
    }
}
The for loop supports a number of variation that increases its power and applicability. The reason it is so flexible is that its three parts, the initialization, the conditional test, and the iteration, do not need to be used for only those purposes, In fact, the three sections of the for can be used for any purpose you desire, Let's look at some examples.
One of the most common variations involves the conditional expression, Specifically , this expression does not need to test the loop control variable against some target value. In fact, the condition controlling the for can be any boolean expression.

class ForLoopTest {

    public static void main(String[] args) throws IOException {

       boolean done = false;
       for(int i = 10; done; i++){
           if(i==5) done =false;
       }
     
    }
}
Here, the for loop continues to run until the boolean variable done is set true, it does not test the value of i.
Here is another interesting for loop variation, either the initialization or the iteration expression or both may be absent, as in this next program.
class ForLoopTest {

    public static void main(String[] args) throws IOException {

        int i;
        boolean done = false;
        i = 0;
        for (; !done;) {
            System.out.println("i is :" + i);
            if (i == 10) {
                done = true;
            }
            i++;
        }
    }
}
Here, the initialization and iteration expressions have been moved out of the for, thus, parts of the for are empty while this is of no value in this simple example indeed, it would be considered quite poor style there can be times when this type of approach makes sense ,
Eg :- if the initial condition is set through a complex expression elsewhere in the program or if the loop control variable changes in a non sequential manner determined by actions that occur within the body of the loop, it may be appropriate to leave these the for empty.
Here us one more for loop variation, You can intentionally create an infinite loop (a loop that never terminates ) if you leave there parts if the for empty.
Eg:
for( ; ; ){
          // body
}

Nested loops 

like all other programming languages, Java allows loops to be nested, that is one loop may be inside another

class ForLoopTest {

    public static void main(String[] args) throws IOException {

        int i,j;
        for(i=0; i<10; i++){
            for (j=i; j<10; j++){
                System.out.print(".");
            }
             System.out.println("");
        }
    }
}
Output
..........
.........
........
.......
......
.....
....
...
..

.


Saturday, November 9, 2013

Flow Controls - do while loop

As you just saw, if the conditional expression controlling a while loop in initially false, then the body of the loop will not be executed all However, sometime it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with, In other words, there are times when you would like to test the termination expression at the end of the loop rather then at the beginning, Fortunately, java has a loop that does that : the do while loop the do while loop always executes its body at least one, because its conditional expression is at the bottom of the loop. its general form is
do {
      // body
}while (condition );
Each iteration of the do while loop first executes the body of the loop and then evaluates the conditional expression. if this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of java's loops, condition must be a boolean expression, here is a reworked version of the "tick " program that demonstrates the do while loop.
class Dowhile{
            public static void main(String args[]){
                          int n = 10;
                          do {
                                       System.out.println("tick "+n);
                                       n--;
                           }while (n > 0);
                       
           }
}
It generates the same output as before. The loop in the above program, while technically correct, can be written efficiently as follows;
do {
           System.out.println("tick "+ n);
}while(--n >0 );
Here, the expression (--n >0) combines the decrements of n and the test for zero into one expression, here is how it works, First, the --n statement executes, decrements n and return the new value of n. this value is then compared with zero,  the loop continues, otherwise it terminates, a menu selection, because you will usually want the body of a menu loop to execute at least once, Consider the following example
class Menu {

    public static void main(String[] args) throws IOException {
        char c;
        do {
            System.out.println("Your name");
            System.out.println("Jone ");
            System.out.println("karina");
            System.out.println("max");
            System.out.println("chose one :");
            c = (char) System.in.read();
        } while (c < '1' || c > '3');
        System.out.println("\n");
        switch (c) {
            case '1':
                System.out.println("My Name is Jone");
                break;
            case '2':
                System.out.println("My Name is Karina ");
                break;
            case '3':
                System.out.println("My name is max");
        }
    }
}

Output 
Your name
Jone
karina
max
chose one :
1

My Name is Jone

In the program, the do while loop is used to verify that the user has entered a valid choice if not, then the user is re prompted. Sine the menu must be displayed  at least once, the do while is the perfect loop to accomplish this
A few other points about this example Notice that characters are read from the keyboard by calling System.in.read(); this is one of java's console input functions, Although java's console I/O methods won't be discussed till the later System.in.read(); is used here to obtain the user;s choice it reads characters form standard input ( returned as integers, which is why the return value was cast to char ) . By default. standard input is line buffered, so you must press ENTER before any characters that you type will be sent to you program.java's console input can be a bit awkward to work with. Further. most real world program and applets will be graphical and window based For these reasons, not much use of console input has been made in this However , is is useful in this context point to consider because System.in.read(); is being used, the program must specify the throw java.io.IOException clause, This line is necessary to handle input errors, it is part Java's exception handling features, which are discussed later.

Thursday, October 31, 2013

Flow Control - while loop

Iteration Statements

java's iteration statements are for,while and do - while.These statements create what we commonly call as loops, As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met. As you will see, Has a loop to fit any programming need.

while loop

The while loop is java's most fundamental loop statement. it repeats a statement or block while it controlling expression is true. Here is its general from;
while (condition) {
         // body of loop
}
The condition can be any boolean expression, The body of the loop will be executed as long as the conditional expression is true, When condition become false, control passes to the next line of code immediately following the loop, the curly braces are unnecessary if only a single statement is being repeated.

Here is a while loop that counts down from 10, print exactly ten line of "tick"
class WhileExample{
               public static void main(String args[]){
                             int i = 10;
                             while(i > 0){
                                        System.out.println("tick "+i);
                                        i--;
                             }
               }
}
Output :
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1

Sine the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute even once if the the condition is false to begin with. For example, in the following fragment, the call to println() is never executed.
class WhileExample {

    public static void main(String args[]) {
        int a =10, b=20;
        while (a> b) {          
            System.out.println("not print");
        }
     
    }
}
The body of the while (or any other of java loops ) can be empty. This is because a null statement (one that consists only of a semicolon ) is syntactically valid in java.
example this program finds of the midpoint between i and j.
class WhileExample {

    public static void main(String args[]) {
       int i, j;
       i = 100;
       j = 200;
        while (++ i < --j) ;
        System.out.println("midpont is "+i);
       
    }
}
Output
               midpont is 150
Here is how this while loop works, The value of i is incremented, and the value of j is decremented, these values are then compared with one another, if the new value of i is less then the new value of j then the loop repeats, if i is equal to or greater then j stops,Upon exit form the loop i will hold a value that is midway between the original value of i and j , (Of course, this procedure only works when i is less then j to begin with.) As you can see, there is no need for a loop body, expression, itself.


Monday, October 28, 2013

Flow Controls - switch

The switch statements is java's multiway branch statement. It provides an easy way to c execution to different parts of your code based on the value of an expression. As such, it offers a better alternative the a large series of if else if statements the General form of a witch statement;
switch (expression) {
 
 case value 1 :   // Statement sequence
                         break;
 case value 2 :  // Statement sequence
                        break;
 case value 3 :  // Statement sequence
                        break;
default           : // default statement sequence

}

The expression must be of type byte, short, int or char each of the value specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal (that is , it must be a constant, not a variable) duplicate case values are not allowed.

The switch statement works like this:

 the value of the expression is compared with each of the literal values in the case statements. if a match is found, the code sequence following that case statement is executed.
class Switch {

    public static void main(String[] args) {
        int switchValue = 3;

        switch (switchValue) {
            case 1:
                System.out.println("One");
                break;
            case 2:
                System.out.println("Two");
                break;
            case 3:
                System.out.println("three");
                break;
            case 4:
                System.out.println("Four");
                break;
            default:
                System.out.println("Not Match");
        }
    }
}
Output
three

if none of the constants matches the values of the expression. then the default statement is executed. However, the default statement is optional, if no case matches and no default is present, then no further action is taken,

the break statement is used inside the switch to terminate a statement sequence. when a break statement is encountered,execution branches to the first line of code that follows the entire switch statement, This has the effect of jumping out of the switch.
class Switch {

    public static void main(String[] args) {
        int switchValue = 3;

        switch (switchValue) {
            case 1:
                System.out.println("One");
            case 2:
                System.out.println("Two");
            case 3:
                System.out.println("three");
            case 4:
                System.out.println("Four");
            default:
                System.out.println("Not Match");
        }
    }
}
Output
three
Four

Not Match

Flow Control - Nested If

Nested ifs 

A nested if is an if statement that is the target of another if or else, Nested ifs are very common in programming, when You nest ifs, the main thing to remember is the and else statement always refer to the nearest if statement that is withing the same block as the else and that is not already associated with an else.
class NestedIfs {

    public static void main(String[] args) {
        int i = 10;
        int k = 20;
        if (i == 10) {
            int j =10;
            if (j < 20) {
            }
            if(k >20){ // this if is associated with
            }else{//this else
            }
        } else {
            // this else refers to if (i==10)
        }
    }
}
As the comments indicate, the final else is not associated with if (j<20) because it is not in the same block (even though it is the nearest if without an else).Rather, the final else is associated with  if(i==10). the inner else refers to if (k > 20) because it is the closest if within the same block.

The if-else-if Ladder

A common programming construct that is based upon a sequence of nested ifs is the if else if ladder. It looks like this 
if(condition){
             // Statement;
}else if(condition){
           // Statement;
}else if(condition){
          // Statement;
}.....
...............
...............
...............
..............
else{
            // Statement;
}
The if statements are executed from the top do down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, conditions is true, then the final else statements will be executed, the final else acts as a default condition,That is if all other conditional tests fail, then the last else statement is performed. if there is no final else and all other conditions are false, then no action will take place.The following simple program uses an if else if ladder.
class IfElseIF {

    public static void main(String[] args) {
       int x = 10;
       if(x == 8){
           System.out.println("X is eight");
       }else if(x == 9){
           System.out.println("x is nine");
       }else if(x==10){
           System.out.println("x is ten");
       }else{
           System.out.println("x big then ten");
       }
    }
}

Flow Controls

A program language uses control statements to cause the flow of execution to advance and branch based on changes to the state of a program. Java's program control statements can be put into the following categories

  • selection.
  • Iteration
  • jump
Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration statements enable program execution to repeat one or more statement (That is, iteration statements form loops). Jump statements allow your program to execute in a nonlinear fashion, All of java's control statements are examined here.

Java's Selection Statements 

Java supports two selection statements: if and switch, These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

if Statements 

The if statement was introduced earlier. if is examined in detail here. The if statement is java's conditional branch statements it can be used to route program execution through two different paths, Here is the general from of the if statement:
if(condition){
        // Statement One
}else{
      // Statement Two
}

Here each statement may be a single statement or a compound statement enclosed in curly braces (That is, a block ). The condition is any expression that returns a boolean value.The else clause is optional.

The if works like this: if the condition is true, then statement One is executed. Otherwise, Statements Two (if it exists) is executed. in no case will both statements be executed .

Example 
class IfElseStatement{

    public static void main(String[] args) {
     
        int a = 10;
        int b = 5;
     
        if(a>b){
            a = 0;
        }else{
            b = 0;
        }
     
        System.out.println("A and B :"+ a+" "+b);
 
    }
}

Here, if a is less than b, Then a is set zero.Otherwise, b is set zero.In no case are they both set to zero.
Most often, the expression used to control the if will involve the relational operator:  However, this is not technically necessary, it is possible to control the if using a single boolean variable, as shown.

class IfElseStatement{

    public static void main(String[] args) {
     
       boolean b = true;
        if (b) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
 
    }
}
Remember, only one statement can appear directly after the if or the else if you want to include more statements, you'll need to create a block, as shown

class IfElseStatement{

    public static void main(String[] args) {
     
       int x = 10;
       if(x>5){
           int i = 10;
           i+=20;
           System.out.println("i is : "+ i);
       }else{
           int e = 34;
           e+= 45;
           System.out.println("e is :"+ e);
       }
    }
}
Here, both statements withing the if block will execute if date is greater than 30. is is always better to include the curly braces when using the if, even when there is only one statement in each clause, This makes it easy to add and statement later.
class IfElseStatement{

    public static void main(String[] args) {
     
       int date = 10;
   
       if(date > 30){
          changeToNextMoth();
          date = 1;
       }else{
           waitMorDate();
           date+=1;
       }
    }
 
    public static  void changeToNextMoth(){
        int moth = 4;
        moth+=1;
    }
 
    public static void waitMorDate(){
        System.out.println("wait...");
    }
 
}
It seems clear that the statement System.out.println("wait..."); was intended to executed inside the esle clause, because of the indentation level. However , since java doesn't recognize whitespace, and there is no way for the compiler to know what was intended, This will compile fine, but it will behave incorrectly when run. The above example is corrected as follows:
class IfElseStatement{

    public static void main(String[] args) {
     
       int date = 10;
   
       if(date > 30){
          changeToNextMoth();
          date = 1;
       }else{
           waitMorDate();
           date+=1;
       }
    }
 
    public static  void changeToNextMoth(){
        int moth = 4;
        moth+=1;
    }
 
    public static void waitMorDate(){
        System.out.println("wait...");
    }
 
}

Sunday, October 27, 2013

Arrays

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

One - Dimensional Arrays

A one dimensional array is essentially, a list of variables of the same type. To create an array, you first must create an array variable of the desired type. the general form of a one dimensional array declaration is
Type variable_Name [];
Here, type declares the base type of the array, the base type determines the data type of each element in the array.
Example ti declares an array named montDays with the type "array of int"
int mothDays [];
Although the declaration says that monthDays is an array variable, no array actually exists, That is, the array monthdays is set to null, which represents an array with no value. To link montDays with an actual Physical array of integers, you must allocate one using new and assign it to mothDays, new is a special operator that allocates memory
variable_Name = new type [size];
Here type specifies the type of data being allocated, size specifies the number of elements in the array, and variable_Name 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. The following example allocates a 12 element array of integers and links them to month_days.
class MyFirstArray{

    public static void main(String[] args) {
     
        int moth_days [] = new int[12];

    }
}
After this statement executes, moth_days will refer to an array of 12 integers,Also all elements in the array will be initialized to zero.

Obtaining an array is a two way process.

  1. Declare a variable of the desired array type.
  2. allocate the memory that will hold the array. using new and assign it to the array variable.
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
class MyFirstArray{

    public static void main(String[] args) {
     
        int moth_days [];
        moth_days = new int[12];
     
        moth_days[0] = 31;
        moth_days[1] = 28;
        moth_days[2] = 31;
        moth_days[3] = 30;
        moth_days[4] = 31;
        moth_days[5] = 30;
        moth_days[6] = 31;
        moth_days[7] = 31;
        moth_days[8] = 31;
        moth_days[9] = 31;
        moth_days[10] = 30;
        moth_days[11] = 31;
        System.out.println("April has : "+moth_days[3]+" Day's");
    }
}
The above Program creates an array of the number of days in each month.

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

    public static void main(String[] args) {
     
        int moth_days [] = new int[12];
 
    }
}
Array can be initialized when they are declared, the process is much the same as that used to initialize the simple types, An array initialize is a list of comma separated expressions surrounded by curly braces, the commas separated 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 initialize. There is no need to user new.

Example 
class MyFirstArray{

    public static void main(String[] args) {
       
        int moth_days [] = {30,28,31,30,31,30,31,31,31,31,30,31};
        System.out.println("April has : "+ moth_days[3]+" Day's");
 
    }
}
Java strictly checks to make sure that you do not accidentally try to store or refer to values outside of the range of the array, The Java run time system will check that all array indexes are in the correct range.If you try to access elements outside the range of the array, you will cause a run time error.

Type Conversion and casting

It is common to assign a value of one type to a variable of another type. if the two types are compatible, them java will perform will perform the conversion automatically.
Example
class type{
    public static void main(String[] args) {
        int i = 100;
        long l = i;
    }
}
It is always possible to assign an int value to long variable However, not all types are compatible. Therefore, not all conversions are compatible. Therefore not all conversions are implicitly allowed , Example there is no conversion allowed from double to byte. However conversion between incompatible types is also possible. For this, you must use a cast, which performs an explicit conversion between incompatible types.

Automatic Conversions

When one type of data is assigned to another type of variable, an automaric conversion will take place if the following are true.

  • The two types are compatible.
  • the destination type is larger than the source type.
When these are true, a widening conversion takes place Example the int type is always large enough to hold all valid byte values, so no explicit casting is required. For widening conversion, the numeric type, including Integer and floating point types,are compatible with each other, However, numeric types are not compatible with char or boolean.  Also char and boolean are also not compatible with each other. Also java performs an automatic conversion when storing a literal integer constant into variable of type byte, short or long.

Casting Incompatible types 

What if you want to assign an int value to byte variable? This conversion will not be performed automatically as a byte is smaller then an int. this type of conversion is called as 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 has Form:
Data_Type Variable_name = (Target_Data_Type) Value;
Here, target type is the desired type to convert the specified value to Example the following code fragment casts an int to a byte, it will be reduced to modulo byte's range.
class type{
    public static void main(String[] args) {
        int a = 258;
        byte b = (byte) a;
        System.out.println("b is : "+b);
    }
}
Output 
b is : 2

When a floating point value is assigned top an int, truncation will occur. Since integers do not have fraction parts, When a floating point is assigned to an int variable, the fractional part gets lost.
class Conversion {

    public static void main(String[] args) {
        byte b;
        int i = 257;
        double d = 323.142;
        System.out.println("Convert Int to byte");
        b = (byte) i;
        System.out.println("i and b : "+i+" "+b);
        System.out.println("Convert double to int ");
        i = (int) d;
        System.out.println("d and i : "+d+" "+ i);
        System.out.println("Convert double to byte ");
        b = (byte) d;
        System.out.println("d and b : "+d+" "+b);

    }
}

Output 
Convert Int to byte
i and b : 257 1
Convert double to int
d and i : 323.142 323
Convert double to byte

d and b : 323.142 67

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

Automatic type promotion in expressions

In addition to assignments, conversions occur in expressions. Take a look at the following example.

class AutoCast{
    public static void main(String[] args) {
        byte a = 40;
        byte b = 50;
        byte c = 100;
        int d = a * b / c;
    }
}

The result of the intermediate term a * b is 2000, which exceeds the range of a byte. To handle this problem. Java automatically promotes each byte or short operand to int when evaluation an expression.This means that subexpression a*b is performed using integers, and not bytes.Therefore, The result of the intermediate expression, 50 * 40 is legal even though a and b are both specified as type byte.

Type Promotion Rules 

In addition to the promotion of bytes and shorts to int, defines several type promotion rules that apply to expression, 
  • All Byte and short values are promoted to int, as hast described.
  • if one operand is a long, the whole expression is promoted to long.
  • If one operand is a float, the entire expression is promoted to float.
  • If any of the operands is double, the result is double.
class Promote{

    public static void main(String[] args) {
        byte b = 42;
        char c = 'a';
        short s = 1024;
        int i = 50000;
        float f = 5.67f;
        double d = 0.1234;
        double result = (f*b)+(i/c)-(d*c);
        System.out.println((f*b)+"+"+(i/c)+"-"+(d*c));

    }
}
Lets Us take look at the following line
double result = (f*b)+(i/c)-(d*c);

In the first subexpression, f*b, b is promoted to a float and the result of the subexpression is float. Next in the subexpression i/c, c is promoted to int , and the result is of type int Then in d*s, the value of s is promoted to double , and the type of the subexpression is double.Finally, these three intermediate values, float, int  and double are considered.The Outcome of float plus an int is a float.Then the resultant float minus the last double,which is the type for the final result of the expression. 

Saturday, October 26, 2013

The scope and life time of variables

Lift Time of variable

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 begins 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 creation a new scope.A scope determines what objects are visible to other parts of your program. it also determines the lifetime of those objects.

They are four type of variable's 

  1. Instance Variables
  2. Method Local Variables
  3. Block Variables
  4. Static Variables 
class Variables {

 
   static int high = 25;                           // static variable
   int with = 30;                                   // instance Variable
 
    public void myMethod(){
        double area = 100;                    // method local variable
        for (int i = 0; i < 10; i++) {
            int value = 10+i;                     // block variable
        }
    }
}
In java, the two major scopes are those defined by a class and those defined by a method. For now we will be discussing only the scope defined by a method, The scope defined by a method begins with its opening curly brace, However, if that method has parameters, they too are include within the method scope. Parameters too work in the same way as any other method variable.
As a general rule, Variables declared inside a scope are not visible to code that is defined outside the scope, therefore , when you declare a variable within a scope, you are localizing that variable and protection it from unauthorized access and modification.

Scope can be nested eg : each time you create a block of code, you are creation a new , nested scope, when this occurs, the outer scope encloses the inner scope, this means that objects declared int he 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
class Scope {

    public static void main(String[] args) {
        int x; // visible to all code within main
        x =10;
        if(x==10){  // start new scope
            int y = 20; // visible onlly to this block
            // x and y both visible here
            System.out.println("X is : "+x+"  "+ "Y is : "+y);
        }
     
        y = 100;  // Error, variable y is not visible here
        // x still visible here
        System.out.println("X is :" +x);
    }
}
x is declared at the start of main() scope and is accessible to all subsequent code within the main().Within if block y is declared. Since a block defines a scope,Y is only visible to code within its block.This is why outside of its block,the line y = 100; is commented our Within the if block, x can be used because code within a block has access to variables declared by the outside scope.

Within a block,variables can be declared at any point but are valid only after they are declared, Therefore, if you declared a variable at the start of the code, All the code written after that will have access to that variable, However , if a variable is declared at the end of the code, the code written before the declaration will not have access to that particular variable.

Variables are created when their scope is entered and destroyed when their scope is left, This means a variable will not hold its value once it has one 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, the lifetime of variable is limited its scope.

if a variable declaration includes an initializer , then that variable will be re- initialized each time the block in which it is declared is entered,

Example 


class LifeTiem {

    public static void main(String[] args) {
        int x;
        for (int i = 0; i < 3; i++) {
            int y = -1; // initialized each time block is enterd
            System.out.println("Y is : "+ y);
            y = 100;
            System.out.println("Y is Now : "+ y);
        }
    }

}
Output :
Y is : -1
Y is Now : 100
Y is : -1
Y is Now : 100
Y is : -1
Y is Now : 100

As your see, Y is always re-initialized to -1 each time the inner for loop is entered. Even though later in the code, it is entered the value 100 this value is lost

Java variables

Variables 

The variable is the basic unit of storage in a java program. it is defined by the combination of an identifier , a type,and an optional initialize. also all variables have a scope,which defines their visibility, and their lifetime, Let us look at variables in depth,

A variable is Temporary memory Allocation   

Declaring Variable

In java all variable must be declared before they can be used, the basic form of a variable declaration is 

TYPE IDENTIFIER = VALUE
The type is one of java's primitive data 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, the initialization expression must result in a value of the same type as that specified for the variable,To declare more the one variable of the specified type, use a comma separated list.

        int a ,b,c;
        int d=3,e,f=5;
        byte z = 22;
        double pi = 3.14159;
        char x = 'x';
class Area {

    public static void main(String[] args) {
        double hight,width,area;
        hight = 10.8;
        width = 3.1416;
        area = hight * width;
        System.out.println("Area is :"+ area);
    }
}
Output :
              Area is :33.92928

Dynamic initialization

Although the earlier examples have used only constants as initializers, java allows variable dynamcally, using 
class Area {

    public static void main(String[] args) {
        double high,width;
        high = 10.8;
        width = 3.1416;
        double area = high * width; // area is dynamically initialized 
        System.out.println("Area is :"+ area);
    }
}
Any expression valid at the time the variable is declared, the following program computers the area af a rectangle.
Here,Three Local Variables, high , width, area are declared. the first two high and width are initialized by constants, area is initialized dynamically to the area of the rectangle

String Class

As in most other languages, in java also it is specified by enclosing a sequence of characters between a pair of double quotes,Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Declaring Strings:
The most direct way to create a string is to write:
String name = "Your Name";

Example 
class StringTest {

    public static void main(String[] args) {
        String name = "Your Name";
        String twoLine = " Line One \n Line Two";
        String quotes = "\"This is in quotes \" ";
        System.out.println(name);
        System.out.println(twoLine);
        System.out.println(quotes);
    }
}
Output :
anup
 Line One 
 Line Two
"This is in quotes " 


Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Your Name'.


As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.

public class CharArray{

   public static void main(String args[]){
      char[] charArray = { 'h', 'e', 'l', 'l', 'o', '.'};
      String helloString = new String(charArray);
      System.out.println( helloString );
   }
}
Output
hello.
class StringTest {

    public static void main(String[] args) {
        String v1="45";
        String v2="46";
        System.out.println(v1+v2);
    }
}
Output 
4546

String Class Methods


Methods with Description
1char - charAt(int index)
Returns the character at the specified index.
2int - compareTo(Object o)
Compares this String to another Object.
3int - compareTo(String anotherString)
Compares two strings lexicographically.
4int - compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
5String - concat(String str)
Concatenates the specified string to the end of this string.
6boolean - contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
7static - String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
8static - String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
9boolean - endsWith(String suffix)
Tests if this string ends with the specified suffix.
10boolean - equals(Object anObject)
Compares this string to the specified object.
11boolean - equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
12byte - getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
13byte[]- getBytes(String charsetName
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
14void - getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
15int - hashCode()
Returns a hash code for this string.
16int - indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
17int - indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
18int - indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
19int - indexOf(String str, int fromIndex
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
20String - intern()
Returns a canonical representation for the string object.
21int - lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
22int - lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
23int - lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
24int - lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
25int - length()
Returns the length of this string.
26boolean - matches(String regex)
Tells whether or not this string matches the given regular expression.
27boolean - regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
28boolean - regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
29String - replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
30String - replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
31String - replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
32String[] - split(String regex)
Splits this string around matches of the given regular expression.
33String[] - split(String regex, int limit)
Splits this string around matches of the given regular expression.
34boolean - startsWith(String prefix)
Tests if this string starts with the specified prefix.
35boolean - startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
36CharSequence - subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
37String - substring(int beginIndex)
Returns a new string that is a substring of this string.
38String - substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
39char[] - toCharArray()
Converts this string to a new character array.
40String - toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
41String - toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
42String - toString()
This object (which is already a string!) is itself returned.
43String - toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
44String - toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
45String - trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
46static - String valueOf(primitive data type x)
Returns the string representation of the passed data type argument.

Character Class

Insurance,Loans,Mortgage,Attorney,Credit,Lawyer,Donate,Degree,Hosting,Claim,Conference Call,Trading,Software,Recovery,Transfer,Gas/Electricity,Classes,Rehab,Treatment, Cord Blood,

In java, The data types used to store characters is char. Java uses Unicode to represent character,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 ,Hebrew 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 bi negative chars Since java is designed to allow applets to be written for worldwide use,it makes sense that is would use Unicode to represent characters

Example 
class UsingChar {

    public static void main(String[] args) {
        char c1,c2;
        c1 = 88;
        c2 = 'Y';
        System.out.print("c1 and c2 : ");
        System.out.println(c1+" "+c2);
    }

}
Output :
       c1 and c2 : X Y

Notice that c1 is assigned the value 88, which is the ACCII (and Unicode) value that corresponds to the letter first 127 values in the Unicode character set,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, of to increment the values of a character variable.

Example 
class UsingChar {

    public static void main(String[] args) {
        char c1;
        c1 = 'X';
        System.out.println("c1 is : "+c1);
        c1++;
        System.out.println("c1 is : "+c1);
   
    }
}
Output 
         c1 is : X

         c1 is : Y

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

However in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper class Character for primitive data type char.

The Character class offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor
Character c = new Character('a');

The Java compiler will also create a Character object for you under some circumstances. For example, if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character for you. This feature is called autoboxing or unboxing, if the conversion goes the other way.

Escape Sequences:

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.

The newline character (\n) has been used frequently in this tutorial in System.out.println() statements to advance to the next line after the string is printed.

Following table shows the Java escape sequences:

Escape SequenceDescription
\tInserts a tab in the text at this point.
\bInserts a backspace in the text at this point.
\nInserts a newline in the text at this point.
\rInserts a carriage return in the text at this point.
\fInserts a form feed in the text at this point.
\'Inserts a single quote character in the text at this point.
\"Inserts a double quote character in the text at this point.
\\Inserts a backslash character in the text at this point.

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly

Example 
class UsingChar {

    public static void main(String[] args) {
        System.out.println("I said \"Yes\" ");
        System.out.println("\n");
        System.out.println(" 1 +\n 1\n --\n 2");
    }
}
Output 
I said "Yes"

 1 +
 1
 --

 2

Character Methods

Here is the list of the important instance methods that all the subclasses of the Character class implement


SNMethods with Description
1isLetter()
Determines whether the specified char value is a letter.
2isDigit()
Determines whether the specified char value is a digit.
3isWhitespace()
Determines whether the specified char value is white space.
4isUpperCase()
Determines whether the specified char value is uppercase.
5isLowerCase()
Determines whether the specified char value is lowercase.
6toUpperCase()
Returns the uppercase form of the specified char value.
7toLowerCase()
Returns the lowercase form of the specified char value.
8toString()
Returns a String object representing the specified character valuethat is, a one-character string.

Wednesday, October 16, 2013

Number Class

Insurance, Loans,Mortgage,Attorney, Credit, Lawyer, Donate, Degree, Hosting, Claim, Conference Call, Trading, Software, Recovery, Transfer, Gas/Electricity, Classes, Rehab, Treatment, Cord Blood,


Number class

When working with numbers, most of the time you use the primitive types in your code.
For example:
int i = 500;
float gpa = 3.65f;
byte mask = 0xff;
However, in development, we come across situations where we need to use objects instead of primitive data types. In-order to achieve this Java provides wrapper classes for each primitive data type.

All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.

This wrapping is taken care of by the compiler, the process is called boxing. So when a primitive is used when an object is required, the compiler boxes the primitive type in its wrapper class. Similarly, the compiler unboxes the object to a primitive as well. The Number is part of the java.lang package.

There are three reasons that you might use a Number object rather than a primitive:

  • As an argument of a method that expects an object (often used when manipulating collections of numbers).
  • To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type.
  • To use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary)
Boxing and UnBoxing
boxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Example of boxing :
class BoxintExample {

    public static void main(String args[]) {
      int x = 10;
      Integer integer = x;
        System.out.println(integer);
    }
}
Output is :- 10

Example of UnBoxing :
class UnBoxintExample {

    public static void main(String args[]) {
      int x = 10;
      x = x+10;
    }
}
Output is 10


Java if else

Insurance Loans Mortgage Attorney Credit Lawyer Donate Degree Hosting Claim Conference Call Trading Software Recovery Transfer Gas/Electricity Classes Rehab Treatment Cord Blood

The if Statement:

An if statement consists of a Boolean expression followed by one or more statements.
The syntax of an if statement is:
if(boolean_expression) {
   //Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be executed.

Exampl
class IfStatement {
    public static void main(String[] args){
        int x = 10;
        if(x == 10){
            System.out.println("X is equal to 10");
        }
    }
}

The Output is
X is equal to 10

if else Statement 

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
if(boolean_expression){
   //Executes when the Boolean expression is true
}else{
   //Executes when the boolean expression is false
}
Example 
class IfElseStatement {
    public static void main(String[] args){
        int x = 12;
        if(x == 10){
            System.out.println("X is equal to 10");
        }else{
             System.out.println("X is Not equal to 10");
        }
    }
}
Out put is
X is Not equal to 10

The if else if else Statement

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
  • An if can have zero or one else's and it must come after any else if's.
  • An if can have zero to many else if's and they must come before the else.
  • Once an else if succeeds, none of the remaining else if's or else's will be tested.
The syntax of an if else if
if(Boolean_expression 1){
   //Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
   //Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
   //Executes when the Boolean expression 3 is true
}else {
   //Executes when the none of the above condition is true.
}
Example 
class IfElseIfStatement {
    public static void main(String[] args){
        int x = 12;
        if(x == 10){
            System.out.println("X is equal to 10");
        }else if(x==11){
             System.out.println("X is equal equal to 11");
        }else if(x==12){
             System.out.println("X is equal equal to 12");
        }else{
            System.out.println("X > 12");
        }
    }
}
Output is
X is equal equal to 12

Nested if else Statement

A nested if statement is an if-else statement with another if statement as the if body or the else body.
The syntax of Nested if else
if(Boolean_expression 1){
   //Executes when the Boolean expression 1 is true
   if(Boolean_expression 2){
      //Executes when the Boolean expression 2 is true
   }
}
Example 
class NestedIfElse {
    public static void main(String[] args){
        int firstValue = 12;
        int secondValue = 20;
     
        if(firstValue ==12){
            System.out.println("First Value is 12");
            if(secondValue == 20){
                System.out.println("Second Value is 20");
            }
        }
     
    }
}
Output is
First Value is 12
Second Value is 20

The switch Statement

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

The syntax of switch statement
switch(expression){
    case value :
       //Statements
       break; //optional
    case value :
       //Statements
       break; //optional
    //You can have any number of case statements.
    default : //Optional
       //Statements
}

The following rules apply to a switch statement

The variable used in a switch statement can only be a byte, short, int, or char.

  • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
  • The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
  • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
  • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
  • Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
  • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
class SwitchStatement {

    public static void main(String args[]) {
        int value = 10;

        switch (value) {
            case 5:  System.out.println("Value is Five");
               break;
             
            case 10: System.out.println("Value is Ten");
                break;
            case 15: System.out.println("Value is fivtean");
                break;

        }
        System.out.println("Your value is > 15");
    }
}

The Output is :-
Value is Ten
Your value is 10