Practice Exams:

1z0-808 Oracle Java SE 8 Programmer – Lambda Expressions and Static Imports

  1. Section Overview

In this section, we’re going to learn about a new construct that was added to Java eight. It’s called the lambda. And the lambda gives us a way to pass in a block of code to a method as a parameter. We’ll also talk about static imports. So let’s hit the first lecture and look at lambda’s.

  1. Marker and Functional Interfaces

In the previous section, you learned all about interfaces, you learned all of the syntax and the rules. And we really don’t have a lot to add to that. But there are two different kinds of interfaces that I want to show you, especially the second one I will be introducing because it’s related to the topic of this section, lambdas. So when an interface doesn’t contain any methods at all, it’s referred to as a marker interface. And a marker interface is typically going to be used by the APIs of the Java platform. And it’ll use it to figure out, does this object adhere to some kind of a rule? Can I depend on that? The developer thought about and took care of some type of situation. Here’s a really common marker interface.

It’s the interface called serializable. It’s in the Java IO package. And there are no abstract methods that an object or a class will need to implement. They just simply say implement serializable, and then that’s it. No methods to implement. It’s not all that common for a developer such as ourselves to write our own marker interfaces, but it’s pretty common that as we write code in classes that will use marker interfaces that were provided by the Java API. Now back to serializable. The purpose of this particular interface is to say, well, let me define serializable. Serializable means that we can take our object, take all the state in it and turn it into a byte array.

And then that byte array can be used to send it across the network or to save it to a file and so on. And so when we say that we implement serializable, what we’re saying is we thought about it. We thought about which pieces of state should be serialized and which pieces shouldn’t outside the scope of this course. But there is a keyword called transient. And if I mark a piece of state as transient, then it will not be serialized when the object goes through that process. And so we use these kind of marker interfaces to let the Java API know, yes, we’re okay, we’ve taken care of this. So that’s all that a marker interface is. Now a functional interface is something that has one abstract method.

Marker interface has no abstract methods. A functional has one. So here’s an example. I’ve got my Payable interface and I have one abstract method raised salary. Note that I don’t have the word public or abstract in this definition, but remember that that’s implicit. If I don’t say public, it’s definitely going to be public anyway. That’s implicit. If I don’t say abstract, static or default, then it’s assumed to be abstract. So that is a functional interface. Now, if I had additional methods in here that were default or static methods, it’s still considered functional as long as there’s only one abstract method. There’s one little sort of gotcha rule about that.

Maybe it’s the kind of thing you might see on an exam. But the only one abstract method rule is bent. If we make an abstract method that’s overriding a method that comes from Java laying object in other words, if I had public abstract string, two string which is overriding the method, two string in Java lang object, then that would be okay. I could have additional abstract methods that come from object, but that’s it. And the reason that we’re focusing on functional interfaces is because it’s tied directly to a new syntax that we have in Java se eight called the Lambda Expression. And in the next lecture, we’ll take a look and see what that is.

  1. Lambda Expressions

One of the most celebrated pieces of functionality that was added to Java Eight is called the Lambda expression, although most people just call it a lambda. It’s a syntax that allows us to write a code, a block of code and to pass it around in the same way that we would a primitive or an object reference. And so the use case is imagine we got some kind of a functional interface. The functional interface, remember, defines one aspect abstract method. And we’ve written a method that says we accept a parameter. It’s really any object that is an instance of this functional interface. So what we’d normally have to do, we would normally have to create a brand new class that implements the functional interface.

We’d have to override the abstract method. We’d have to instantiate an object from that new class and then pass it into the method. Let’s actually see that in action. So here is the traditional interface implementation. We start with our functional interface. We’ve got payable and it’s going to have one method here. It’s an abstract method, raise salary. Then we’re going to have some part of the code that’s going to say I accept a payable object so that I can call the method raised salary. So here’s an example of that. We’ve got our cut check method. It accepts a payable object and it knows that it can call raised salary on it because that’s the only abstract method it has at this moment in time.

Cut check doesn’t really care what object you truly are, if you’re an employee or if you’re even a cat. As long as you are payable, it knows that it can say raise salary and you’ll return some kind of a double. That’s all it cares about. So nothing’s changed there in Java eight. That’s how you would write a functional interface and that’s how you’d make a method that accepts a functional interface. But here’s what’s changed prior to Java Eight. What we’d have to do is make sure that some class, some concrete class implements that payable interface and then we would create an implementation. We would override the raised salary method.

Okay, fine. So then to use it at runtime we would create a new consultant, call the cut check method and pass in that consultant object. And of course that seems fine, that seems like exactly how you would do it. It does work as expected. But the problem is that any time we want to make a new raised salary implementation, we have to create an entirely new class. Now I did mention previously that there’s another construct we don’t cover here called an anonymous class. That’s an alternative way that we could do it, but it’s still more code that we’d have to write than what we’re about to see.

Specifically, the lambda is going to allow us to pass in a method implementation for that functional interface without having to create an entire class for it. So here’s an example. Now we’ve got our salary, which is 75,000, we’re calling Cutcheck. And the syntax you’re seeing here, that is the lambda expression. The syntax of the lambda is first of all on the left side of the arrow token. The arrow token is right in the middle there. It’s just a dash and a greater than symbol. In this case, what we’re saying is we’re implementing a method and we’re going to have one parameter passed into us, it’s type double and we’re going to call that parameter percentage.

Then on the right side of the arrow token, that’s the implementation. We are implementing the abstract method without defining the whole signature. Again, we’re just putting in the method body the things that would be in between the curly braces. So in this case, we’re saying we’re going to return the salary plus the percentage multiplied by the salary. What if we had more than one parameter, if we had multiple parameters that are being passed into the interface method? Well, in that case they just need to be comma separated. So here we were creating an implementation of a method. We’re going to be passed in three parameters.

We’re naming those parameters A, B and C. And then on the right side of the arrow token, that’s where we’re using them. Return A plus B plus C. If your functional interface defines a method that has no parameters, you just use an empty set of parentheses. So in this case, nothing’s being passed into our method. We’re just executing the code in the block. So that’s the lambda syntax. You’re essentially just specifying what is the implementation of the method without having to create the class, without having to redefine the method signature. You just pass in the body and of course, mention what the parameters are that are being passed into your method. But we can even simplify the syntax further.

So let’s start with the lambda expression that we had in Cutcheck. Let’s review it. On the left side of the arrow token we’ve got double percentage, which means when the body is executed, when our implementation is executed, a parameter is going to be passed in and we’re going to refer to that parameter as percentage. It’s of type double. And then on the right side of the arrow token, that’s the body. And we’re saying we’re going to return the salary plus the percentage multiplied by the salary. Now, the parameter type on the left side is optional. I can just put percentage. We don’t actually have to specify that it is a double.

If it turns out that on the left side there’s only one parameter, we’re only being passed in one parameter to the body of our method, then we don’t even need the parentheses around it. So now on the left side we just have percentage. We don’t have the type double, we don’t have the parentheses, and that’s perfectly legal. But again, only if there is only one parameter. If we had more than one parameter we wouldn’t be able to do this. Now on the right side where we’re defining the body if there is only one statement in the body then we can get rid of the curly braces, we can get rid of the return keyword and we can get rid of the semicolon but we have to do that all as a group.

You can’t just say like well, I think I’ll just get rid of the curly braces or just the return or just the semicolon. They all appear together or they’re all omitted together. And so now this is the simplest version of the lambda expression we can have. So we accept a parameter that we’re calling percentage. And then the body, the execution is we are returning the salary plus the percentage multiplied by salary.

So now the cutcheck method of implication looks like this here. We’ve got our double salary 75,000, we call cut check, and we pass in that entire lambda expression.

And although that looks a little bit like more code than just simply passing in the consultant, we didn’t have to actually make an implementation of the functional interface. We didn’t have to override the method completely. With the method signature, we were able to just simply create this nice terse lambda expression. As a side note, the parameter names between the lambda and the functional interface don’t actually have to match I used percentage in both the method definition and the lambda but you can see here we could just have used x. I could have said x is the name of the first parameter passed in. As long as I use x in the body then that’s legal. You can use whatever parameter names you want.

  1. Predicate

One of the more common functional interfaces that people write is where they are going to run some kind of a test. They accept a parameter, they run some kind of a test and then they return true or false depending on whether or not the test passed. So when the lambda expressions were introduced in Java eight, they included another interface called the predicate and it handles that very scenario that it’s a test method. It’s passed in a parameter and then it returns a boolean. So the type of the interface is predicate t. And notice those arrows with the t, that’s known as a parameter type.

So t, we just simply specify what is the type of object that’s going to be passed into the test. So the method then is called test and it takes an object of that type t and then returns a boolean. So in other words, you just run test. We pass in a parameter, we execute some code to determine whether or not the test passes and we return that result to the caller. So that t. I said it’s a parameter type that’s a part of generics and that’s something that we’re going to be talking about in the collection section. So let’s look at an example. Let’s say we’ve got a method where we’re able to include a customer in a promotional mailing.

But we want this to be fairly flexible so that someone who calls this method to kick off the mailing could give us some sort of a test to say whether or not a customer should in fact be included in the mailing. So here’s our promotion service class. We’ve got a customer and we’ve got our method Send Promotion which takes a predicate and the predicate is going to be passed a customer object. And so then what we do is we simply call test. We pass in the customer that we have and whoever calls this method and passes in the predicate can run whatever arbitrary test they want. They’ll return true or false and then we’ll find out if we should include them in the promotional mailing.

So any code now that’s going to call this send promotional method can pass in a lambda expression to execute that test. So it might look like this. We instantiate the promotion service object we call Send Promotion and then we pass in our lambda. So remember, the left side is the parameter that we’re about to receive. We’re receiving a customer and then the test is going to be customer get age and make sure that their age is over 18, greater than or equal to 18 if it is return true and they get the promotional mailing. If it’s not return false and they don’t.

  1. Static Imports

Applications typically need some constant values to use in the life of the program. We’ve defined constants as variables that are typically public, static and final in a class. We’ve also seen that interfaces can define constants alongside the abstract static and default methods. So for example I could have a interface here called Safe Driver and we’ve got some constants in here. We’ve got maximum speed, safe falling distance, minimum fuel level. We also have a static method. Print max Speed. In this case it’s going to print whatever the maximum speed is. These are just constants and static methods that are available in the interface.

Now imagine a situation where you’re implementing a class and you’d love to import these different constants but you don’t actually want to implement drive and stop. You don’t really want to implement the interface, you just want the constants. Well Java has a feature which does allow us to import constants and static methods without having to actually import the entire class or implement the entire interface. It’s called a static import and it’s too bad it wasn’t called an import static because that’s how you actually write it. You’re never going to write static import, you write import static. It’s an import that goes along with all of your other import statements but just notice that it includes that keyword static.

And then what you do is you put in the name of the static constant or the static method that you are trying to import. So in this case we just want to call the method Print Max Speed. So now here we have print. Max speed. Now of course we could have just said Safe Driver print Max Speed here in the main method that would have been perfectly fine but this allows you to write a little less code. We don’t have to put the name of the interface, we can just invoke the method. Now the previous example showed us importing one specific static member. We can also implement all of the static members of an interface or a class using a wild card.

So in this case here I’ve got import static. com intertech safedriver star and so now I’m going to get all of the static members that are inside of Safe Driver so I can refer to maximum speed and that is perfectly legal. I can call print. Max speed. But one of the things about the wild card is that it doesn’t act as a traditional import. So what I couldn’t do oddly enough is say Safe Driver, safe following distance and it’s not the safe following distance that’s the problem. If I got rid of Safe Driver it would work. But the problem is that when this class is being compiled they’re going to see Safe Driver and since it’s not we didn’t do a traditional import it’s going to say I’m not entirely sure what Safe Driver is.

So if we did for some reason wanted to include the name of the interface occasionally. Then we’d have to uncomment this line right here, which is your regular import import intertext safe driver. And then I would be able to include the type. Why would you want to do that? I’m not entirely sure, but that’s one of those kind of gotchas that they may throw at you on the exam. So I want you to be aware that that’s just not legal unless you have a normal traditional import. There’s also a note down here that says similar to regular imports, wildcards and static imports are not recursive. And really, that should be kind of obvious because the way we’re using the wildcard here is different than a regular import.

With a regular import, we’re applying a wildcard to a package and there could be sub packages. But here we’re applying the wildcard to either a class or an interface. So there are no sub packages to a class or an interface. The wildcard simply means grab the stuff that’s in this particular entity. But it’s not just interfaces that the static import is used. It can be used to access static members of a class. For example, if you’re using the Java Lang math class quite a bit, you could add a static import to reduce the amount of typing. Like, for example, math has E as a constant and Pi as a constant.

And of course, we don’t have to import the math class because it’s in the Java Lang package. We get that out of the box. But anytime we’d refer to Pi or E, we’d have to include the Math reference, which would look something like this. So here I’ve got my calculation and I’m multiplying some stuff to math point pi, right? Math dot pi. If I use a static import now, I can refer to Pi without having to include the Math dot. Does that really give you a whole lot? I don’t know, I think that’s debatable. I don’t tend to use a lot of static myself, but they are part of the syntax, so you need to know and it’s definitely a part of the exam.

  1. Lambda Expressions Lab

In this lab, you’re going to work with a new feature to Java eight. You’re going to work with a lambda. So you’ll be creating a functional interface called rushable, and the lambda will then determine whether or not an order is a rush job. As always, the instructions are in the resources for this lecture. It is called lab twelve lambda’s. It’s a PDF file. All of the instructions are in there, as well as the solution code. If you have any questions, please let me know.