Switch Statement

Switch Statement :

Java has a built in multiway decision making statement known as switch. The switch statement tests the value of a given variable or expression against a list of case values and when a match is found , a block of statements associated with that case is executed.

 

Program illustration of switch statement

Class cityguide

{

Public static void main( String args[])

{

Char choice;

System.out.println(“Select your choice “);

System.out.println(“M for MAdras “);

System.out.println(“B for Bomday “);

System.out.println(“C for Calcutta “);

System.out.println(“ Choice “);

System.out.flush();

Try

{

Switch( choice = ( char) system.in.read())

{

Case ‘M’:

Case m: system.out.println( “Madras” );

Break;

Case B;

Case b: system.out.println( “ Bombday”);

Break;

Case C:

Case c: system.out.println(“ Calcutta “);

Break;

Default: system.out.println( “ Invalid Choice “);

}

}

Catch ( exception e )

{

System.out.println(“ I / O Error “);

}

}

}

 

The ? : operator

This operator is a combination of ?and : and takes three operands.This operator is known as the conditional operator.

The general form of the use of the conditional statement is as follows :

Condition1 expression ?expression1 : expression2

 

The conditional operation is evaluated first. If the result is true expression 1 is evaluated and is returned as the value of conditional expression. Otherwise expression 2 is evaluated and its value is returned.

For example :

If ( x> 0 )

Flag = 0;

Else

Flag = 1;

Can be written as

Flag = (x<0) ?0 : 1

Evaluation of another example :

Y = 1.5x + 3 ; for x <=2

Y = 2x + 3 ; for x > 2

This can be evaluated using conditional operator as follows :

Y = (x – 2) ?( 2 x + 5 ) : ( 1.5x + 3 )

Leave Comment

Important Topics

Title
OOPS
Data Types
JAVA
JVM
Command Line Args
Machine Neutral
Scope of Variables
Operators :
Generic Type Casting
IF Else
Switch Statement
The while statement
The do statement
The for statement
Classes, objects and methods
Constructors
Methods Overloading
Static Members
Nesting of methods
Inheritance : Extending a Class
Overriding methods
Overriding methods
Final variable and methods
Abstract class in Java
Visibility control
Questions
Functional interfaces
Lambda functions
Method References in Java
Collections in Java
Java Spring
Java SpringBoot
Java SpringBoot
Spring Dependency Injection
Spring Inversion of Control
AOP
JavaBeans
Stream API