Pages

Control Statements in java

           The control statement are used to controll the flow of execution of the program .
This execution order depends on the supplied data values and the conditional logic.
Java contains the following types of control statements. .

1- Selection Statements:
               Selection statements allow your program to choose different paths of
 execution based upon the outcome of an expression or the state of a variable Java
supports two selection statements, "if and switch".
   a: If Statement:
          It can be used to route program execution through two different paths.
          This is a control statement to execute a single statement or a block of code,
            when the given condition is true and if it is false then it skips if block and rest code of program is executed .
  Syntax:
 if(condition)
  {
<statement1>;
  }
  else
  {
  <statement2>;
  }

              If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed.
Example:
if(a>b)
  {
  System.out.println("a is greater than b");// prints a is greater than b
  }
  else
  {
   System.out.println("b is greater than a");//prints b is greater than a
  }
   if-else-if Ladder
When there are more than two conditions then a common programming construct that is based upon a sequence of nested ifs called if-else-if ladder is used. It looks like this:
 
if(condition)
     <statement>;
   else if(condition)
     <statement>;
   else if(condition)
     <statement>;
       ...
    else
     <statement>;


 b.Switch statement:
       Switch statement provides a better alternative than a large series of if-else-if statements.This is an easier implementation to the if-else statements. The keyword "switch" is followed by an expression that should evaluates to byte, short, char or int primitive data types ,only.
General Syntax:
  
switch (x) {
    case value0:
    doSomething0();
    break;
  case value1:
    doSomething1();
    break;
  case value2:
    doSomething2();
    break;
 case value3:
    doSomething3();
    break;
  case value4:
    doSomething4();
    break;
    ....
    ....
  case valueN:
    doSomethingN();
    break;
  default:
    doSomethingElse();
    }

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. If none of the constants matches the value 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.

2- Looping Statements:
           Looping statements or Iteration statements enable program execution to repeat one or more statements (that is,iteration statements form loops).
a: for loop:
for(initialization; condition; iteration)
{
// body
}

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 the 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 evaluating 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.

b: do-while

 do
 {
 // body of loop
 }
 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

c: while

The while loop is Java’s most fundamental looping statement. It repeats a statement or block while its controlling expression is true. Here is its general form:

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 becomes 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.

3- Branching Statements:
            Branching statements allow your program to execute in a nonlinear fashion. Break, jump and goto are the branching statements used in java.

Datatypes And Arrays

            Java is a strongly typed language. All expressions and parameters are checked by the java compiler to ensure that the types are compatible.
             There are 8 simple datatypes defined by Java. They are byte, short, int, long, char, float, double and boolean.

Integers:
             The datatypes byte, short, int and long is grouped  under integers. All of these datatypes are signed, positive and negative values.

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

short
16
-32,768  to  32,767

byte
8
-128  to  127

Floating point types:
              When evaluating expressions that require fractional precision then floating-point numbers are used. There are two types of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Their width and ranges are shown here:
Name
Width in Bits
Approximate Range
double
64
4.9e–324 to 1.8e+308
float
32
1.4e-045 to 3.4e+038

Characters:
                 char is the datatype used to store characters in java. In Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow applets to be written for worldwide use, it makes sense that it would use Unicode to represent characters.

Booleans:
             The simple datatype used for logical values is boolean. It can have only one of two possible values, true or false. This is the type returned by all relational operators, such as a < b. boolean is also the type required by the conditional expressions that govern the control statements such as if and for.


Arrays:
             An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information.

One-Dimensional Arrays
     A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must create an array variable of the desired type. The general form of a one-dimensional array declaration is
type var-name[ ];
Here, type declares the base type of the array. The base type determines the data type of each element that comprises the array. Thus, the base type for the array determines what type of data the array will hold.
            For example, the following declares an array named month_days with the type “array of int”:
int month_days[];
Although this declaration establishes the fact that month_days is an array variable, no array actually exists. In fact, the value of month_days is set to null, which represents an array with no value. To link month_days with an actual, physical array of integers, you must allocate one using new and assign it to month_days. new is a special operator that allocates memory.
  The general form of new as it applies to one-dimensional arrays appears
as follows:
array-var = new type[size];
Here, type specifies the type of data being allocated, size specifies the number of elements in
the array, and array-var is the array variable that is linked to the array. That is, to use new to
allocate an array, you must specify the type and number of elements to allocate. The elements in the array allocated by new will automatically be initialized to zero. This example allocates a 12-element array of integers and links them to month_days.
month_days = new int[12];
After this statement executes, month_days will refer to an array of 12 integers. Further, all elements in the array will be initialized to zero.
Let’s review:
                Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated.
     Once you have allocated an array, you can access a specific element in the array by specifying its index within square brackets. All array indexes start at zero.
For example, this statement assigns the value 28 to the second element of month_days.
month_days[1] = 28;
The next line displays the value stored at index 3.
System.out.println(month_days[3]);
Putting together all the pieces, here is a program that creates an array of the number
of days in each month.
// Demonstrate a one-dimensional array.
class Array
{
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}

When you run this program, it prints the number of days in April. As mentioned, Java array indexes start with zero, so the number of days in April is month_days[3] or 30. It is possible to combine the declaration of the array variable with the allocation of the array itself, as shown here:
int month_days[] = new int[12];
This is the way that you will normally see it done in professionally written Java programs. Arrays can be initialized when they are declared. The process is much the same as that used to initialize the simple types. An array initializer is a list of comma-separated expressions surrounded by curly braces. The commas separate the values of the array elements. The array will automatically be created large enough to hold the number of elements you specify in the array initializer. There is no need to use new.
            For example, to store the number of days in each month, the following code creates an initialized array of integers:
// An improved version of the previous program.
class AutoArray
 {
public static void main(String args[])
{
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

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



OOP concepts

                                    Java is an object oriented programming language. Object-oriented programming is at the core of Java. Object Oriented Programming or OOP is the technique to create programs based on the real world. All java programs are object oriented.
          To understand the functionality of OOP in Java, we first need to understand several fundamentals related to objects. These include class, method, inheritance, encapsulation, abstraction and polymorphism.
  • Classes and Objects:
               A class is a blueprint for an object, and that nearly everything in java is an object. All java code is defined in a class. A class describes how to make an object of that class type. Class is the central point of OOP and that contains data and codes with behavior. The class definition describes all the properties, behavior, and identity of objects present within that class. In Java everything happens within class and it describes a set of objects with common behavior.
             Objects are the basic unit with identity and behavior, and object can take care of itself; you don’t have to know or care how the object does it. An object knows things and does things. Things an object knows about itself are called instance variables. They represent the state of an object Things an object does are called methods. They represent the behavior of an object.

  • Abstraction:
              An abstraction is an essential element of object-oriented programming. An abstraction is the way of converting real world objects in terms of class. The process of abstraction in Java is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface). For example creating a class Vehicle and injecting properties into it.
Example:
public class Vehicle {
public String colour;
public String model;
}

  • Encapsulation:
               Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. This is an important programming concept that assists in separating an object's state from its behavior. This helps in hiding an object's data describing its state from any further modification by external component. In Java there are four different terms used for hiding data constructs and these are public, private, protected and package. One way to think about encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper.

  • Inheritance:
              The process by which one object acquires the properties of another object is known as inheritance. Inheritance is the property which allows a Child class to inherit some properties from its parent class. In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class. Though objects are distinguished from each other by some additional features but there are objects that share certain things common. In object oriented programming classes can inherit some common behavior and state from others. Inheritance in OOP allows to define a general class and later to organize some other classes simply adding some details with the old class definition. This saves work as the special class inherits all the properties of the old general class and as a programmer you only require the new features. This helps in a better data analysis, accurate coding and reduces development time. 
  • Polymorphism:
               Polymorphism (many forms) is a feature that allows one interface to be used for a general class of actions. It describes the ability of the object in belonging to different types with specific behavior of each type. So by using this, one object can be treated like another and in this way it can create and define multiple level of interface. Here the programmers need not have to know the exact type of object in advance and this is being implemented at runtime. Polymorphism gives us the ultimate flexibility in extensibility. The ability to define more than one function with the same name is called Polymorphism. In java, there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class.
Overloading occurs when several methods have same names with
  • Overloading is determined at the compile time.
  • Different method signature and different number or type of parameters.
  • Same method signature but different number of parameters.
Same method signature and same number of parameters but of different type.