{"id":27149,"date":"2019-02-22T08:57:10","date_gmt":"2019-02-22T08:57:10","guid":{"rendered":"https:\/\/blog.jetbrains.com\/idea\/?p=19149"},"modified":"2019-03-20T16:12:41","modified_gmt":"2019-03-20T16:12:41","slug":"java-12-and-intellij-idea","status":"publish","type":"idea","link":"https:\/\/blog.jetbrains.com\/pt-br\/idea\/2019\/02\/java-12-and-intellij-idea","title":{"rendered":"Java 12 and IntelliJ IDEA"},"content":{"rendered":"<p>With switch expressions, Java 12 is enhancing one of its basic language\u00a0constructs \u2013 <code>switch<\/code> \u2013 to improve everyday coding experience for developers. Benefits are multi-fold. As compared to the \u2018traditional\u2019 switch constructs, <a href=\"http:\/\/openjdk.java.net\/jeps\/325\" target=\"_blank\" rel=\"noopener\"><em>switch expressions<\/em><\/a> can return a value. The ability to define multiple constants with a switch branch, and improved code semantics, makes it concise. By removing default fall-through switch branches, you are less likely to introduce a logical error in a switch expression.<\/p>\n<p>In this blog, we\u2019ll cover the pain points of using existing switch statements, define <em>switch expressions<\/em>, and explain why they are good for you. <\/p>\n<p>To use Switch Expressions, we&#8217;ll need IntelliJ IDEA 2019.1. It is free to download in its Early Access Program from <a href=\"https:\/\/www.jetbrains.com\/idea\/nextversion\/\" target=\"_blank\" rel=\"noopener\">our website<\/a>. Java 12 language features are not supported in 2018.3 or earlier versions of IntelliJ IDEA. Let\u2019s get started.<!--more--><\/p>\n<h1>Traditional switch constructs<\/h1>\n<p>If you think of a switch construct as a multi-way condition, using an expression seems to be a better fit. However, switch could only be used as a statement until now. The current switch syntax is constrained and verbose. It often leads to error-prone code that is difficult to debug.<\/p>\n<p>Here\u2019s an example that uses a switch statement to calculate the <code>height<\/code> of a chair, based on the <code>size<\/code> value passed to it:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"default\" data-enlighter-title=\"\">public enum Size {S, M, L, XL};\r\npublic class Chair {\r\n    public void calcHeight(Size size) {\r\n        int height = 0; \r\n        switch (size) {\r\n            case S:\r\n                height = 18;\r\n            case M:\r\n                height = 20;\r\n                break;\r\n            case L:\r\n                height = 25;\r\n                break;\r\n        }\r\n    }\r\n}<\/pre>\n<p>The preceding code has multiple issues:<\/p>\n<ul>\n<li>Repetitive <code>break<\/code> and assignment statements add noise to code.<\/li>\n<li>Code verbosity makes it difficult to comprehend the code.<\/li>\n<li>Default fall-through in switch branches sneaks in a logical error \u2013 the missing <code>break<\/code> statement for case label <code>S<\/code> lets the control fall through to case label <code>M<\/code>. This results in assignment of 20 instead of 18 to <code>height<\/code> when you execute <code>calcHeight(Size.S)<\/code>.<\/li>\n<\/ul>\n<h1>Switch expressions<\/h1>\n<p>Let&#8217;s rewrite the preceding example using a switch expression. In IntelliJ IDEA, you can\u00a0use Alt+Enter on the <code>switch<\/code>\u00a0keyword to see the suggestions. Select &#8216;Replace with enhanced &#8216;switch&#8217; statement&#8217; to convert the traditional <code>switch<\/code> statement to a switch expression:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-16062\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-cover-Java12-SwitchExpr-gif1.png\" alt=\"\" width=\"703\" height=\"393\" data-gif-src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-Java12-SwitchExpr-gif1.gif\" \/><\/p>\n<p>The preceding code offers multiple benefits:<\/p>\n<ul>\n<li>Code in a switch branch is concise and easy to read. You define what to execute to the right of <code>-&gt;<\/code>.<\/li>\n<li>Switch branches can return a value, which can be used to assign value to a variable.<\/li>\n<li>Switch branches <i>don&#8217;t<\/i> need a <code>break<\/code> statement to mark their end. In absence of a <code>break<\/code> statement, the control doesn&#8217;t fall through the switch labels \u2013 which helps avoid logical errors.<\/li>\n<\/ul>\n<h1>Returning value vs. executing statements<\/h1>\n<p>When you aren&#8217;t using a switch expression to return a value, a switch branch can choose to execute a statement or block of statements, or even throw an exception:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"default\" data-enlighter-title=\"\">public enum Size {S, M, L, XL};\r\npublic class NotReturningValueFromSwitchLabel {\r\n    public void calcHeight(Size size) {\r\n        int height = 0; \r\n        switch (size) {\r\n            case S -&gt; height = 18;\r\n            case M -&gt; { \r\n                           height = 20; \r\n                           System.out.println(height);\r\n                      }\r\n            case L -&gt; height = 25;\r\n        }\r\n    }\r\n}<\/pre>\n<h1>Handling all possible argument values<\/h1>\n<p>When you are using a switch expression to <i>return<\/i> a value, it should be able to handle <i>all<\/i> possible values that you could pass to it as an argument. For instance, if you miss a case label corresponding to an enum constant, IntelliJ IDEA detects it. It offers to insert the specific case label or <code>default<\/code> case label.<\/p>\n<p>By default, IntelliJ IDEA inserts a default value depending on the variable type. You can edit the placeholder value:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-16062\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-imgSwitchExprMissingBranch.png\" alt=\"\" width=\"639\" height=\"357\" data-gif-src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-gifSwitchExprMissingBranch.gif\" \/><\/p>\n<p>Types other than an enum can have infinite values. When you pass types like <code>byte<\/code>, <code>short<\/code>, <code>int<\/code>, or <code>String<\/code> and miss including the <code>default<\/code> label, IntelliJ IDEA can detect and fix it:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-16062\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-Frame1-switchexpr-4.png\" alt=\"\" width=\"639\" height=\"357\" data-gif-src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-SwitchExpr4-DefaultBranch.gif\" \/><\/p>\n<h1>Define multiple constants in the same case label<\/h1>\n<p>Unlike switch statements, switch expressions allow you to define comma-separated multiple constants in a case label. This cuts down code redundancy \u2013 you can execute the same code for all case labels.<\/p>\n<p>If you define redundant code for your case labels in a switch expression, IntelliJ IDEA can fix it for you:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-16062\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-imgSwitchExprCaseMerge.png\" alt=\"\" width=\"639\" height=\"357\" data-gif-src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-gifSwitchExprCaseMerge-2.gif\" \/><\/p>\n<h1>Local variables and break statements in switch branches<\/h1>\n<p>With switch expressions, you can define local variables in switch branches. The block must include a <code>break<\/code> statement specifying the value to return:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"\">enum Size {S, M, L, XL};\r\n\r\npublic class LocalVariablesWithSwitch {\r\n    public void assignValue(Size size) {\r\n        int height = 0;\r\n        height = switch(size) {\r\n            case S -&gt; 18;\r\n            case M -&gt; {\r\n                    int weight = 19;\r\n                    break (weight &gt; 10 ? 15 : 20); \r\n                } \r\n            case L, XL -&gt; 25;\r\n        };\r\n    }\r\n}<\/pre>\n<p>The case label for value M defines a block statement. A block can also define local variables (weight in this case). The scope and accessibility of the local variable <code>weight<\/code> is limited to the case label M. Notice how a switch expression uses a <code>break<\/code> statement to return a value.<\/p>\n<p>Just in case you miss defining a return value for a switch branch, IntelliJ IDEA underlines the keyword <code>case<\/code>. When you hover the mouse pointer over it, you can view the message about the missing return value:<\/p>\n<p><a href=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-usingBreakToReturnValueFromSwitch.png\" rel=\"attachment wp-att-19205\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-19205\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-usingBreakToReturnValueFromSwitch.png\" alt=\"usingBreakToReturnValuFromSwitch\" width=\"562\" height=\"313\" \/><\/a><\/p>\n<h1>Preview language feature<\/h1>\n<p>Switch expressions is a <a href=\"http:\/\/openjdk.java.net\/jeps\/12\" target=\"_blank\" rel=\"noopener\">preview language feature<\/a>. This essentially means that even though it is complete, it has a possibility of <i>not<\/i> being confirmed as a permanent feature in a future Java release. This happens for a reason.<\/p>\n<p>Java runs on billions of devices and is used by millions of developers. Risks are high for any mistake in a new Java language feature. Before permanently adding a language feature to Java, the architects of Java evaluate what the developers have to say about it \u2013 how good or bad it is. Depending on the feedback, a preview feature might be refined before it&#8217;s added to Java SE, or dropped completely. So, if you have any feedback on Switch expressions, please share it <a href=\"https:\/\/mail.openjdk.java.net\/mailman\/listinfo\/amber-dev\" target=\"_blank\" rel=\"noopener\">here<\/a>.<\/p>\n<h1>IntelliJ IDEA Configuration<\/h1>\n<p>Since Switch expressions is a Java 12 language feature, please download and install <a href=\"https:\/\/jdk.java.net\/12\/\" target=\"_blank\" rel=\"noopener\">OpenJDK 12<\/a> and configure it to use with IntelliJ IDEA:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-16062\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-png-SwitchExpr-IntelliJ-Settings.png\" alt=\"\" width=\"1020\" height=\"720\" data-gif-src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2019\/02\/idea-Switchexpr-IDEsettings.gif\" \/><\/p>\n<p>Java is evolving and switch expressions is one of the welcome changes in Java 12.<\/p>\n<p><b>Happy Coding!<\/b><\/p>\n","protected":false},"author":921,"featured_media":0,"comment_status":"open","ping_status":"open","template":"","categories":[808],"tags":[744,3335,3328],"cross-post-tag":[],"acf":[],"_links":{"self":[{"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/idea\/27149"}],"collection":[{"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/idea"}],"about":[{"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/types\/idea"}],"author":[{"embeddable":true,"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/users\/921"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/comments?post=27149"}],"version-history":[{"count":0,"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/idea\/27149\/revisions"}],"wp:attachment":[{"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/media?parent=27149"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/categories?post=27149"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/tags?post=27149"},{"taxonomy":"cross-post-tag","embeddable":true,"href":"https:\/\/blog.jetbrains.com\/pt-br\/wp-json\/wp\/v2\/cross-post-tag?post=27149"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}