Java | Decision making statements

05 min read

Decision Making:

If, Switch are the decision-making statements used in java will be seen in detail below,

The expression in the switch can also be of type String. But using strings in the switch is expensive. If we need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-else's. This is because it knows that the case constants are all same type and simply must be compared for equality with the switch expression. The compiler has no such knowledge of a long list of 'if' expressions.

Example:

Write a program to read the slot name in which the student has registered for Java and display whether his class will be in the morning or afternoon.

importjava.util.*;
public class classtiming
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a slot:");
switch(slot)
{
case "c1" :
System.out.println("Your class is in morning");
break;
case "c2" :
System.out.println("Your class in the afternoon");
break;
default:
System.out.println("Enter the slot registered for Java");
break;
}
}
}

'for' loop:

  • simple for
  • Enhanced for (or) for-each loop

goto:

Although a reserved keyword in Java, it is not supported as it is hard to understand and maintain and also prohibits compiler optimizations.

break:

Provides a 'civilized' form to goto. However, it cannot be used to exit from a deeply nested loop set, unlike 'goto'.

Labeled break:

Can be used to break out of one or more blocks of code.

Syntax: break label; //a name that identifies a block of code.

The labeled block must enclose the break statement, but it need not be the immediately enclosing block.

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error