Saturday, November 02, 2019

Java 13: Enhancements to Switch Expressions

You may remember from my previous post that, in Java 12, the traditional switch statement was enhanced so that it could be used as an expression. In Java 13, there has been a further change to this feature. The break statement can no longer return a value. Instead, you have to use the new yield statement, as shown below:

final int result = switch (input) {
    case 0, 1 -> 1;
    case 2 -> 4;
    case 3 -> {
      System.out.println("Calculating: " + input);
      final int output = compute(input);
      System.out.println("Result: " + output);
      yield output;
    }
    default -> throw new IllegalArgumentException("Invalid input " + input);
};

Note that this is still a preview language feature, which means that it must be explicitly enabled in the Java compiler and runtime using the --enable-preview flag.

Saturday, October 26, 2019

Java 13: Text Blocks

Java 13 has delivered the long-awaited multiline strings or Text Blocks. You no longer need to concatenate strings that span multiple lines or escape special characters, which really improves the readability of your code. Text blocks are a preview language feature, which means that they must be explicitly enabled in the Java compiler and runtime using the --enable-preview flag.

Here is an example of a text block:

String textBlock = """
    <html>
      <body>
        <p style="color:red">This is a text block</p>
      </body>
    </html>""";

As shown above, a text block is enclosed by three double quotes ("""). The opening """ cannot be followed by any non-whitespace characters i.e. the actual text must start on the line following the opening delimiter. You do not need to escape any special characters within the text block, which is great!

In previous versions of Java, you would have had to write it like this:

final String old = "<html>\n" +
    "\t<body>\n" +
    "\t\t<p style=\"color:red\">This is a text block</p>\n" +
    "\t</body>\n" +
    "</html>";

In fact, in this example, textBlock == old because both have exactly the same content and refer to the same object in the String pool.

Now let's take a look at how leading whitespace is handled by considering the following two text blocks:

String textBlock1 = """
    <html>
      <body>
        <p style="color:red">This is a text block</p>
      </body>
    </html>""";
 
String textBlock2 = """
        <html>
          <body>
            <p style="color:red">This is a text block</p>
          </body>
        </html>
 """;

If you print out these two text blocks, the first one is printed out as:

<html>
  <body>
    <p style="color:red">This is a text block</p>
  </body>
</html>

and the second one as:

        <html>
          <body>
            <p style="color:red">This is a text block</p>
          </body>
        </html>

The leftmost non-whitespace character on any of the lines in the text block or the leftmost closing delimiter determines the "starting point" of the whole block and whitespace is preserved on each line from this starting point.

Another point to note is that trailing whitespace at the end of each line is removed in text blocks but you can use the octal escape sequence \040 to preserve it as shown below:

String octal = """
    line 1    \040
 line 2""";

Sunday, August 25, 2019

Switching Back to Windows 7 Style Outlook Email Alerts in Windows 10

In Windows 10, the Outlook 2016 desktop application sends email alerts to the Windows Notification Center. I don't like how big this email alert is and, more importantly, it's not possible to delete the email by clicking on the alert, which I could do in Windows 7. Instead, I have to go into Outlook and delete the email there.

The good news is that it is quite easy to switch back to the old-style email alert, which is smaller and has a delete button, as follows:

  1. Right-click the Outlook shortcut icon and choose "Troubleshoot Compatibility"
  2. In the Program Compatibility Troubleshooter dialog, select "Troubleshoot program"
  3. Select "The program worked in earlier versions of Windows but won't install or run now"
  4. Select "Windows 7"
  5. Press "Test the program..." which will launch Outlook. Send yourself an email to confirm that the email alert is now back to Windows 7 style
  6. Select "Yes, save these settings for this program"

Saturday, August 10, 2019

Stack Overflow - 200k rep reached!

I've been a bit quiet on Stack Overflow lately because work has been keeping me very busy, but I have now managed to reach 200,000 reputation!

For me, Stack Overflow has not simply been a quest for reputation, but more about learning and helping fellow programmers in need.

Right, time to celebrate!

Sunday, June 02, 2019

Java 12: Switch Expressions

In Java 12, the switch statement has been enhanced so that it can be used as an expression. It is now also possible to switch on multiple constants in a single case, resulting in code that is more concise and readable. These enhancements are a preview language feature, which means that they must be explicitly enabled in the Java compiler and runtime using the --enable-preview flag.

Consider the following switch statement:

int result = -1;
switch (input) {
  case 0:
  case 1:
    result = 1;
    break;
  case 2:
    result = 4;
    break;
  case 3:
    System.out.println("Calculating: " + input);
    result = compute(input);
    System.out.println("Result: " + result);
    break;
  default:
    throw new IllegalArgumentException("Invalid input " + input);
}

In Java 12, this can be rewritten using a switch expression as follows:

final int result = switch (input) {
  case 0, 1 -> 1;
  case 2 -> 4;
  case 3 -> {
    System.out.println("Calculating: " + input);
    final int output = compute(input);
    System.out.println("Result: " + output);
    break output;
  }
  default -> throw new IllegalArgumentException("Invalid input " + input);
};

As illustrated above:

  • The switch is being used in an expression to assign a value to the result integer
  • There are multiple labels separated with a comma in a single case
  • There is no fall-through with the new case X -> syntax. Only the expression or statement to the right of the arrow is executed
  • The break statement takes an argument which becomes the value returned by the switch expression (similar to a return)

Saturday, June 01, 2019

Using Java 12 in Eclipse

1. Install JDK 12

Link: https://www.oracle.com/technetwork/java/javase/downloads/jdk12-downloads-5295953.html

2. Install Eclipse 4.11

Link: https://download.eclipse.org/eclipse/downloads/drops4/R-4.11-201903070500

3. Install Eclipse Java 12 Support

Start Eclipse and go to Help > Install New Software. Add Update Site: https://download.eclipse.org/eclipse/updates/4.11-P-builds. Install Eclipse Java 12 support for 2019-03 development stream from the list of available software

4. Add Java 12 JRE to Eclipse

Go to Window > Preferences, navigate to Java > Installed JREs and add the Java 12 JRE (that you installed in Step 1). Tick the box to make it the default JRE

5. Upgrade Compiler Compliance Level

In your preferences, go to Java > Compiler and select "12" as the "Compiler compliance level". In addition, tick "Enable preview features".

That's it! Now you can try out Switch Expressions!

Monday, April 22, 2019

Load Testing Web Apps Using Apache JMeter

Apache JMeter is an excellent tool for simulating user load on a web application in order to test performance. You can easily build a test plan by specifying the number of users and the interval between requests, and JMeter will then spawn a thread per user and hit your webapp. At the end of the test, you will get a performance summary report showing the min, max and average response times.

Here is a quick walkthrough of using JMeter:

  • Download JMeter from here
  • Run the jmeter.bat (for Windows) or jmeter (for Unix) file to start the JMeter GUI
  • Add a "Thread Group" to the Test Plan and configure the number of users, ramp-up period and duration of the test
  • Add a "HTTP Request" to the Thread Group and set the server URL and any request parameters
  • Add a "Constant Timer" (or any other Timer) to the HTTP Request and specify the time interval between requests
  • Add a "Summary Report" to the Thread Group
  • Add a "View Results in Table" to the Thread Group
  • Run the test and view the Summary Report

There are a number of other components that can be added to the test plan as well. For example, you can add a "HTTP Header Manager" to the Thread Group if you want to add any fields to the request's header. The "Response Assertion" component is useful for checking if you have received the desired response from the server.

Once you are happy with your test plan, you can save it to a file and then run it on the command line whenever you need to load test your application or as part of your continuous build process.

Tuesday, January 01, 2019

fahd.blog in 2018

Happy 2019, everyone!

I'd like to wish everyone a great start to an even greater new year!

In keeping with tradition, here's one last look back at fahd.blog in 2018.

During 2018, I posted 14 new entries on fahd.blog. I am also thrilled that I have more readers from all over the world! Thanks for reading and especially for giving feedback.

Top 5 posts of 2018:

I'm going to be writing a lot more this year, so stay tuned for more great techie tips, tricks and hacks! :)

Related posts: