Switch expressions in Java 12

With switch expressions, Java 12 is enhancing one of its basic language  constructs – switch – to improve everyday coding experience for developers. Benefits are multi-fold – from reduced code verbosity, better code readability to no implicit fall-through ambiguity through its case labels.

Code semantics for Switch expressions

Here’s an example of new switch expression, which modifies a variable value, based on an enum value passed to a method:

enum SingleUsePlastic {STRAW, BAG, SPOON, FORK, KNIFE, PLATE, BOTTLE};
class Planet {
    private static long damage;
    public void use(SingleUsePlastic plastic) {
        damage += switch(plastic) {
                case STRAW -> 10;
                case BAG -> 11;
                case SPOON, FORK, KNIFE -> 7;
                case PLATE -> 15;
                case BOTTLE -> 20;
       };
    }
}

The new switch expression shown in the preceding code is a pleasure to read and comprehend. It lets the business logic take the centre stage.

The following image highlights the changes:

The new switch expressions are in addition to the traditional switch constructs. They are not replacing the existing switch constructs.

A switch expression offers multiple benefits and features:

  • Unlike a switch construct, a switch expression can return a value
  • The return value of a switch case is followed by ->
  • The case labels can include comma separated multiple values
  • There isn’t any fall through of the control across switch case labels
  • The code is easy to read and understand

Issues with the traditional switch constructs

The current syntax of switch constructs is constrained and verbose. It often leads to error prone code, which is difficult to debug.

Let’s rewrite the preceding example using the traditional switch statement:

enum SingleUsePlastic {STRAW, BAG, SPOON, FORK, KNIFE, PLATE, BOTTLE};
class Planet {
    private static long damage;
    public void use(SingleUsePlastic plastic) {
        switch (plastic) {
            case STRAW  : damage += 10;
                          break;
            case BAG    : damage += 11;
                          break;
            case SPOON  : damage += 7;
                          break;
            case FORK   : damage += 7;
                          break;
            case KNIFE  : damage += 7;
                          break;
            case PLATE  : damage += 15;
                          break;
            case BOTTLE : damage += 20;
                          break;
       };
    }
}

The arms (case labels) in switch constructs must include a break statement to prevent fall-through of the control. This essentially means that when control finds a matching case value, it will execute the statements until it finds a break statement, or it reaches the end of the switch construct.

Let’s modify the preceding code, replacing the break statement corresponding to case label KNIFE with System.out.println() statement:

case KNIFE  : damage += 7;
              System.out.println(7);

With this modified code, when you call use(SingleUsePlastic.KNIFE), the following happens:

  • Control falls-through the arm corresponding to value PLATE
  • Variable damage increments by 22 (7 for KNIFE and 15 for PLATE).

The traditional switch construct have a default fall-through of control across the case labels, in absence of a break statement. This leads to unexpected bugs.

The new switch expressions is here to bring the spotlight back to the business logic.

Code blocks, local variables and extended break statement

The switch expressions can define a block of code to execute for a matching value. The block is defined using a pair of curly braces and it must include a break statement specifying the value to return.

Let’s modify code from our previous example and define a code block corresponding to case PLATE:

class Planet {
    private static long damage;
    public void use(SingleUsePlastic plastic) {
        damage += switch(plastic) {
            case STRAW -> 10;
            case BAG -> 11;
            case SPOON, FORK, KNIFE -> 7;
            case PLATE -> {
                                int radius = ..;
                                break (radius < 10 ? 15 : 20); // Using break to 
                                                               // return a value
                          }
            case BOTTLE -> 20;
        };
    }
}

The case label for value PLATE defines a block statement. A block can also define local variables (radius in this case). The scope and accessibility of local variable radius is limited to the case label PLATE.

Notice how a switch expression uses a break statement to return a value (all case labels of a switch expression must return a value).

Another syntax for switch expressions

Apart from using -> to specify a return value, a switch expression can also use a colon (:) to mark the beginning of code to execute and a break statement to return a value. Here’s an example:

class Planet {
    private static long damage;
    public void use(SingleUsePlastic plastic) {
        damage += switch(plastic) {
            case STRAW : break 10;      // Use : to start code, break to return val
            case BAG : break 11;
            case SPOON, FORK, KNIFE : break 7;
            case PLATE :      // no need for using curly brace
                                int radius = ..;
                                break (radius < 10 ? 15 : 20); // Using break to 
                                                               // return a value
            case BOTTLE : break 20;
        };
    }
}

Comparing break with break <return value>

A traditional switch construct uses a break statement (without any return value) to break out of a switch construct when a matching value is found. It also prevents fall-through of the control across multiple case labels. A break statement with a return value is used in switch expressions to return a value and return the control from a switch expression.

You can compare these flavors of break with a return statement with similar flavors. In a method, you can use a return statement to return a value and exit a method, or just exit a method without returning a value. Here’s a quick example:

int calculate(int value1, int value2) {   // return type of method is int
    int result = …
    return result;                        // returns int value
}

void output(int value1, int value2) {     // return type of method is void
    int result = …
    if (result > 10)
        return;                           // Just exit method without returning
    else                                  // any value.
        System.out.println(…);
}

A switch expression uses break to return a value. Traditional switch construct uses break to prevent fall-through of control across its case labels.

Returning values for all case labels

All case labels must return a value in a switch expression. If you define a code block in a switch construct and miss returning a value, the code won’t compile:

class Planet {
    private static long damage;
    public void use(SingleUsePlastic plastic) {
        damage += switch(plastic) {
            case SPOON, FORK, KNIFE -> 7;
            case PLATE -> {
                                int radius = ..;
                              // no break statement
                          }
        };
    }
}

In the preceding code, since the code block for label PLATE doesn’t return a value using the break statement, it won’t compile.

Similarly, if you use a colon (:) to define the case labels of a switch expression, all its labels must include a break statement with a return value. Otherwise your code won’t compile:

class Planet {
    private static long damage;
    public void use(SingleUsePlastic plastic) {
        damage += switch(plastic) {
            case SPOON, FORK, KNIFE : break 7;   // this is okay
            case PLATE : int radius = ..;
                         // no break statement   // Won’t compile
        };
    }
}

All case labels in a switch expression must return a value, or else the switch expression won’t compile.

Executing code with switch expressions

As of now, switch expression is a preview feature, that is, it might be removed in a future Java version. To compile source code, say, Planet.java, with switch expressions, you’ll need JDK 12 (downloadable from https://jdk.java.net/12/).

Compile your code with the following command line options:

> javac --release 12 --enable-preview Planet.java

You can execute it as follows:

> java --enable-preview Planet

 

- Mala Gupta

Epsilon – A Garbage Collector which doesn’t collect any garbage

Imagine a software organization replaces its programmers with the ones who don’t know how to code; to calculate how long will it take for them to exhaust their funds and shut down. In this scenario, new revenue stops while pay to staff continues. In a similar manner, when one uses Epsilon garbage collector, introduced in Java 11, software application replaces its Garbage collector (GC) with Epsilon, which does not release memory; to calculate how long will it take for the JVM to exhaust all its memory and shut down.

The expected behavior of a GC is to allocate memory and then collect garbage (that is, release memory blocked by unused objects), so that developers can focus on other aspects of their applications. But GC behavior is un-deterministic– which means, you, as a developer can’t determine when GC cycles will start and introduce latency in your applications. This can be a major impediment in performance tuning especially when you are trying to investigate out the reason for instances of high latency in your system – whether it is your code – or the GC, which needs to be tuned.

Epsilon GC can help.

Epsilon is a no-operation GC – that doesn’t collect any garbage. It only handles allocation of memory. When the available Java heap exhausts, the JVM shuts down.

Here are a few scenarios where Epsilon is used.

Epsilon enables you to improve your applications by testing their performance. By comparing performance of your applications with Epsilon and other GCs, you can filter out GC-induced overheads from OS induced overheads – letting you choose the best GC.

Suppose you want to limit the memory usage of an application process. By using Epsilon, you can define the allocation limit, which fails JVM on heap exhaustion.You can stub the rest of processes and execute it using Epsilon with a memory allocation limit.

Since Epsilon doesn’t perform all the regular GC function of reclaiming memory, it has also proven useful in VM interface testing.

It is simple to use Epsilon. To evaluate Epsilon download JDK 11, released in Sep 2018.

Enable it at runtime using the options

-XX:+UnlockExperimentalVMOptions
and
-XX:+UseEpsilonGC

followed by the application class name. Following is an example:

> java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC MyApp

On initialization, Epsilon allocates memory in contiguous linear memory chunks, until your application completes its execution or runs out of heap memory. On running out of heap memory, JVM shuts down.

Epsilon must NOT be used in production. It is an experimental GC – to prevent it from being used in production unless explicitly enabled through JVM options, as it would be a disaster to use a GC that doesn’t reclaim memory. Epsilon is a powerful developer tool to fine tune application performance. Eventually, you’ll adopt another GC for your application in production.

Do you have alternatives to Epsilon? Yes, but it could be ambiguous, difficult or error prone.

You could configure existing GCs to never collect garbage, say, by setting very large young generation. But this could behave differently on different systems. You could modify existing GC to not collect garbage – but that could be against what they were designed for. Further improvements in existing GC – could reach overheads so low that Epsilon might not be required for latency or throughput parameters. But you could still use Epsilon for performance and memory testing.

Epsilon standardizes the process for application fine tuning. Several organizations have built custom JVMs – taking off garbage collection from it – so they could test their applications on multiple parameters like performance, memory, latency or throughput.

That’s not all. I think we have just scratched the surface and Epsilon can do much more. For example, it can help you create garbage free applications. One of the most popular ‘garbage free’ application is Log4j, a logging application by Apache. Give your imagination wings. Explore ways to make the best use of Epsilon.

– Mala Gupta

What is a NoSQL database?

Post for university students – bridge your IT gaps

Sooner or later, you’ll need to work with persistent data, stored in a database. With different types of data and storage or retrieval needs, you’ll come across the term relational, SQL or NoSQL databases.

Here’s an excellent article on this topic by Amazon : What is NoSQL


Confessions of an experienced project manager – why Java certifications are important

Here’s an interesting story of how Oracle Java Certification helped a team of Java programmers.

Hi, I am John, a senior project manager.

Our company hired a new Java programmer, to join my team, at our Atlanta office, some 5 months back.

I was doubtful at the beginning. With just a few months of experience, I was hesitant to add him to my team. All my team members had been working on various Java projects for more than 7 – 8 years.

I was wrong.

We were approached by a client – one of their Java projects didn’t seem to perform as much as it was supposed to, after being deployed to machines with multi-core processors. Among many measures, one of the steps was to refactor the code to make best use of Java’s parallel streams. My old team seemed to struggle with it. I admit – it is difficult to unlearn and learn new concepts. In this case, our new recruitment (with the least experience), took the lead. He knew about the latest Java language changes, changes in programming style and API changes. With his knowledge and the expertise and experience of all the team members, we managed to breeze though the changes. We even earned brownie points with our client for this project.

On reflecting, we realized that our new recruitment, Harry, knew about the latest language features and approaches because he earned his Oracle Java Programmer certifications. Though I don’t consider certification to be the only factor for his abilities to work on the project, it definitely played a big role.

In fact I would highly recommend experienced programmers to go for Oracle Java Programmer certifications. They include the latest changes in the language and programming approach. Most of the programmers don’t care about updating their skills. They polish their skills when they work on a new project. However, this could be a liability to the organisation and the project they are working on.

The topics included in the Oracle Java Certification like Lambdas, Functional Interfaces, Java Stream API, concurrency enhancements and many more, mandates a programmer to update herself with the latest enhancements.

I highly recommend Oracle Java Programmer Certifications – to improve the existing skills of your employees, increasing the proficiency of your team.

Happy coding!

Why I have been writing books on Oracle’s Java Programmer certifications

One of the most agonising sounds is – that of – shattering of your dreams.

As a young girl, my dreams were shattered. I wrote the books on Oracle Java certification with Manning Publications to save others from this pain.

I wanted to become a programmer, ever since I started to code at the young age of 10, in grade 6. I just loved how the mighty machines could be commanded to execute instructions with absolute precision. I felt powerful.

Fast forward – I graduated with a degree in Computer Science from the University. To my dismay, I realized there was a big gap between what I learnt at the university and what the industry required me to know to work on real projects.

I felt cheated.

My dreams were shattered.

For my first job as a Java programmer, I was asked to earn the Java’s programmer certification within three months of starting my work.

Voila! It was my a-ha moment. For me, it was the perfect way to align the skills of university students with the industry.

Oracle’s beginner certification in Java – Programmer Certifications – teaches the basic hygiene in programming. It covers all the basics of Java programming, a lot of which aren’t used by new programmers. It removes confusions with their usage, promoting good programming practices – showing the bugs that can be introduced with inappropriate code. It also helped me to debug code, finding syntax and logical errors, without even using the compiler or runtime engine.

No, I did NOT assume that I acquired all the preceding skills – the Java’s Programmer Certification validated them.

Ever since that moment –

I wanted to save the dreams of other young students and professionals, all over the world.

I want them to have awesome Java programming skills so that they get to work on the best Java projects.

The Oracle Java Certifications are recognized by the IT industry all over the world.

Oracle also offers multiple levels of certification in Core Java, Enterprise Java and Java Cloud Service.

Writing books on Java certification was one of the ways I could think of helping others.

The Oracle Java Programmer’s exam are not easy to pass. To ease the exam preparation, I use a lot of images, comic strips, hands-on ‘Twist in the Tale’ exercises in my book, so that readers get a hang of Java topics and can recall the final details while writing their exam.

I’m doing my bit to save the big dreams of young university graduates and professionals around the world.

Can you help me in saving these dreams?

– Mala Gupta

Free 15 sample questions on String Pool


Here’s a set of
15 free sample questions on String Pool, which have been taken from following of my blog posts on String Pool:

The blog posts don’t include comprehensive answers to the questions that are included in them.

I hope they help.

With much respect,
Mala

RARE pic of String’s Pool party


(Series on String Pool – Part 4 of 4)

I know, its late, but it took us a while to get this RARE pic for you.

In this (gossip) blog post, you’ll find out, who managed to let their hair down on the the New Year Eve’s String Pool party, hosted by the JVM. A you know, the ‘String Pool’ party is EXCLUSIVELY for the String literals.

But do you think its open to the String literals defined in ALL scopes?

Let’s see whether the String literals assigned to a local, instance or static variable, or passed as method arguments, were permitted in the String pool.

All of the following claimed to be invited by JVM:

(1) String literals assigned to local variables


(2) String literals passed as method arguments

(3) String literals assigned to instance variables


(4) String literals assigned to static variables



Now here is the rare pic of this party, exclusively for you!

As you can see, all String literals, irrespective of the scope in which they are defined, made it to the String pool.

The preceding pics and concepts will help you to answer questions on String Pool in the OCA Java Certification. For example, the following code will output ‘true’ thrice:

class EJavaGuruSPool3 {
	static String staticStr = "eJavaGuru.com";       // static variable
	String instanceStr = "eJavaGuru.com";            // instance variable

	public static void main(String args[]) {
		SPool3 sPool = new SPool3();
		sPool.aMethod(staticStr);                // static variable passed as method parameter
		sPool.aMethod(sPool.instanceStr);        // instance variable passed as method parameter
		System.out.println(staticStr == sPool.instanceStr);
	}

	void aMethod(String paramStr) {
		String localStr = "eJavaGuru.com";        // local variable
		System.out.println(localStr == paramStr);
	}
}

Here’s a quick question for your to answer.

What is the output of the following code?

 

class SPool4 {
	public static void main(String args[]) {
		final String local1 = "eJava";         // local1 variable in main
		final String local2 = "Guru.com";      // local2 variable in main
		SPool4 sPool = new SPool4();
		sPool.aMethod(local1 + local2);
	}

	void aMethod(String paramStr) {
		String localStr = "eJavaGuru.com";        // local variable in aMethod
		System.out.println(localStr == paramStr);
	}
}

 

Happy Coding!

Mala Gupta
Author of Manning’s OCA Java SE 8 Programmer I Cert book

String Pool : String instances created by concatenating two or more String literals

(Series on String Pool : Part 3 of 4)

Let’s hear the conversation between a programmer and JVM on this topic –


Programmer : “Where do the String instances created by concatenating two or more literal values reside? Are they placed in the String Pool?”

“Here’s a quick example. Will the variable ‘val2’ refer to the String instance referred to by variable ‘val1’:”

class EJavaGuru {
    public static void main(String args[]) {
        String val1 = "Fax";
        String val2 = "F" + "a" + "x";
        System.out.println(val1 == val2);
    }
}

 

JVM : “The preceding code will output true.”

 

Programmer : “What happens, if I modify the preceding code, so that one of the String literal is stored in a variable, as follows:”

 

class Test {
    public static void main(String args[]) {
        String val1 = "Fax";
        String temp = "x";
        String val2 = "F" + "a" + temp;
        System.out.println(val1 == val2);
    }
}

 

JVM : “It will output false. To keep it simple, I only place compile time constants in the String pool.”

 

Programmer : “What about the following modified code then?”

 

class EJavaGuru {
    public static void main(String args[]) {
        String val1 = "Fax";
        final String temp = "x";
        String val2 = "F" + "a" + temp;
        System.out.println(val1 == val2);
    }
}

 

JVM : “The preceding code is good to output true, because the value stored in the variable ‘temp’ is now a compile time constant.”

Programmer : : “Thanks for clearing my doubts.”

String Pool : String values returned by String methods – are they stored in the String Pool?

(Series on String Pool : Part 2 of 4)


If you are preparing for your OCA Java SE 8 Programmer 1 certification exam, this post on String pool and String methods is for you.

String values returned by the methods of class – are they stored in the String Pool?

Answer to this question is not so simple. It depends on:

a) whether the String instance on which a method is called, comes from the String pool.
b) the values that are passed to the String methods.

The OCA Java SE 8 exam will include questions to test whether a String value returned by a String method, can be equal to an existing String instance. These values might be compared using the == operator or the equals() method.

Calling String methods on String instances that aren’t in the String pool

A String instance, which is created using a String constructor (by using the ‘new’ operator), isn’t placed in a String pool. When you can call String methods on such instances, the returned String values are never placed in the String pool.

You’ll find out the reason for this, in the section that follows.

Let’s cover a few String methods in this post, starting with the method trim(). To get a hang of these concepts, I’ll take you through the source code of these methods, from class String.

Method replace()

In the following source code, you can see that the replace() method either returns the String instance that it is called on (by returning ‘this’), or creates and returns a new String instance, by using the ‘new’ operator.

The method replace() returns the String instance, it is called on, if the oldChar and newChar that are passed to it are same, including their cases (uppercase/ lowercase).

For the OCA Java SE 8 exam, it would mean that the following code will output ‘true’:

String eJava = new String("Hawaii");
String guru = eJava.replace('a', 'a');
System.out.println(eJava == guru);

And the following code will also output ‘true’:

String eJava2 = "Hawaii";
String guru2 = eJava2.replace('a', 'a');
System.out.println(eJava2 == guru2);

What happens when the old and new char that you pass to the replace() method aren’t same. Here’s a quick example, which will output false:

String temp = "Hawaoo";
String eJava = "Hawaii";
String guru = eJava.replace('i', 'o');
System.out.println(temp == guru);

The following code will also output ‘false’.

String temp2 = new String("Hawaoo");
String eJava2 = new String("Hawaii");
String guru2 = eJava2.replace('i', 'o');
System.out.println(temp2 == guru2);

But if you compare the variables ‘temp2’ and ‘guru2’ using the equals() method, the code will output ‘true’. Here’s the modified code:

String temp2 = new String("Hawaoo");
String eJava2 = new String("Hawaii");
String guru2 = eJava2.replace('i', 'o');
System.out.println(temp2.equals(guru2));         // outputs true

What happens it you call the String method replace() that accepts two String method parameters?  Will they output the same result? Open the source code of class String and verify it yourself.

Method substring()

In the following source code, you can see that the substring(int) and substring(int, int) method either returns the String instance that it is called on (by returning ‘this’), or creates and returns a new String instance, by using the ‘new’ operator.

Method trim()

Again, method trim() returns String instances pretty much on the same logic as methods substring() and replace(). trim() returns the String instance on which it is called, if no white spaces need to be removed from it, otherwise, it creates and returns a new String instance.

Here’s the source code of method trim():

Method concat()

Here’s the source code of method concat():

You can expect the concat() method to return a new String instance, if the method parameter passed to concat() is not null.

Here’s a quick sample OCA Java SE 8 question for you, based on the topics covered in this article:

What is the output of the following code?

String old = "1.5";
String oldest = "1.0";
String current = old.replace('.', '.');
String latest = oldest.replace(".", ".");
boolean result = old == current && oldest == latest;
if (result)
    old.concat("Hello ").trim();
else
    old.concat("Hello").substring(0, 5);
System.out.println(old);


a) true
b) false
c) 1.5
d) 1.5He
e) 1.5Hello
f) Compilation error
g) Runtime exception

Post your answers in the comments.

Happy coding.

With much respect,
Mala

String Pool : Why are String instances discriminated based on how they are created?

(Series on String Pool : Part 1 of 4)


Imagine how you would feel if you and your siblings were treated differently, depending on how you all were born.

The ones who were born in hospital A, can reside in a lavish resort with a pool. The ones who were born in hospital B, can’t reside in ‘the’ lavish resort with the pool.

Instances of class String are treated differently, by the JVM, depending on how they are created.

Welcome to the String Pool

The String Pool includes String instances, which are created using String literal values. The ones created by using the String constructor aren’t placed in the String pool.

Why is a String pool required?

String instances are widely used in Java. They are immutable, that is, once created, their value can’t change. By caching strings, JVM can save memory and improve performance. It ‘might’ refer to the existing strings, rather than creating new ones.

Why is this topic important in the OCA Java certification?

To ensure that new Java developers understand the difference between equality of String reference variables and equality of the values referred by them.

What’s the difference between equality of reference variables and equality of their values?

Equality of String variables (or any other type), is determined using the comparison operator, that is, ==.

A quick example:

String eJava = new String("OCA");
String guru = new String("OCA");
System.out.println(eJava == guru);


The preceding code will output false because the variables ‘eJava’ and ‘guru’ refer to different String instances.
Here’s another example, which checks the equality of values referred by the variables ‘eJava’ and ‘guru’, by using the method equals():

String eJava = new String("OCA");
String guru = new String("OCA");
System.out.println(eJava.equals(guru));

Since the variables ‘eJava’ and ‘guru’ refer to instances that store the same String value (‘OCA’), the preceding code will return true.

This seems okay. What is the problem?

Often new Java programmers mistake the comparison operator, that is, ==, for checking the equality of the ‘values’ referred by Java objects.

Due to the way the String instances are stored in a pool (or cache), their otherwise buggy code works okay. A quick example:

String eJava = "OCA";
String guru = "OCA";

System.out.println("Strings are equal : " + (eJava == guru));

In the preceding code, a new Java programmer is trying to check for the equality of the values referred to by the variables ‘eJava’ and ‘guru’. Though the code outputs true, a similar logic for the same programmer might give ‘incorrect’ output. Here’s another example:

String eJava = new String("OCA");
String guru = new String("OCA");

System.out.println("Strings are equal : " + (eJava == guru));

The preceding code will output false.

 


Tomorrow, I’ll share more interesting facts about the String pool.

Till then, Happy Coding!

With much respect,
Mala Gupta

Author of Manning’s OCA Java SE 8 Programmer I Cert Book.