{"id":16536,"date":"2016-10-23T21:03:31","date_gmt":"2016-10-23T21:03:31","guid":{"rendered":"https:\/\/www.whizlabs.com\/?p=16536"},"modified":"2020-08-31T12:48:17","modified_gmt":"2020-08-31T12:48:17","slug":"ocajp-switch","status":"publish","type":"post","link":"https:\/\/www.whizlabs.com\/blog\/ocajp-switch\/","title":{"rendered":"OCAJP &#8211; How to use a switch statement?"},"content":{"rendered":"<p>This post is about the OCAJP exam objective &#8220;<strong>Use a switch statement<\/strong>&#8220;. You will be mainly tested in the exam about allowed data type variables for switch and Question contains switch statement with compile time errors, you need to correct those errors by selecting the given options.<\/p>\n<p>Here, We would explain each and every important points regarding switch statement. If you have any questions regarding this article, please write it in the comments section.<\/p>\n<blockquote><p><a href=\"https:\/\/www.whizlabs.com\/ocajp-scja\/ocajp8-free-test\/\">TRY NOW : 25 Free OCAJP Mock Exam Questions<\/a><\/p><\/blockquote>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_76 ez-toc-wrap-left counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ea7e02;color:#ea7e02\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ea7e02;color:#ea7e02\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-switch\/#How_to_use_switch_statement\" >How to use switch statement?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-switch\/#Allowed_data_types_for_switch_parameter_value\" >Allowed data types for switch parameter value<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-switch\/#Compile-time_Constant_Values\" >Compile-time Constant Values<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-switch\/#Case_values_should_assignable_to_the_passed_to_the_switch_statement\" >Case values should assignable to the passed to the switch statement<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-switch\/#Fall_through_in_switch_block\" >Fall through in switch block<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.whizlabs.com\/blog\/ocajp-switch\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"How_to_use_switch_statement\"><\/span>How to use switch statement?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Here are the few important points about switch statement in Java.<\/p>\n<ul>\n<li>A switch statement is a complex decision-making structure in which a single value is evaluated and flow is redirected to the first matching branch known as a case statement.<\/li>\n<li>If no such case statement is found that matches the value, an optional default statement will be called.<\/li>\n<li>If no such default option is available, the entire switch statement will be skipped.\n<ul>\n<li>if and if-else statements can used to support both simple and complex decision logic.<\/li>\n<li>In many cases switch statement provides a cleaner way to handle complex decision logic.<\/li>\n<li>Let&#8217;s see an example to understand difference between if-else and switch statements.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>int x=3;\nif(x==1){\n    System.out.println(\"x equals 1\");\n} else if(x==2) {\n    System.out.println(\"x equals 2\");\n}else if(x==3) {\n    System.out.println(\"x equals 3\");\n}else \n{\n    System.out.println(\"Don't know x value\");\n}\n<\/pre>\n<ul>\n<li>The same functionality using switch statement.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>int x=3;\nswitch(x){\n   case 1 :\n      System.out.println(\"x equals 1\");\n      break;\n   case 2 :\n      System.out.println(\"x equals 2\");\n      break;\n   case 3 :\n      System.out.println(\"x equals 3\");\n      break;\n   default :\n      System.out.println(\"Don't know x value\");\n }\n<\/pre>\n<ul>\n<li>The main difference between if-else and switch is &#8221; if-else statement checks each and every condition but switch directly executes the particular condition.<\/li>\n<li>The general form of switch statement is :<\/li>\n<\/ul>\n<pre>switch(expression){\n   case constant1 : code block\n   case constant2 : code block\n   case constant3 : code block\n   .\n   .\n   .\n   default : code block\n}\n<\/pre>\n<ul>\n<li>It may contain zero or more case branches.<\/li>\n<li>Curly braces are mandatory even though there are no statements in the switch.<\/li>\n<li>No need to write case branches in a particular order. You can write in any order.<\/li>\n<li>case branch syntax is important because some may test with invalid syntax.<\/li>\n<li>A switch statement should contain only one default branch.<\/li>\n<li>You can write default branch at any place within switch statement.<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Allowed_data_types_for_switch_parameter_value\"><\/span>Allowed data types for switch parameter value<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<ul>\n<li>You can\u2019t use the switch statement to compare all types of values, such as all types of objects and primitives.<\/li>\n<li>There are limitations on the types of arguments that a switch statement can accept.<\/li>\n<li>A switch statement accepts arguments of type char, byte, short, int, and String(starting from Java version 7).<\/li>\n<li>It also accepts arguments and expressions of types enum, Character, Byte, Integer, and Short, but because these aren\u2019t on the OCAJP exam objectives, We won\u2019t cover them in these article.<\/li>\n<li>The switch statement doesn\u2019t accept arguments of type long, float, double,boolean or any object besides String.<\/li>\n<\/ul>\n<ul>\n<li>The following examples doesn&#8217;t compile because those data types are not allowed by the switch.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Examples :<\/strong><\/span><\/p>\n<pre>long x = 1;\nswitch (x) {\/\/compile time error at this line because long is not allowed.\n\n}\n<\/pre>\n<p>&nbsp;<\/p>\n<pre>float x = 2.0f;\nswitch (x) {\/\/compile time error at this line because float is not allowed.\n\n}\n<\/pre>\n<p>&nbsp;<\/p>\n<pre>double  x = 5.0;\nswitch (x) {\/\/compile time error at this line because double is not allowed.\n\n}\n<\/pre>\n<p>&nbsp;<\/p>\n<pre>boolean  x = true;\nswitch (x) {\/\/compile time error at this line because boolean is not allowed.\n\n}\n<\/pre>\n<p>&nbsp;<\/p>\n<ul>\n<li>Apart from passing a variable to a switch statement, you can also pass an expression to the switch statement as long as it returns one of the allowed types.<\/li>\n<li>The following code is valid:<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre> \nbyte a = 3, x = 6;\nswitch (a+x) {\n\/\/ ..code\n}\n<\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Compile-time_Constant_Values\"><\/span>Compile-time Constant Values<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<ul>\n<li>The values in each case label must be compile-time constant values of the same data type as the switch value<\/li>\n<li>This means you can use only literals, enum constants, or final constant variables of the same data type as case label value.<\/li>\n<li>By final constant, we mean that the variable must be marked with the final modifier and initialized with a literal value in the same expression in which it is declared.<\/li>\n<li>The value of a case label must be a compile-time constant value. That is, the value should be known at the time of code compilation<\/li>\n<li>Remember switch parameter variable value need not be compile-time constant. But case label must be a compile-time constant value.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>int a = 5, b = 12, c = 4;\nswitch (a) {\n    case b + c: \/\/ gives compile time error because it is evaluated at run time. so it is not compile time constant\n    System.out.println(b + c);\n    break;\n    case 2 * 7:\n\tSystem.out.println(\"14\");\n   }\n<\/pre>\n<ul>\n<li>You can use variables in an expression if they\u2019re marked final because the value of final variables can\u2019t change once they\u2019re initialized:<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>final int a = 3;\nfinal int b = 4;\nfinal int c = 5;\nswitch (a) {\n\tcase b + c: \/\/ doesn't gives compile time error because it is evaluated\n\t\/\/ at compile time because all are final variables. so it is compile time constant\n\tSystem.out.println(b + c);\n\tbreak;\n}\n\n<\/pre>\n<ul>\n<li>You may be surprised to learn that if you don\u2019t assign a value to a final variable with its declaration, it isn\u2019t considered a compile-time constant:<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>final int a = 10;\nfinal int b = 20;\nfinal int c;\nc = 30;\nswitch (a) {\n\tcase b + c: \/\/Line 1\n\tSystem.out.println(b + c);\n\tbreak;\n  }\n<\/pre>\n<ul>\n<li>Line1 gives compile time error because it is evaluated at run time.<\/li>\n<li>Because c is a final variable but it is initialized in the next line.So it is evaluated at run time. so the whole expression evaluated at run time.<\/li>\n<li>So it is not compile time constant. It gives compile time error.<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Case_values_should_assignable_to_the_passed_to_the_switch_statement\"><\/span>Case values should assignable to the passed to the switch statement<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<ul>\n<li>Examine the following code, in which the type of argument passed to the switch statement is byte and the case label value is of the type float. Such code won\u2019t compile:<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>byte b = 5;\nswitch (b) {\n  case 4.5: \n  System.out.println(1); \n  break;\n}\n<\/pre>\n<ul>\n<li>Null is not allowed as a case label.<\/li>\n<li>Code that tries to compare the variable passed to the switch statement with null won\u2019t compile, as demonstrated in the following code:<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>String name = \"OCA\";\nswitch (name) {\ncase \"OCA\": \nSystem.out.println(\"OCAJP\");\nbreak;\ncase null: \nSystem.out.println(\"null\");\n}\n<\/pre>\n<ul>\n<li>In switch every case label value should be unique. If more than one case label value is same , you will get compile time error.<\/li>\n<li>See the following code demonstrated this rule. This code won&#8217;t compile.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>int x = 5;\nswitch(x){\n    case 1 :\n\tSystem.out.println(\"Hi\");\n\tbreak;\n    case 1 :\n\tSystem.out.println(\"Hello\");\n }\n\t\t\n<\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Fall_through_in_switch_block\"><\/span>Fall through in switch block<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<ul>\n<li>Once case constant is matched, JVM will executes the associated case branch and subsequent code blocks , if there is no break statement after first matched case.<\/li>\n<li>See the following code demonstrated this rule.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><strong>Example :<\/strong><\/span><\/p>\n<pre>String color = \"green\";\nswitch (color) {\n    case \"red\":\n\tSystem.out.println(\"red\");\n    case \"green\":\n\tSystem.out.println(\"green\");\n    case \"blue\":\n\tSystem.out.println(\"blue\");\n  }\n<\/pre>\n<p>It outputs like :<\/p>\n<pre>green\nblue\n<\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>For OCAJP exam you need to remember all these points about switch statement.You will mainly tested about allowed data types to switch parameter and compile time constant concept, fall through concepts.<\/p>\n<p><strong>If you are interested in practicing more questions, consider our <a href=\"https:\/\/www.whizlabs.com\/ocajp-scja\/ocajp8-practice-tests\/\">650+ mock exam questions for OCAJP certification exam<\/a>.<\/strong><\/p>\n<p><strong>If you are looking for any support or help on <a href=\"https:\/\/www.whizlabs.com\/blog\/how-to-prepare-for-ocajp-8-certification\/\" title=\"How to prepare for OCAJP 8 Certification\">preparing for OCAJP certification exam<\/a>, please contact our support or call us.<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This post is about the OCAJP exam objective &#8220;Use a switch statement&#8220;. You will be mainly tested in the exam about allowed data type variables for switch and Question contains switch statement with compile time errors, you need to correct those errors by selecting the given options. Here, We would explain each and every important points regarding switch statement. If you have any questions regarding this article, please write it in the comments section. TRY NOW : 25 Free OCAJP Mock Exam Questions How to use switch statement? Here are the few important points about switch statement in Java. A [&hellip;]<\/p>\n","protected":false},"author":220,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[13],"tags":[1140],"class_list":["post-16536","post","type-post","status-publish","format-standard","hentry","category-java","tag-ocajp-8-preparation"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"profile_24":false,"profile_48":false,"profile_96":false,"profile_150":false,"profile_300":false,"tptn_thumbnail":false,"web-stories-poster-portrait":false,"web-stories-publisher-logo":false,"web-stories-thumbnail":false},"uagb_author_info":{"display_name":"Aditi Malhotra","author_link":"https:\/\/www.whizlabs.com\/blog\/author\/aditi\/"},"uagb_comment_info":182,"uagb_excerpt":"This post is about the OCAJP exam objective &#8220;Use a switch statement&#8220;. You will be mainly tested in the exam about allowed data type variables for switch and Question contains switch statement with compile time errors, you need to correct those errors by selecting the given options. Here, We would explain each and every important&hellip;","_links":{"self":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/16536","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/users\/220"}],"replies":[{"embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/comments?post=16536"}],"version-history":[{"count":1,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/16536\/revisions"}],"predecessor-version":[{"id":71610,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/16536\/revisions\/71610"}],"wp:attachment":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/media?parent=16536"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/categories?post=16536"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/tags?post=16536"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}