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

Tuesday, October 15, 2013

Java Loops

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

About java loops

There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
  • while Loop
  • do while Loop
  • for Loop

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

while Loop

The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:
while (expression) {
     //statement
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement's in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileLoop program:
class WhileLoop {
    public static void main(String[] args){
        int count = 1;
        while (count < 11) {
            System.out.println("Count is: " + count);
            count++;
        }
    }
}
Output is

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

You can implement an infinite loop using the while statement as follows:

while (true){
    // your code goes here
}

do while Loop 

The Java programming language also provides a do-while statement, which can be expressed as follows



do {
     statement's
} while (expression);


The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileLoop program:

class DoWhileLoop {
    public static void main(String[] args){
        int count = 1;
        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 11);
    }
}

Output is :-

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

for Loop

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for(initialization; Boolean_expression; update){
   //Statements
}

The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears
  • Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
  • After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
  • The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.


The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output
class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }
}

The output of this program is:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.

The three expressions of the for loop are optional; an infinite loop can be created as follows
for ( ; ; ) {
 
    // your code goes here
}

The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:

int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array

class EnhancedForDemo {
    public static void main(String[] args){
         int[] numbers =
             {1,2,3,4,5,6,7,8,9,10};
         for (int item : numbers) {
             System.out.println("Count is: " + item);
         }
    }
}

In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Basic Operators

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

Conditional Operator ( ? : ):

         Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as

variable x = (expression) ? value if true : value if false

Example :-

class BasicOperators{
     public static void main(String[] args) {
         int x = 30;
         int one = ((x==30) ? 10 : 20);
         System.out.println("First "+ one);
       
         int two = ((x < 10) ? 10 : 20);
         System.out.println("Two "+ two);
       
     }
 }

Output is :-
First 10
Two 20



Instance Of Operator 

This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceOf operator is wriiten as

( Object reference variable ) instanceOf  (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is the example:

 class BasicOperators{
     public static void main(String[] args) {
         String Svalue = "Java";
         boolean isString = Svalue instanceof String;
         System.out.println(isString);
     }
 }

Output is true

This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example:



class Vehicle {}

class Car extends Vehicle {
   public static void main(String args[]){
      Vehicle a = new Car();
      boolean result =  a instanceof Car;
      System.out.println( result);
   }
}

Output is true




Basic Operators

The Assignment Operators

There are following assignment operators supported by Java language:

Simple assignment operator ( = )

Simple assignment operator, Assigns values from right side operands to left side operand
Example :-

 class BasicOperators{
     public static void main(String[] args) {
         int x = 0;
         x = 10 + 23;
         System.out.println(x);
     }
 }

Output is 33

Add AND assignment operator ( += )

Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
Example :-

 class BasicOperators{
     public static void main(String[] args) {
         int x = 10;
         x += 13;
         System.out.println(x);
     }
 }

Output is 23

Subtract AND assignment operator ( -= )

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

 class BasicOperators{
     public static void main(String[] args) {
         int x = 10;
         x -= 3;
         System.out.println(x);
     }
 }

Output is 7 

Multiply AND assignment operator ( *= )

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

 class BasicOperators{
     public static void main(String[] args) {
         int x = 10;
         x *= 3;
         System.out.println(x);
     }
 }

Output is 30 

Divide AND assignment operator ( /= )

Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

class BasicOperators{
     public static void main(String[] args) {
         int x = 30;
         x /= 3;
         System.out.println(x);
     }
 }

Output is 10

Modulus AND assignment operator ( %= )

Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

 class BasicOperators{
     public static void main(String[] args) {
         int x = 30;
         x %= 2;
         System.out.println(x);
     }
 }

Output is 0



Basic Operators

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

The Bitwise Operators:

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Convert Number to Binary 




60 ------- 00111100
13 ------- 00001101

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands 60 & 13 = 0000 1100
| Binary OR Operator copies a bit if it exists in either operand 60 | 13 = 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both 60 ^ 13 = 0011 0001
~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. ~a = 1100 0011

The Logical Operators:


Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero,
then the condition becomes true.
(false && true) is false
(true && true) is true
|| Called Logical OR Operator. If any of the two operands are non-zero,
then the condition becomes true.
(false || true) is true
(false || false ) is false
! Called Logical NOT Operator. Use to reverses the logical state of its operand.
If a condition is true then Logical NOT operator will make false.
(!true) is false
(!false) is ture

Monday, October 14, 2013

Basic Operators

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:


  • Arithmetic Operators
  • Relational Operators
  • Bitwise Operators
  • Logical Operators
  • Assignment Operators
  • Misc Operators

The Arithmetic Operators :


Operator Description Example
+ Addition - Adds values on either side of the operator 10 + 10 = 20
- Subtraction - Subtracts right hand operand from left hand operand 20 - 10 = 10
* Multiplication - Multiplies values on either side of the operator 2 * 2 = 4
/ Division - Divides left hand operand by right hand operand 10 / 2 = 5
% Modulus - Divides left hand operand by right hand operand and
returns remainder
10 % 2 = 0
++ Increment - Increases the value of operand by 1 1++ Given 2
-- Decrement - Decreases the value of operand by 1 2-- Given 1

The Relational Operators:

There are following relational operators supported by Java language




Operator Description Example
== Checks if the values of two operands are equal or not, if yes then
condition becomes true.
10 == 10 is true
10 == 20 is false
!= Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true
10 != 10 is false
10 != 20 is true
> Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true.
2 > 1 is true
4 > 2 is false
< Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.
10 < 2 is false
2 < 10 is true
>= Checks if the value of left operand is greater than or equal to the value of right operand,
if yes then condition becomes true.
10>=10 is true
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then
condition becomes true.
10<=10 is true