2/25/2023 0 Comments Java switch![]() ![]() The switch statement executes the case corresponding to the value of the expression. Thus, it must be a constant and not a variable. Each case value must be a unique literal. The expression must be of type int, char, byte, or short. The switch keyword is followed by an integer expression enclosed in parentheses. The figure below shows the syntax of switch-case statement. The switch-case statement is used when a variable needs to be compared against different values. ![]() ![]() The use of the switch-case statement results in better performance. To avoid this, the switch-case approach can be used as an alternative for multiple selections. The following is the syntax of if-else-if construct.Ī program is difficult to comprehend, when there are too many if statements representing multiple selection constructs. When a true condition is found, the statement associated with the true condition is executed. The conditions are evaluated sequentially starting from the top of the ladder and moving downwards. The multiple if construct is known as the if-else-if ladder. The inner else refers to if(num % 5 = 0), because it is closest to the inner if within the same block. Here, the final else is associated with if(num % 3 = 0). Then, using nested-if statements, it checks whether num is divisible by 3 and 5 or only by 3, and then prints an appropriate statement. Here, code declares a variable num and stores an integer value accepted from the user. ("The number is not divisible by 3 and 5.") Message is displayed if number is not divisible by 3 and 5 ("The number is divisible by 3 but not by 5.") Message is displayed if number is divisible by 3 but not by 5 ("The number is divisible by both 3 and 5.") Message is displayed if number is divisible by both 3 and 5 ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |