Tag Archive | ocp java

Sailing with Java 8 Streams

Let us explore Java 8 features and start using it in your day to day work. You will be surprised how Java has evolved to become so different yet easy & powerful. In this presentation, we discuss Java 8 Stream API.

 

OCJP Samples Questions: Exceptions and Assertions

Are you a Java enthusiast and preparing for Java 8 certification exam (OCP Java SE 8)? Try out these questions on Exceptions and Assertions.

These questions has answers with detailed explanation.

Creating Immutable Classes such as String Class

What is an immutable object?

Once an object is created and initialized, it cannot be modified. We can call accessor methods (i.e., getter methods), copy the objects, or pass the objects around—but no method should allow modifying the state of the object. Wrapper classes (such as Integer and Float ) and String class are well-known examples of classes that are immutable.

Let us now discuss String class. String is immutable: once you create a String object, you cannot modify it. How about methods such as trim that removes leading and trailing whitespace characters–do such methods modify the state of the String object? No. If there are any leading or trailing whitespace characters, the trim method removes them and returns a new String object instead of modifying that String object.

Defining Immutable Classes

Keep the following aspects in mind for creating your own immutable objects:

  • Make the fields final and initialize them in the constructor. For primitive types, the field values are final, there is no possibility of changing the state after it got initialized. For reference types, you cannot change the reference.
  • For reference types that are mutable, you need to take of some more aspects to ensure immutability. Why? Even if you make the mutable reference type final it is possible that the members may refer to objects created outside the class or may be referred by others. In this case,
    • Make sure that the methods don’t change the contents inside those mutable objects.
    • Don’t share the references outside the classes–for example, as a return value from methods in that class. If the references to fields that are mutable are accessible from code outside the class, they can end up modifying the contents of the object.
    • If you must return a reference, return the deep copy of the object (so that the original contents remain intact even if the contents inside the returned object is changed).
  • Provide only accessor methods (i.e., getter methods) but don’t provide mutator methods (i.e., setter methods)
    • In case changes must be made to the contents of the object, create a new immutable object with the necessary changes and return that reference.
  • Declare the class final. Why? If the class is inheritable, methods in its derived class can override them and modify the fields.

Let us now review the String class to understand how these aspects of taken care in its implementation:

  • All its fields are made private. The String constructors initialize the fields.
  • There are methods such as trim, concat, and substring that need to change the contents of the String object. To ensure immutability, such methods return new String objects with modified contents.
  • The String class is final, so you cannot extend it and override its methods.

Here is a circle class that is immutable. For brevity, this example shows only the relevant methods for illustrating how to define an immutable class:

//ImmutableCircle.java
// Point is a mutable class
class Point {
 private int xPos, yPos;
 
 public Point(int x, int y) {
     xPos = x;
     yPos = y;
 }
 
 public String toString() {
     return "x = " + xPos + ", y = " + yPos;
 }
 
 int getX() { return xPos; }
 int getY() { return yPos; }
}

// ImmutableCircle is an immutable class – the state of its objects
// cannot be modified once the object is created
public final class ImmutableCircle {
 private final Point center;
 private final int radius;

 public ImmutableCircle(int x, int y, int r) {
    center = new Point(x, y);
    radius = r;
 }
 
 public String toString() {
     return "center: " + center + " and radius = " + radius;
 }
 
 public int getRadius() {
     return radius;
 }
 
 public Point getCenter() {
    // return a copy of the object to avoid
    // the value of center changed from code outside the class
    return new Point(center.getX(), center.getY());
 }
 
 public static void main(String []s) {
     System.out.println(new ImmutableCircle(10, 10, 20));
 }
 // other members are elided ...
}

This program prints

center: x = 10, y = 10 and radius = 20

Note the following aspects in the definition of the ImmutableCircle class:

  • The class is declared final to prevent inheritance and overriding of its methods
  • The class has only final data members and they are private
  • Because center is a mutable field, the getter method getCenter() returns a copy of the Point object

Immutable objects also have certain drawbacks. To ensure immutability, methods in immutable classes may end-up creating numerous copies of the objects. For instance, every time getCenter() is called on the ImmutableCircle class, this method creates a copy of the Point object and returns it. For this reason, we may need to define a mutable version of the class as well, for example, a mutable Circle class.

The String class is useful in most scenarios, if we call methods such as trim , concat , or substring ina loop, these methods are likely to create numerous (temporary) String objects. Fortunately, Java provides StringBuffer and StringBuilder classes that are not mutable. They provide functionality similar to String,  but you can mutate the contents within the objects. Hence, depending on the context, we can choose to use String class or one of StringBuffer or StringBuilder classes.

Writing One-liners in Java 8

img

We all love one-liners, don’t we? The ones like these:

  • “War does not determine who is right – only who is left.”
  • “Always borrow money from a pessimist. He won’t expect it back.”
  • “We live in a society where pizza gets to your house before the police.”

For techies like us, “one-liners” mean something different – it’s a program that is written in one line. Of course, C is my favourite for writing oneliners, like the following one that copies a string from source (variable “char *s”) to target (variable “char *t”):

while (*t++ = *s++);

That’s cute, isn’t it? Perl is another favourite language for writing oneliners (there is even a book on it!)

With lambda expressions and streams in Java 8, you can now write curt code in Java also. Here are some one-liners written in Java 8:

Files.lines(Paths.get(“./FileRead.java”)).forEach(System.out::println);

This code prints the contents of the file “FileRead.java” in the current directory. The java.nio.file.Files class has lines() method that returns a StreamString>.

Pattern.compile(” “).splitAsStream(“a be cee”).forEach(System.out::println);

This code splits the input string “a be cee” based on whitespace and hence prints the strings “a”, “be”, and “cee” on the console. The java.util.Pattern class has splitAsStream() method that returns a StreamString>.

new Random().ints().limit(5).forEach(System.out::println);

This code prints five random integers and prints them to console. The java.util.Random class has ints() method that returns an IntStream. It generates an infinite stream of random integers; so to restrict the number of integers to 5 integers, we call limit(5) on that stream.

“hello”.chars().sorted().forEach(ch -> System.out.printf(“%c “, ch));

This code prints the characters e h l l o on the console.

The String class has chars() method (newly introduced in Java 8 in CharSequence—an interface that String class implements). This method returns an IntStream (why IntStream? Remember that there is no equivalent char specialization for Streams). This code calls sorted() method on this stream, so the stream elements get sorted in ascending order. Because it is a stream of integers, this code uses “%c” to explicitly force the conversion from int to char.

Few years back, if someone said you could write one-liners in Java (i.e., Java before version 7), I would have laughed: Java is so “verbose” that just getting Java to print “hello world” takes 8 lines or so! But with Java lambdas and streams (functional programming in Java), it is finally possible to write short but expressive code in Java.

If you are a Java programmer and haven’t done functional programming in Java 8, get started and explore the new way of programming in Java. A bonus is writing short code as illustrated by the one-liners in this article. Also, do check out our latest book for learning functional programming with lambdas and streams in Java 8: “Oracle Certified Professional Java SE 8 Programmer Exam 1Z0-809”, S G Ganesh, Hari Kiran, Tushar Sharma, Apress, 2015. URL:http://amzn.com/1484218353.

Dealing With the Diamond Problem in Java

How to solve the issues that arise from interfaces or classes that extend multiple interfaces in Java. In Java, an interface or class can extend multiple interfaces. For example, here is a class hierarchy from java.nio.channels package:

 

1685122-captured

The base interface is Channel. Two interfaces, ReadableByteChannel and WriteableByteChannel, extend this base interface. Finally, ByteChannel interface extends ReadableByteChannel and WriteableByteChannel.  Notice that the resulting shape of theinheritance hierarchy looks like a “diamond.”

In this case, the base interface Channel does not have any methods. The ReadableByteChannel interface declares read method and the WriteableByteChannel interface declares write method; the ByteChannel interface inherits both read and write methods from these base types. Since these two methods are different, we don’t have a conflict and hence this hierarchy is fine. Read more here

OCP Java (OCPJP) 8 Exam Quick Reference Card

If you are preparing to appear for Oracle Certified Professional Java SE 8 Programmer (OCPJP 8) certification exam, this a reference card (sort of long cheat sheet) meant to help you. You may want to print this reference card for your easy and quick reference when you prepare for your exam.

Source code of the book

Through out the book we have provided self-contained programs for explaining concepts related to the Oracle Certified Professional Java SE 8 programmer exam topics (1z0-809). Seeing and typing to try out the programs given in the book is a tedious task. Now, You can try out those programs given in this book by just downloading the source code here so that you can tweak them and check yourselves whether your understanding about the concepts is correct.

9781484218358

Java exam preparation guide

Oracle Java certifications are one of the most sought-after certifications in the IT world. In this site you will find useful resources for OCPJP 7 & 8 Exam preparation.

This book is a comprehensive, step-by-step and one-stop guide for cracking the Java SE 8 Programmer II exam (IZ0-809)

9781484218358