Decision Making Statement In Java

When a program breaks the sequential flow and jumps to another part of the code, it is called selection or branching.

When the branching is based on a particular condition, it is known as conditional branching.

If branching takes place without any condition, it is known as unconditional branching.

 

DECISION MAKING WITH IF STATEMENT:

An if statement tests a particular condition; if the condition evaluates to true , a course of action is followed i.e a statement or set of statements is executed . Otherwise (if the condition evaluates to false) ,the course-of-action is ignored.

The if statement may be implemented in different forms depending on the complexity of conditions to be tested.

  • Simple if statement
  • if….else statement
  • Nested if….else statement
  • else if ladder

 IF STATEMENT:

The syntax of the if statement is shown below:

if(expression)

statements;

 

Where a statement may consist of a single statement , a compound statement, or nothing. The expression must be enclosed in paranthesis. If the expression evaluates to true, the statement is executed, otherwise ignored.

Flow Chart Is given As Below:-

 

 

 

For example:-

a=20;

b=10;

if(a>b)

{

           System.out.println(“Largest Value is=”+a);

}

If the given condition is true,then the computer will print the message Largest value is=20 and if not,it will simply skip this statement.

 

IF….ELSE STATEMENT:

This form of if allows either-or condition by providing an else condition block. The syntax of the if-else statement is the following:

 

if(expression)

{

  statement-1;

}

else

{

  statement-2;

}

 

If the expression evaluates to true i.e., a non-zero value, the statement-1 is executed, otherwise statement-2 is executed. The statement-1 and statement-2 can be a single statement, or a compound statement, or a null statement.

 

This statement works in the following manner:-

 

           

The example is given as below:-

……………….

……………….

if(code==1)

boy=boy+1;

else

girl=girl+1;

X X X X X

……………

In this example,if the code is equal to 1,the statement boy=boy+1; is executed and the control is transferred to the statement xxxxx,after skipping the else part.if the code is not equal to 1,the statement boy=boy+1; is skipped and the statement in the else part girl=girl+1; is executed before the control reached the statement xxxxx.

 

NESTED IF….ELSE STATEMENT:

 

A Nested if is an if that has another if in it’s ‘if’s’ body or in it’s else’s body. The nested if can have one of the

following three forms:

1.    if(expression1)

        {

          if(expression2)

           statement-1;

         else

           statement-2;

        }

      else

         body of else;

 

2.     if(expression1)

        body-of-if;

       else 

       {

          if(expression2)

           statement-1;

         else

           statement-2;

        }

 

3.      if(expression1)

        {

          if(expression2)

           statement-1;

         else

           statement-2;

        }

      else

     {

       if(expression3)

           statement-3;

      else

         statement-4;

 } 

Program For Nesting If-else Statements:-

class Ifelsetesting

{

        public static void main(String args[])

        {

              int a=325,b=712,c=478;

              System.out.println(“Largest value is:”);

if(a>b)

{

if(a>c)

{

     System.out.println(a);

}

else

{

System.out.println(c);

}

}

else

{

if(c>b)

{

System.out.println(c);

}

else

{

System.out.println(b);

}

}

}

}

 

 

THE ELSE-IF LADDER:

A common programming construct in the java is the if-else-if ladder , which is often also called the if-else-if staircase because of it’s appearence.

 

It takes the following general form:

if(expression1) 

        statement1;

  else

      if(expression2) 

          statement2;

  else 

      if(expression3) 

          statement3;

   :

   else 

          statement n;

 

The expressions are evaluated from top downward. As soon as expression evaluates to true , the statement associated with it is executed and the rest of the ladder is bypassed. If none of the expression are true, the final else gets executed. If the final else is missing , no action takes place if all other conditions are false.

 

            

 

 

Advertisements

Switch Statement In Java

THE SWITCH STATEMENT:

Java provides a multiple branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed.

The general form of switch is:

switch(expression)

{

case 1:

   segment 1

case 2:

   segment 2

   …

case n:

   segment n

default:

   default segment

}

 

A switch statement is used for multiple way selection that will branch to different code segments based on the value of a variable or an expression . The optional default label is used to specify the code segment to be executed when the value of the variable or expression does not match with any of the case values. if there is no break statement as the last statement in the code segment for a certain case, the execution will continue on into the code segment for the next case clause without checking the case value.

 

NESTED SWITCH:

We can use switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines in its own block, no conflicts arise between the case statements in the inner switch and those in the outer switch.

 

switch(count)

{

   case 1:

   switch(target)

   {

       case 0:

       System.out.println(“target is zero”);

       break;

       case 1:

       System.out.println(“target is one”);

       break;

   }

break;

    case2: //. . .

 

Here the case 1: statement is inner switch does not conflict with the case 1: statement in the outer switch. The count variable is only compared with the list of cases at the outer level. if the count is 1 , then target is compared with the inner list cases.

While Statement in Java

The simplest of all the looping structures in java is the while statement.The basic format of the while statement is:-

Initialisation:

while(test condition)

{

       body of the loop

}

      The while loop is an entry -controlled loop statement.The test condition is evaluated and if the condition is true ,then the body of the loop is executed.After execution of the body,the test condition is once again evaluated an if it is true,the body is executed once again.This process of execution of the body of the body continues until the test condition becomes false and the control is transferred out of the loop.On exit,the program continues with the statement immediately after the body of the loop. The body of the loop may have one more statements.

Consider the following example:-

 

………………..

………………..

sum=0;n=1;while(n<=10)

{

          sum=sum+n*n;

           n=n+1;

}

 

System.out.println(“Sum=”+sum);

………………

……………..

The body of the loop is executed 10 times for n=1,2,3…..,10 each time adding the square of the value of n,which is incremented inside the loop.The test condition may also be written as n<11;the result would be the same.

Do-While Loop In Java

The While loop test condition before the loop is executed.Therefore,the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. On some occasions it might be necessary to execute the body of the loop before the test is performed.Such situation can be handled with the help of the do statement.Unlike the while loop, the do-while is an exit-controlled loop i.e it evaluates its text-expression at the bottom of the loop after executing it’s loop-body statements. This means that a do-while loop always executes at least once. The syntax of the do-while loop is:

    do

    {

         loop-body;

     }

while(condition);

 

Example:

 ……………………

……………………

i=1;

sum=0;

do

{

              i=i+2;

}

while(sum<40 || i<10);

………………………..

……………………….

 

the loop will be executed as long as one of the two relations is true.

 

Sample Program:-

 

class DoWhileTest

{

     public static void main(String args[])

     {

           int row,column,y;

           System.out.println(“Multiplication Table:”);

            row=1;

            do

            {

                     column=1;

                      do

                     {

                               y=row*column;

                              System.out.println(” “+y);

                             column=column+1;

                       }

                       while(column<=3);

                       System.out.println(“\n”);

                       row=row+1;

              }

              while(row<=3);

       }

}

For Loop

The for loop is another entry-controlled loop that provides a more concise loop structure.The for loop is the easiest to understand of the java loops.The Syntax of the for loop statement is:

 

for( initialization expression(s); test condition; update expression)

{

   loop-body;

}

The execution of the for  statement is as follows:

1.)Initialization of the control  variables is done first,using assignment statements such as i=1 and count=0.The variables are known as loop-control variables.

2.) the value of the control variable is tested using the test-condition.The test condition is a relational expression,such as  i<10 that determines  when the loop will exit.If the condition is true,the body of the loop is executed ,otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.

3.)When the body of the loop is executed,the control is transferred back to the for statement after evaluating the last statement such as i=i+1 and the new value of the control variable is again  tested to see whether it satisfies the loop condition.if the condition is satisfied,the body of the loop is again executed.This process continues till the value of the control variable fails to satisfy the test condition

This can be understood by the following figure:-

 

   

 

Java Tokens

Java Tokens:-

A Java program is a collection of tokens, comments and white spaces. There are five types of tokens included in java language. They are:

 

  • Reserved keywords
  • Identifiers
  • Literals
  • Operators
  • Seprators

 

Java Character Set:

Characters used to write java tokens are the smallest units of java language. These characters are defined by the uni-code character set, an emerging standard that tries to create characters for a large number of scripts world wide. The uni-code is a 16  bit character coding system.

 

Keywords:

Keywords implement specific features of the language. There are 60 reserved keywords defined in the java language. These keywords combined with the syntax of the operators and separators, from the definition of the java language. These keywords cannot be used as names for a variable, class or method.

 

Identifiers:

Identifiers are used for class names, method names, and variable names. An identifier may beb any sequence of uppercase and lowercase letters,numbers, or the underscore and dollar-sign characters. They must not begin with a number.

Again java is case sensitive , so First is different from first. Some examples of valid identifiers are:

avg            temp              b5                count              ptest              this_is_fine

 

Invalid variable names include:

 

2count            high-temp            Not/fine

 

Literals:

A constant value in java is created by using a literal representation of it. Literals can be digits, letters, and other characters. Major five types of literals in java are:

 

  • Integer literals
  • Floating-point literals
  • Character literals
  • String literals
  • Boolean literals

 

Each of them has a type associated with it. The type describes how the values behave and how they are stored. Example of some literals are given below:

10098.6          ‘Y’             “This is an answer”

A literal can be used anywhere a value of it’s type is allowed.

 

Separators:

In java, there are a few characters that are used as separators . Semicolon(;) is the most commonly used separator in java. It is used to terminate statements. The separators are shown below:

 

 

Operators:

Java supports a rich set of operators.An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.Operators are used in programs to manipulate data and variables.They usually form a part of mathematical or logical expressions.Java operators can be classified into a number of related categories as given below:-

  1. Arithmetic Operators :- +,-,*,/,%
  2. Relational Operators:-<,<=,>,>=,= =,!=
  3. Logical Operators:- &&,||,!
  4. Assignment Operators:- =
  5. Increment & Decrement Operators:- ++,–
  6. Conditional Operators:- ?:
  7. Bitwise Operators:- &,!,^,~,<<,>>,>>>
  8. Special operators:- Instanceof,Dot Operator
 

Downloading The Java Compiler

In order to get a Java development environment set up on your machine you will have to complete the following steps:

 

  • Download a large file containing the Java development environment (the compiler and other tools).
  • Download a large file containing the Java documentation.
  • If you do not already have WinZip (or an equivalent) on your machine, you will need to download a large file containing WinZip and install it.
  • Install the Java development environment.
  • Install the documentation.
  • Adjust several environment variables.
  • Test everything out.

Before getting started, it would make things easier if you create a new directory in your temp directory to hold the files we are about to download. We will call this the download directory.

 

Step 1 – Download the Java development environment

Go to the page http://java.sun.com/j2se/1.4.2/download.html. Download the SDK software by clicking on the “Download J2SE SDK” link. You will be shown a licensing agreement. Click Accept. Select your operating system and download the file to your download directory. This is a huge file, and it will take several hours to download over a normal phone-line modem. The next two files are also large.

Step 2 – Download the Java documentation

Download the documentation by selecting your operating system and clicking the SDK 1.4.1 documentation link.

Step 3 – Download and install WinZip

If you do not have a version of WinZip or an equivalent on your machine, go to the page http://www.winzip.com/ and download an evaluation copy of WinZip. Run the EXE you get to install it. We will use it in a moment to install the documentation.

Step 4 – Install the development kit

Run the j2sdk-1_4_1-*.exe file that you downloaded in step 1. It will unpack and install the development kit automatically.

Step 5 – Install the documentation

Read the installation instructions for the documentation. They will instruct you to move the documentation file to same directory as that containing the development kit you just installed. Unzip the documentation and it will drop into the proper place.

Step 6 – Adjust your environment

 

Windows 8

  • Drag the Mouse pointer to the Right bottom corner of the screen
  • Click on the Search icon and type: Control Panel
  • Click on -> Control Panel -> System -> Advanced
  • Click on Environment Variables, under System Variables, find PATH, and click on it.
  • In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  • Close the window.
  • Reopen Command prompt window, and run your java code.

 

Windows 7

 

  • Select Computer from the Start menu
  • Choose System Properties from the context menu
  • Click Advanced system settings > Advanced tab
  • Click on Environment Variables, under System Variables, find PATH, and click on it.
  • In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  • Reopen Command prompt window, and run your java code.

 

Windows XP

  • Start -> Control Panel -> System -> Advanced
  • Click on Environment Variables, under System Variables, find PATH, and click on it.
  • In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  • Close the window.
  • Reopen Command prompt window, and run your java code.

 

Windows Vista

 

  • Right click My Computer icon
  • Choose Properties from the context menu
  • Click Advanced tab (Advanced system settings link in Vista)
  • In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  • Reopen Command prompt window, and run your java code.

 

Step 7 – Test

Now you should be able to open another MS-DOS window and type javac. If everything is set up properly, then you should see a two-line blob of text come out that tells you how to use javac. That means you are ready to go. If you see the message “Bad Command or File Name” it means you are not ready to go. Figure out what you did wrong by rereading the installation instructions. Make sure the PATH is set properly and working. Go back and reread the Programmer’s Creed above and be persistent until the problem is resolved.