Sunday 18 March 2012

If Else statement


If statement is very powerful decision making statement and is used to control the flow of execution of statement .
If we want to execute a statement on some condition .  than we should use the if statement
Syntax  :-
If(Condition){
//Statement
}
Example :-
If(a<b){
System.out.println(a is smaller than b);
}
In above example first it check that if a is less than b only if it is true then next statement will be executed  otherwise no statement will be executed.
If statement can be implemented in the following  ways:-
1.       Simple if statement
2.       If else statement
3.       Else if ladder
4.       Nested if else statement

1)      Simple if statement :-
If (condition){
Statement - block - x
}
                Statement –block – y
                In this is if the condition is true  then statement block x will be executed  and then statement block y will be executed, otherwise the statement  block x will be skipped only statement block y will be executed.
Example :
Class SimpleIf{
Public static void main(String args[]){
Int a=10,b=5;
If(a>b){
System.out.println(“a is greater”);
}
System.out.println(“Thanks for coming”);
}
}
Output:
a is greater
Thanks for coming

IF Else statement:-
If(condition)
{
Statement – block -x
}
else
{
Statement – block – y
}
Statement-z
In this if the condition is true then statement block x will be executed and statement block y will be skipped and then statement z will be executed and condition will false then statement block x will be skipped and statement block y will be executed and statement z will be executed.
Nested  if else:-
If(condition 1){
                If(condition 2){
Statement  -1
}
else{
statement - 2
}
}
else{
statement -3
}
In the above example if condition-1 is false then statement -1 and statement-2  will be skipped and only statement -3 will be executed and if the condition -1 will true then condition-2 will be checked and if condition -2 will be true then statement -1 will be executed otherwise statement -2 will be executed.
Example
Int  a=5;
Int b=10;
Int c=15;
If(a>b){
                If(a>c){
System.out.println(“a is greater”);
}
else{
System.out.println(“c is greater”)
}
}
else{
if(b>c){
System.out.println(“b is greater”);
}
else{
System.out.println(“c is greater”);
}

}
Else if ladder:-  If we want to use multiple decision in our program then we have an another option that is else if ladder.
Syntax:
If(condition 1) {
Statement 1
}
                else if(condition 2){
                Statement 2
}
else if(condition 2){
                Statement 2
}
else{
Statement  3
}
In this all the condition is evaluated from top to down which condition is that statement will be executed if all condition will be false then final else statement will be executed.
Example
If(marks>90){
System.out.println(“First division”)
}
                else If(marks>80){
System.out.println(“Second division”)
}
else If(marks>60){
System.out.println(“Third division”)
}
else {
System.out.println(“Pass”)
}
This will end our if statement

Friday 9 March 2012

Loop in java


Looping is used to develop programs which are having some repetitive process. When a particular block of statement have to reapete then loops are used . it makes the programmer job easier , because instead of writing same lines again and again , loop can be used.
 Loop is consist of  two segments one is body and other is exit condition . exit condition is a condition which will end the loop. Means the sequence of statement will reapete until the condition is true.
A looping process have four main steps , which are as follows:
1)      Setting and initialization of a counter
2)      Execution of statements
3)      Test for condition that whether  the condition is true or false
4)      Increment/decrement counter;
Java supports three type of loop statements :
While
Do while
For
While loop:- while loop is an entry-controlled loop statement . at first step the test condition is evaluated , if it is true then the statement is executed and if it is false the exit from loop. After execution of statement again the condition is evaluated and this process is repeated until the condition is true.
Syntax of while
Initialization :
While (test condition){
Body of loop
Increment/decrement
}  
Example of while loop
class whileLoop{
                public static void main(String args[]){
int i=0;
while(i<5){
System.out.println(i);
i++;
}
}
}
Output:
0
 1
2
3
4
Do while loop:-
In while loop first condition is tested then body of loop is executed .In in do while loop first the body of loop is executed and then condition is executed. So the minimum chance of execution of while loop is 0 an the minimum chance of execution of do while loop is 1. Because whether the condition is true or false the statement will be executed atleast for one time.
Syntax of do while loop
Initialization
do
{
Body of loop
}
While(test condition)
We can use nested loop that is loop inside loop according to requirement .
class doWhileLoop{
                public static void main(String args[]){
int row, column, x;
row=1;
do{
column =1;
do{
x=row*column;
column=column+1;
}while(column<=3);
System.out.println();
Row=row+1;
}while(row<=3);
}
}
Output
1    2   3
2    4    6
3   6     9

For loop:-
For loop is most widely used loop and very useful loop .because in for loop initialization , condition and increment/decrement are in a single row.
Syntax of for loop
For(initialization; test condition; increment/decrement){
Body of loop
}

Example of for loop:
public class foorloop {
      public static void main(String[] args) {
            for(int i=1;i<=10;i++){
                  System.out.println("2  * " +i + "=" + 2*i );
            }
      }
}

Output
2  * 1=2
2  * 2=4
2  * 3=6
2  * 4=8
2  * 5=10
2  * 6=12
2  * 7=14
2  * 8=16
2  * 9=18
2  * 10=20

We can use nested loops that is loop inside loop as many as required . There is no limit of nesting loops .

Thursday 8 March 2012

What is jsp


JavaServer Pages (JSP) is a server-side technology that allows developers to create Web-based applications that use Java components.
JavaServer Pages (JSP) technology is technology for delivering dynamic content to web clients in a secure and well-defined way.
Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a little code that handles application logic and a lot more code that handles output formatting. . For these reasons, web application developers turn towards JSP as their preferred servlet environment
The JavaServer Pages specification extends the Java Servlet API to provide web application developers with a robust framework for creating dynamic web content on the server using HTML, and XML templates, and Java code A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the client in a more powerful and flexible manner. Most of a JSP file is plain HTML but it also has, interspersed with it, special JSP tags.

Documents the JSP file, but is not included in the response                                
<%-- comment --%>
No equivalent.
Declares variables or methods valid in the page’s scripting language.
<%! declaration; [ declaration; ]+ ... %>               
<jsp:declaration>
declaration [ declaration; ]+ </jsp:declaration
Contains an expression valid in the page’s scripting language.
<%= expression %> 
<jsp:expression>
expression
</jsp:expression>
Contains a code fragment valid in
the page’s scripting language.. 
<% code fragment %>             
<jsp:expression>
code fragment
</jsp:expression>
To process a JSP file, we need a JSP engine that can be connected with a web server Firstly when a web browser seeks a JSP file through an URL from the web server, the web server recognizes the .jsp file extension in the URL requested by the browser and understands that the requested resource is a JavaServer Page. Then the web server passes the request to the JSP engine. The JSP page is then translated into a Java class, which is then compiled into a servlet.
This translation and compilation phase occurs only when the JSP file is requested for the first time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For each additional request of the JSP page thereafter, the request directly goes to the servlet byte code, which is already in memory. Thus when a request comes for a servlet, an init() method is called when the Servlet is first loaded into the virtual machine, to perform any global initialization that every request of the servlet will need. Then the individual requests are sent to a service() method, where the response is put together. The servlet creates a new thread to run service() method for each request. The request from the browser is converted into a Java object of type HttpServletRequest, which is passed to the Servlet along with an HttpServletResponse object that is used to send the response back to the browser. The servlet code performs the operations specified by the JSP elements in the .jsp file.
Example of a jsp file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
      <form action="abc">
<%    int a=2;
      int b=3;
            if(a<3){
            out.print(a);
            }
            else{
                  out.print(b);
            }
%>
      </form>
</body>
</html>

Sunday 4 March 2012

Exception handling in java


An exception is a condition that is caused by a run-time error . when java interpreter encounter an error such as dividing an integer  by zero, then it creates an exception and throw it informs us that error has occurred. If that exception is not handled or caught , the interpreter will display an error message and terminate the program. If we want to avoid this and program to continue with execution of remaining code, then we should try to catch the exception. This is known as exception handling
                The exception handling consist of two segments , one to detect errors and throw exception and the other to catch exceptions and to take appropriate actions.
Some common exceptions that are occurred during the program  listed as follows

1)ArithmeticException
Caused by math errors like division by zero
2)ArrayStoreException
Caused when a program tries to store the wrong type of data in array

ArrayIndexOutOfBoundException
Caused by bad index of array
FileNotFoundException
Caused when attempt to access a file that is not exist
IOException
Caused by general I/O failure
OutOfMemoryException
When not enough memory to allocate a new object
NullPointerException
Caused by referencing a null object
NumberFormatException
Caused when a conversion between strings and number fails


Syntax for Exception handling code
There is try keyword in java that is used for exception handling . All the statement s which are likely to generate an exception put in try block and catch block is define by catch keyword that catches the exception thrown by try block.
Syntax is as follows
try{
statement; // generates an exception
}
catch(Exception_type e)
{
Statement //processes the exception
}
More than one catch statement
It is possible to have more than one catch statements in a program corresponding to single try statement. Example is as follows
class test1{
public static void main(String args[]){
int a[]={2,4};
int b=2;
try{
int  x=a[2]/b-a[1];
}
catch(ArithmeticException e){
System.out.println(“Division by zero”);
}
Catch(ArrayIndexOutOfBoundException e)
{
System.out.println(“Array index error”);
}
Catch(ArrayStoreException e)
{
System.out.println(“Array index error”);
}
Int y=a[1]/a[0];
System.out.println(”y = ”  +y);
}
}
Use of Finally statement
Java supports another statement known as finally for exception handling .  finally  block may be added immediately after the try block or after the last catch block. Defining a finally block is guaranteed to execute statement under the finally block  , regardless of whether or not in exception is thrown.
In the above program we may include the last two statements inside a finally block as shown below.
finally
{
Int y=a[1]/a[0];
System.out.println(”y = ”  +y);
}

Thursday 1 March 2012

Array in java


An array is an group of contiguous or related data items that share a common name. the elements of an array are stored in contiguous memory locations and each individual element can be accessed using one or more indices or subscripts. A subscript or an index is a positive integer value , which indicates the position of an array. Arrays are used when a programmer wants to store multiple data items of the same type into a single list and also wants to access and manipulate individual elements of list.
Types of array
1)           One dimensional arrays
2)            Two dimensional arrays

One dimensional arrays:- A list of items can be given one variable name using only one subscript and such a variable is called a single –subscripted variable or a one-dimensional array.
The syntax for declaring a single-dimensional array is as follows :
data_type array_name[];
after an array is declared , you need to create it by allocating space to it in memory. Arrays are created using new operator.
Array_name=new data_type[size];

Example of array One dimensional arrays:-
int marks[];
marks= new int[5];
For example if we want to represent a set of five numbers, say (20,22,26,85,77) by an array variable number, then we may create  the variable number as follows
Int number[]={20,22,26,85,77};
The element will be store as follows
number [0]=20
number [1]=22
number [2]=26
number [3]=85
number [4]=77

Two dimensional arrays:- Two-dimensional arrays are useful when thedata being processed are to be arranged in the form of rows and columns(matrix form)
The syntax for declaring a two-dimensional array is as follows:
                data_type array_name[][];
The syntax for creating a two-dimensional array is as follows:
data_type array_name[row_size][column_size];
For example an array arr [][] of type int having three rows and two columns can be declared and created using this statement
Int arr[][]=new int[3][2];

Initialization of two dimensional array
                Int arr[3][2]={ {101,23},{56,55},{88,63} };
                        The element will be stored in  two dimensional array as follows:
arr[0][0] = 101
arr[0][1]  = 23
arr[1][0]  =56
arr[1][1] = 55
arr[2][0]  =88
arr[2][1] = 63

Wednesday 29 February 2012

What is inheritance


This is always  nice if we could reuse something that already exist rather than creating the same all over again.  This  is done by creating a new classes , reusing the properties of existing ones. This mechanism of deriving a new class from an old one is called inheritance . The old class is known as base class or parent class or super class and new class is known as derived class or child class.
 Inheritance facilitates a class to acquire the properties and functionality of another class . the new class depicts the acquired properties  and behavior of the existing class as well as its own unique properties and behavior.
The syntax to define subclass
 Class sub_class extends super_class
{
//variables and methods declaration
}
Types of inheritance :-
1)      Single inheritance
inheritance in java, single inheritance







class Class1
{
//variables and methods declaration
}
class Class2 extends Class1
{
//variables and methods declaration
}
2)      Hierarchical  inheritance

inheritance in java







class Class1
{
//variables and methods declaration
}
class Class2 extends Class1
{
//variables and methods declaration
}
class Class3 extends Class1
{
 //variables and methods declaration
}
3)      Multilevel Inheritance

inheritance in java







class Class1
{
//variables and methods declaration
}
class Class2 extends Class1
{
//variables and methods declaration
}
class Class3 extends Class2
{
 //variables and methods declaration
}
4)      Multiple Inheritance

inheritance in java

3





class Class1
{
//variables and methods declaration
}
class Class2
{
//variables and methods declaration
}
class Class3 extends Class2 extends Class1

{
 //variables and methods declaration
}

Saturday 18 February 2012

What is recursion

Simply put, recursion is when a function calls itself.
recursion is process, when a method calling itself again and again inside its body .
this is look like a never ending loop.but there is a condition which we check , if it is true then exit.
A method that calls itself is said to be recursive.
The best example of recursion is the computation of the factorial of a number.
The factorial of a number N is the product of all the whole numbers between
1 and N. for example, 3 factorial is 1×2×3, or 6. Here is how a factorial can be computed by use of a recursive method.

class Fact {
int fact(int n){
if (n==1){
return 1;
}
int result;
result= fact(n-1)*n;
return result;
}
}

class DemoClass {
public static void main (String args[]) {
Fact f =new Fact();
System.out.println("Factorial of 3 is " + f.fact(3));
}
}

Output:
Factorial of 3 is 6


in the above example a method fact is defined which is calling itself inside its body.
fact is recursive function .

now in DemoClass we calling fact(3) and execution steps are as follows:

1) first fact will check if 3==1 then return 1.
2) 3!=1, now it will call fact2(3-1)*3 (we are assigning new name fact 2 to fact for understanding)
3) now again fact will check if 2==1 then return .
4) 2!=1, now it will call fact3(2-1)*2 (we are assigning new name fact 3 to fact for understanding)
5) now again fact will check if 1==1 then return .
6) 1==1, now it will return 1 to fact2.
7) now fact2 will return 1*2=2to fact .
8) now fact2 will return 2*3=6 to DemoClass
Related Posts Plugin for WordPress, Blogger...