JAVA
Download
1 / 46

JAVA - PowerPoint PPT Presentation


  • 113 Views
  • Uploaded on

JAVA. Control Statement. 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. We discus these topics in detail in next two topics.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' JAVA' - alma


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

JAVA

Control Statement


Java s selection statements
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.

  • We discus these topics in detail in next two topics.

  • Before going further let us know something about Scanner class of java.


Scanner
Scanner

  • Let us start with one simple program for Scanner class.

    import java.util.Scanner;

    public class ScannerDemo

    {

        public static void main(String[] args)

        {

            Scanner s = new Scanner(System.in); // Here we initialize object s for Scanner class.  

    System.out.print("Enter the first value a : ");

    int a = s.nextInt();    // Scan int type value

    System.out.print("Enter the second value b : ");

    int b = s.nextInt();    // Scan int type value

    int sum = a + b;

    System.out.println("The addition of a and b : a + b = "+sum);

        }

    }


  • Here we import java.uti.Scanner because the Scanner class is inside util package of java library.

  • Than we create reference (object) of class Scanner named s.

  • "System.in" This is the predefined library which allow user to enter value in any variable at run time through keyboard. We can say same as scanf() in c and cin >> in c++.

  • Now in Scanner class there are so many different different methods for scanning different type of values.


  • For Ex. in our program we use nextInt() method for scanning int type value.

  • Here are some in-built methods of  Scanner class for scanning different types of values.

    1. nextByte()  for scanning byte type value.

    2. nextShort()  for scanning short type value.

    3. nextInt() for scanning int type value.

    4. nextLong() for scanning long type value.

    5. nextFloat() for scanning floting point value.

    6. nextDouble() for scanning double type value.

    7. next() for scanning a string.


If else if in java
if else if in java:

  • The if statement is Java’s conditional branch statement. It can be used to route program

  • execution through two different paths.

    Syntax :

    if (condition)

    {

         statement1;

    }

  • When the condition is true the Statement within the if is executed. After that execution continues with the next statement after the if statement.

  •  If the condition is false then the statement within the if is not executed and the execution continues with the statement after the if statement.


import java.util.Scanner;

class larger1

{

        public static void main(String args[])

        {

int x1,x2,x3;

int large;

                Scanner s = new Scanner(System.in);

System.out.println("Enter value for x1 : ");

                x1=s.nextInt();

System.out.println("Enter value for x2 : ");


  x2=s.nextInt();

System.out.println("Enter value for x3 : ");

                x3=s.nextInt();

                large = x1;

                if (x2 > large)

                        large = x2;

                if (x3 > large)

                        large = x3;

System.out.println("\n\n\tLargest number = " + large);

        }

}


  • NOTE : The number of statement in if block is only one than parentheses are optional but if its more than one than parentheses are compulsury. And if we enter the same value in x1, x2 and x3 in above program than largest number is x1 because our both condition will be false because here we checked only > not >=. 

    EX.

    if (condition) 

    {

    Statement 1;

    Statement 2; 

    }

  • Same as above, except that here multiple statements are executed if the condition Is true.


If else
if else :

  • Syntax :

    if (condition)

    {

        statement1;

    }

    else

    {

        statement2;

    }

  • The if else work like this: If the condition is true, then statement1 is executed. Otherwise,statement2 is executed. In no case will both statements be executed.


import java.util.Scanner;

class result

{

        public static void main(String args[])

        {

                Scanner s = new Scanner(System.in);

System.out.println("Enter marks : ");

int marks = s.nextInt();

                if (marks<40)

System.out.println("\nThe student has failed .. ");

                else

System.out.println("\nThe student has Passed .. ");

        }

}


If else if ladder
if-else-if Ladder :

  • Syntax :

    if(condition)

      statements;

    else if(condition)

    statemenst;

    else if(condition)

      statements;

    ...

    ...

    else

      statements;


  • The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • If none of the conditions is true, then the final else statement 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.


import one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. java.util.Scanner;

class Day

{

        public static void main(String args[])

        {

                Scanner s = new Scanner(System.in);

System.out.println("Enet day between 0 to 6 Day = ");

int  day = s.nextInt();

                if (day == 0)

                {

System.out.println("\n Sunday");

                }

                else if (day == 1)

                {

System.out.println("\n Monday");

                }

                else if (day == 2)


{ one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

System.out.println("\n Tuesday");

                }

                else if (day == 3)

                {

System.out.println("\n Wednesday");

                }

                else if (day == 4)

                {

System.out.println("\n Thursday");

                }

                else if (day == 5)

                {

System.out.println("\n Friday");

                }

                else

                {

System.out.println("\n Saturday");

                }

        }

}


Nested if
Nested if one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • A nested if is an if statement that is the target of another if or else. 

  • Nested ifs are very common in programming.

  • Syntax :

    if(condition)

    {

         if(condition)

             statements....

         else

             statements....

    }

    else

    {

          if(condition)

             statements....

         else

             statements....

    }


import one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. java.util.Scanner;

class MaxValue

{

        public static void main(String args[])

        {

inta,b,c;

int max=0;

                Scanner s = new Scanner(System.in);

System.out.println("Enter value for a : ");

                a=s.nextInt();

System.out.println("Enter value for b : ");

                b=s.nextInt();

System.out.println("Enter value for c : ");

                c=s.nextInt();


 if (a>b) one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

                {

                        if(a>c)

                           max=a;

                        else        //This else is associate with this if(a>c)

                           max=c;

                }

                else               //This else is associate with this if(a>b)

                {

                        if(b>c)

                           max=b;

                        else        //This else is associate with this if(b>c)

                           max=c;  

                }

System.out.println("\n max value = " +max);

        }

}


Switch
switch : one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • The switch statement is Java’s multi way branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.

  • It is difficult to understand large number of if else..if statements. So we have switch statement. 

  • Syntax :

    switch (expression) 

    {

    case value 1: 

    statement 1 ; break; 

    case value 2: 

    statement 2 ; break;  

    ...

    ...

    case value N: 

    statement N ; break;

    default: 

    statements ; break; 

    }


  • The expression must be of type byte, short, one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. int, or char; each of the values specified in the case statements must be of a type compatible with the expression.

  • Each case value must be a unique literal (constant, not a variable). Duplicate case values are not allowed.

  • The value of the expression is compared with each ‘case’ values. If a match is found, the corresponding statement or statements are executed.

  • If no match is found, statement or statements in the default case are executed. Default statement is optional.

  • If default statement is absent, then if no matches are found, then the switch statement completes without doing anything.

  • The break statement is used inside the switch to terminate a statement sequence.

  • NOTE : We will study break statement in further chapter.


import one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. java.util.Scanner;

public class Calci

{

    public static void main(String[] args)

    {

inta,b,ch;

    double ans;

    Scanner s = new Scanner(System.in);

System.out.print("Enter a : ");

    a=s.nextInt();

System.out.print("Enter b : ");

    b=s.nextInt();

System.out.println("Enter 1 for addition");

System.out.println("Enter 2 for subtraction");

System.out.println("Enter 3 for multiplication");

System.out.println("Enter 4 for division");

System.out.print("Enter your choice : ");

ch=s.nextInt();


switch( one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. ch)

    {

        case 1:

ans=a+b;

System.out.println("a + b = " + ans);

        break;

        case 2:

ans=a-b;

System.out.println("a - b = " + ans);

        break;


 case 3: one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

ans=a*b;

System.out.println("a * b = " + ans);

        break;

        case 4:

ans=a/b;

System.out.println("a / b = " + ans);

        break;

        default:

System.out.println("Enter correct choice");

    }

    }

}


Looping statements
Looping statements one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • Java’s repetition (iteration) statements are for, while, and do-while. These statements create what we commonly call loops.

  • As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met.


for : one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • The for loop repeats a set of statements a certain number of times until a condition is matched.

  • It is commonly used for simple iteration. The for loop appears as shown below.

  • Syntax :

    for (initialization; condition; expression)

    {

            Set of statements;

    }


  • In the first part a variable is initialized to a value. one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • The second part consists of a test condition that returns only a Boolean value. The last part is an expression, evaluated every time the loop is executed.

  • The following example depicts the usage of the for loop.


Example for loop
Example for loop one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

class for1

{

        public static void main(String args[])

        {

int i;

                for (i=0;i<10;i++)

                {

System.out.println("\nExample of for loop ");

                }

        }

}


While
while one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • The while loop executes a set of code repeatedly until the condition returns false.

  • Syntax :

    while (condition)

    {

          body(statements) of the loop

    }

  • Where <condition> is the condition to be tested. If the condition returns true then the statements inside the <body of the loop> are executed.

  • Else, the loop is not executed.


class while1 one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

{

        public static void main(String args[])

        {

int i=1;

                while(i<=10)

                {

System.out.println("\n" + i);

                        i++;

                }

        }

}


Do while
do while : one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • The do while loop is similar to the while loop except that the condition to be evaluated is given at the end.

  • Hence the loop is executed at least once even when the condition is false.

  • Syntax :

    do

    {

          body of the loop

    } while (condition);


Do while cont
Do while ( one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. cont…)

  • In do while loop semicolon(;) is compulsory after while.

  • NOTE :  for and while loops are entry control loop because here conditions are checked at entry time of loop but do while loop is exit control loop because the condition is checked at exit time.


class dowhile1 one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

{

        public static void main(String args[])

        {

int i = 1;

int sum = 0;

                do

                {

                        sum = sum + i;

                        i++;

                }while (i<=10);

System.out.println("\n\n\tThe sum of 1 to 10 is .. " + sum);

        }

}


  • NOTE :  one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does.

  • => We can use comma operator inside for loop to declare more than one variable inside loop.

    class Sample

    {

           public static void main(String args[])

           {

    int a, b;

                for(a=1,b = 4;a < b;a++,b--)

                {

    System.out.println("a = " + a);

    System.out.println("b = " + b);

                }

           }

    }


  • NOTE :  one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. The actual syntax of for loop is " for( ; ; ) ". It means we can use or access every for loop which contain two semicolon (;) inside round braces of for loop.

  • EX.

    for( ; ; )

    {

        // ...

    }


Nested loops
Nested loops :  one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another.

  • It can help you to scan and print multi dimensional array as well as in so many other application or program.


class Nested one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

{

        public static void main(String args[])

        {

int i, j;

                for(i=0; i<10; i++)

                {

                        for(j=i; j<10; j++)

                        {

System.out.print(".");

                        }

System.out.println();

                }

        }

}


Jump statements
Jump Statements one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • Java supports three jump statements: break,continue, and return. These statements transfer control to another part of your program.

  • 1. break.

  • 2. continue.

  • 3. return.


The break statement
The break statement one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. 

  • This statement is used to jump out of a loop.

  • Break statement was previously used in switch – case statements.

  • On encountering a break statement within a loop, the execution continues with the  next statement outside the loop.

  • The remaining statements which are after the break and within the loop are skipped.


  • Break statement can also be used with the label of a statement.

  • A statement can be labeled as follows.           

  • statementName : SomeJavaStatement

  • When we use break statement along with label as

    break statementName;

  • The execution continues with the statement having the label. This is equivalent to a goto statement of c and c++..


An example of break statement
An example of break statement statement.

class break1

{

        public static void main(String args[])

        {

int i = 1;

                while (i<=10)

                {

System.out.println("\n" + i);

                        i++;

                        if (i==5)

                        {

                                break;

                        }

                }

        }

}


An example of break to a label
An example of break to a label statement.

class break3

{

        public static void main (String args[])

        {

boolean t=true;

                a:

                {

                        b:

                        {

                                c:

                                {

System.out.println("Before the break");

                                        if(t)

                                                break b;

System.out.println("This will not execute");

                                }

System.out.println("This will not execute");

                        }

System.out.println("This is after b");

                }

        }

}


Continue statement
Continue statement statement.

  • This statement is used only within looping statements.

  • When the continue statement is encountered, the next iteration starts.

  •  The remaining statements in the loop are skipped. The execution starts from the top of loop again.


class continue1 statement.

{

        public static void main(String args[])

        {

                for (int i=1; i<1=0; i++)

                {

                        if (i%2 == 0)

                                continue;

System.out.println("\n" + i);

                }

        }

}


The return statement
The return statement statement.

  • The last control statement is return. The return statement is used to explicitly return from a method.

  • That is, it causes program control to transfer back to the caller of the method.

  • the return statement immediately terminates the method in which it is executed.


class Return1 statement.

{

       public static void main(String args[])

      {

boolean t = true;

System.out.println("Before the return.");

            if(t)

                return;       // return to caller

System.out.println("This won't execute.");

     }

}


  • NOTE :  statement.the if(t) statement is necessary. Without it, the Java compiler would flag an “unreachable code” error, because the compiler would know that the last println( ) statement would never be executed. To prevent this error, the if statement is used here to trick the compiler for the sake of this demonstration.


ad