Code Object Oriented Programming (Best Tutorial 2019)

Code Object Oriented Programming

How to code and learn Object Oriented Programming Tutorial 2019

In this tutorial, you will learn How to code and learn object-oriented programming. Although this blog concentrates on Java, it also refers to other languages, such as Groovy, Scala, and JavaScript, so you will gain a deeper understanding of concepts common to all programming languages.

 Object Oriented Programming

Software to Install

 Before you begin to program, you must install some basic tools.


Groovy A dynamic language similar to Java that runs on the JVM (Java Virtual Machine). For Java and Groovy, you will have to install the following. 


Install Java and NetBeans  

Download and install the Java JDK 8 with NetBeans. Open NetBeans and select File ➤ New Project… ➤ Java Application Install Groovy 

Go and install Groovy.


Trying It Out

After installing Groovy, you should use it to try coding. Open a command prompt, type groovyConsole, and hit Enter to begin.

In groovyConsole, type the following and then hit Ctrl+r to run the code.

print “hello”

Because most Java code is valid Groovy code, you should keep the Groovy console open and use it to try out all of the examples from this blog.

learn object oriented programming

You can also easily try out Scala and JavaScript in the following ways • 

For JavaScript (JS), just open your web browser and go to For Scala, type “scala” in your command prompt or terminal. Once you have the preceding installed, you should eventually install the following       

  • Scala An object-oriented language built on the JVM 
  • Git A version control program
  • Maven A modular build tool

Go ahead and install these, if you’re in the mood. I’ll wait.


Code on GitHub

A lot of the code from this blog is available on You can go there at any time, to follow along with the blog.


Coding Terms

object oriented programming

In this section, I’ll cover the basic syntax of Java and similar languages. Source file refers to human-readable code. Binary file refers to computer-readable code (the compiled code).


In Java, the source files end with .java, and binary files end with .class (also called class files). You compile source files using a compiler, which gives you binary files.


In Java, the compiler is called javac; in Groovy it is groovyc, and it is scalac in Scala. (See a trend here?) However, some languages, such as JavaScript, don’t have to be compiled. These are called interpreted languages.


Primitives and Reference

 Primitive types in Java refer to different ways to store numbers and have historical but also practical significance,

for example,

  • char A single character, such as A (the letter A)
  • byte A number from -128 to 127 (8 bits1). Typically, a way to store or transmit raw data
  • short A 16-bit signed integer. It has a maximum of about 32,000.
  • int A 32-bit signed integer. Its maximum is about 2 to the 31st power.
  • long A 64-bit signed integer. Maximum of 2 to the 63rd power
  • float A 32-bit floating point number. This is an imprecise value that is used for things such as simulations.
  • double Like float but with 64-bit
  • boolean Has only two possible values true and false (much like 1 bit GROOVY, SCALA, AND JAVASCRIPT


Groovy types are much the same as Java’s. In Scala, everything is an object, so primitives don’t exist. However, they are replaced with corresponding value types (Int, Long, etc.).


JavaScript has only one type of number, Number, which is similar to Java’s float. Every other type of variable in Java is a reference. It points to some object in memory. You can think of this as an address.



A string is a list of characters (text). It is a very useful built-in class in Java (and most languages). To define a string, you simply surround some text in quotes. 

For example     String hello = "Hello World!";

Here the variable hello is assigned the string "Hello World!".

In Java, you must put the type of the variable in the declaration. That’s why the first word above is String.


In Groovy and JavaScript, strings can also be surrounded by single quotes ('hello'). Also, declaring variables is different in each language. Groovy allows you to use the keyword def, while JavaScript and Scala use var.

For example

def hello = "Hello Groovy!" //groovy

var hello = "Hello Scala/JS!" //Scala or JS




Every statement in Java must end in a semicolon (;). In many other languages, such as Scala, Groovy, and JavaScript, the semicolon is optional, but in Java, it is necessary. Much as how periods at the end of each sentence help you to understand the written word, the semicolon helps the compiler understand the code.

By convention, we usually put each statement on its own line, but this is not required, as long as semicolons are used to separate each statement.



The assignment is an extremely important concept to understand, but it can be difficult for beginners. However, once you understand it, you will forget how hard it was to learn.


Let’s start with a metaphor. Imagine you want to hide something valuable, such as a gold coin. You put it in a safe place and write the address on a piece of paper. This paper is like a reference to the gold.


You can pass it around and even make copies of it, but the gold remains in the same place and does not get copied. On the other hand, anyone with the reference to the gold can get to it. This is how a reference variable works.


 Let’s look at an example.

String gold = "Au";

String a = gold;

String b = a;

b = "Br";

 After running the preceding code, gold and a reference to the string "Au", while b refers to "Br".


Class and Object


A class is the basic building block of code in object-oriented languages. A class typically defines state and behavior. The following class is named SmallClass

 package com.example.mpme;
public class  SmallClass  {


Class names always begin in an uppercase letter in Java. It’s common practice to use CamelCase to construct the names. This means that instead of using spaces (or anything else) to separate words, we uppercase the first letter of each word.


The first line is the package of the class. A package is like a directory on the file system. In fact, in Java, the package must actually match the path to the Java source file. So, the preceding class would be located in the path com/example/mpme/ in the source file system.


An object is an instance of a class in memory. Because a class can have multiple values within it, an instance of a class will store those values.


Create a Class

Open your IDE (NetBeans).
 Right-click your Java project and choose New ➤ Java Class.


Properties and Methods

 Next, you might want to add some properties and methods to your class. A property is a value associated with a particular object. A method is a block of code on a class.

package com.example.mpme;
public class SmallClass {
String name;
String getName() {return name;}
void print() {System.out.println(name);}
}de here to remove the line numbers.

In the preceding code, the name is a property and getName and print are methods.


Groovy Classes

Groovy is extremely similar to Java but always defaults to public.

package com.example.mpme;
             class SmallClass {
             String name //property
             def print() { println(name) } //method

Groovy also automatically gives you “getter” and “setter” methods for properties, so writing the getName method would have been redundant.


JavaScript Prototypes


 Although JavaScript has objects, it doesn’t have a class keyword. Instead, it uses a concept called prototype. For example, creating a class looks like the following

function SmallClass() {} = "name"

SmallClass.prototype.print = function() { print( } Here name is a property and print is a method.


Scala Classes

 Scala has a very concise syntax, which puts the properties of a class in parentheses.

For example

class SmallClass(var nameString) {
def  print =  println(name) }


Creating a New Object

 In all four languages, creating a new object uses the new keyword.

For example  sc = new SmallClass();



As a human, it is sometimes useful for you to leave notes in your source code for other humans—and even for yourself, later. We call these notes comments. You write comments thus

String gold = "Au"; // this is a comment
             String a = gold; // a is now "Au"
             String b = a; // b is now  "Au"
             b = "Br";
             /* b is now "Br".
             this is still a comment */


 Those last two lines demonstrate multiline comments. So, in summary,

  • Two forward slashes denote the start of a single-line comment.
  • Slash-asterisk marks the beginning of a multiline comment.
  • Asterisk-slash marks the end of a multiline comment. Comments are the same in all languages covered in this blog.
  • How source code comments work


 Arrays, Lists, Sets, and Maps

So far, I’ve only talked about single values, but in programming, you often have to work with large collections of values. For this, we have many data structures that are built into the language. These are similar for Java, Groovy, Scala, and even JavaScript.



An array is a fixed size collection of data values. Honestly, you probably won’t use an array very often, but it’s an important concept to learn. You declare an array-type in Java by appending [] to the type. For example, an array of ints is defined as int[].


int[] vampireAges = new  int[10]; // ten vampires

Accessing the values in an array uses the same square-bracket syntax, such as 1 vampireAges[0] = 1565; // first vampire


As you can see, the first index of an array is zero. Things tend to start at zero when programming; try to remember this. Patient 0              

Here’s a helpful metaphor the first person to start an outbreak (a zombie outbreak, for example) is known as patient zero, not a patient one. Patient one is the second person infected.


This also means that the last index of the array is always one less than the size of the array. This is also true for lists.

vampireAges[9] = 442; // last vampire

You can reassign and access array values just like any other variable.

int year = 2016; // current year?

int firstVampBornYear = year - vampireAges[0];


 You can also declare arrays of objects as well. In this case, each element of the array is a reference to an object in memory.

Vampire[] vampires = new Vampire[10]; // Vampire array with length 10 You can also populate your array directly, such as if you’re creating an array of strings, for example.

String[] names = {"Dracula", "Edward"};

 Unfortunately, arrays are difficult to use in Groovy and the Array object in JavaScript is more like a Java List. Java arrays are a somewhat low-level structure, used only for performance reasons.




Of course, we don’t always know how many elements we need to store in an array. For this reason (and many others), programmers invented List, a resizable collection of ordered elements.


In Java, you create List in the following way

List<Vampire> vampires = new  ArrayList<>();

The angle-brackets (<>) define the generic type of the list—what can go into the list. You can now add vampires to this list all day, and it will expand, as necessary, in the background.


You add to List like this

vampires.add(new Vampire("Count Dracula", 1897)); List also contains tons of other useful methods, including

 size() Gets the size of List

get(int index) Gets the value at that index

remove(int index) Removes the value at that index

remove(Object o) Removes the given object

isEmpty() Returns true only if List is empty

clear() Removes all values from List


In Java, List has many different implementations, but we’ll just focus on two (don’t worry about the details here).



The only difference you should care about is that, in general, LinkedList grows faster, while ArrayList’s get() method is faster. You’ll learn how to loop through lists, arrays, and sets (and what “loop” means) in the next section. For now, just know that lists are a fundamental concept in programming.


Groovy Lists

Groovy has a simpler syntax for creating lists, which is built into the language.

def list = []
             list.add(new Vampire("Count Dracula", 1897))
             // or
             list << new Vampire("Count Dracula", 1897)


Scala Lists

 In Scala, you create a list and add to a list in a slightly different way

1    var list = List[Vampire]();

2    list + new  Vampire("Count Dracula", 1897)


Also, this actually creates a new list, instead of modifying the existing list. This is because the default List in Scala is immutable, meaning it cannot be modified. Although this may seem strange in conjunction with functional programming, it makes parallel programming (programming for multiple processors) easier.


JavaScript Arrays


 As mentioned earlier, JavaScript uses Array instead of List.

Arrays can be created much like lists in Groovy. However, the methods available are somewhat different. For example, push is used instead of add.

def array = []

array.push(new Vampire("Count Dracula", 1897))

 You can also declare the initial values of Array. For example, the following two lines are equivalent

def years = [1666, 1680, 1722]

def years = new Array(1666, 1680, 1722)


To add to the confusion, arrays in JavaScript can be accessed much like Java arrays.


For example

def firstYear = years[0]

def size = years.length



Set is much like List, but each value or object can only have one instance in Set. Set has many of the same methods as List. In particular, it is missing the methods that use an index, because Set is not necessarily in any particular order.

Set<String> dragons = new HashSet<>();
             dragons.size(); // 2
             dragons.size(); // 1


 In Java, there is such a thing as SortedSet, which is implemented by TreeSet. For example, let’s say you wanted a sorted list of names, as follows

SortedSet<String> dragons = new TreeSet<>();
             // [Deerhurst, Lambton, Norbert, Smaug]


TreeSet will magically always be sorted in the proper order. Okay, it’s not really magic. The object to be sorted must implement the Comparable interface, but you haven’t learned about interfaces yet. JavaScript does not yet have a built-in Set class.




 The map is a collection of keys associated with values. It may be easier to understand with an example.

Map<String,String> map = new  HashMap<>();
             map.put("Smaug", "deadly");
             map.put("Norbert", "cute");
             map.size(); // 2
             map.get("Smaug"); // deadly Map also has the following methods


  •  containsKey(Object key) Returns true if this map contains a mapping for the specified key
  • containsValue(Object value) Returns true if this map maps one or more keys to the specified value
  • keySet() Returns a Set view of the keys contained in this map
  • putAll(Map m) Copies all of the mappings from the specified map to this map
  • remove(Object key) Removes the mapping for a key from this map if it is present


Groovy Maps

 Just as for List, Groovy has a simpler syntax for creating and editing Map.

def map = ["Smaug" "deadly"]
map.Norbert = "cute"
println(map) // [Smaugdeadly, Norbertcute]


Scala Maps

 Scala’s Map syntax is also somewhat shorter.

var map = Map("Smaug" -> "deadly")
             var  map2 =  map + ("Norbert" -> "cute")
             println(map2) // Map(Smaug -> deadly, Norbert -> cute) As with List, Scala’s default Map is also immutable.


 JavaScript Maps


JavaScript does not yet have a built-in Map class, but it can be approximated by using the built-in Object syntax. For example

def map = {"Smaug" "deadly", "Norbert" "cute"}

You could then use either of the following to access map values map.Smaug or map["Smaug"].


Conditionals and Loops

To rise above the label of the calculator, a programming language must have conditional statements and loops.

  •  A conditional statement is a statement that may or may not execute, depending on the circumstances.
  •  A loop is a statement that gets repeated multiple times.


If, Then, Else

 The most basic conditional statement is the if statement. It is the same in all languages covered in this blog.

For example    

if (vampire) { // vampire is a boolean

useWoodenStake();  }


Curly brackets ({}) define a block of code (in Java, Scala, Groovy, and JavaScript). To define what should happen if your condition is false, you use the else keyword.

if (vampire) {
             } else {

Actually, this can be shortened, because we only have one statement per condition.

 if (vampire) useWoodenStake();

else useAxe();


But it’s generally better to use the curly-bracket style in Java. If you have multiple conditions you have to test for, you can use the else if style, such as the following 

if  (vampire) useWoodenStake();
else if (zombie) useBat();
 else useAxe();


switch Statements

Sometimes you have so many conditions that your else if statements span several pages. In this case, you might consider using the switch keyword. It allows you to test for several different values of the same variable. For example

switch (monsterType) {
             case "Vampire" useWoodenStake(); break;
             case "Zombie" useBat(); break;
             case "Orc" shoutInsult();
             default useAxe();


The case keyword denotes the value to be matched.

The break keyword always causes the program to exit the current code block. This is necessary in a switch statement; otherwise, every statement after the case will be executed. For example, when the monster type is "Orc", shout insults and useAxe are executed. 


The default keyword denotes the code to execute if none of the cases is matched. It is much like the final else block of an if/else block. There is more to switch statements, but this involves concepts I’ll cover later on, so we’ll return to this topic.


Boolean Logic


Computers use a special kind of math called Boolean logic (it’s also called Boolean algebra).

All you really need to know are the following three Boolean operators and six comparators &&—AND True only if left and right values are true.

||—OR y if either left or right value is true.
!—NOT Negates a Boolean (true becomes false; false becomes true.
== Equals
!= Does not equal
< Less than
> Greater than
<=Less than or equal>= Greater than or equal


Conditions (such as if) operate on Boolean values (true/false)—the same boolean type that you learned about in Section 3. When used properly, all the preceding operators result in a Boolean value.


For example

if (age > 120 && skin == Pale && !winkled) {
probablyVampire(); }



 The two simplest ways to loop are the while loop and do/while loop. The while loop simply repeats until the loop condition becomes false.

boolean repeat = true;
while (repeat) {
repeat = false;


The preceding would call the doSomething() method once. The loop condition in the preceding code is repeated. This is a simple example. Usually, the loop condition would be something more complex. The do loop is like the while loop, except that it always goes through at least one time. For example

boolean repeat = false;
do {
} while(repeat);
It’s often helpful to increment a number in your loop, for example
int i = 0;
while (i < 10) {


The preceding loop can be condensed using the for a loop.

for  (int  i = 0; i < 10; i++) {


The for loop has an initiation clause, a loop condition, and an increment clause.

 This style of the loop is useful for looping through an array with an index. For example

String[] strArray = {"a", "b", "c"};
for (int i = 0; i < strArray.length; i++)


This would print “ABC.” The preceding loop is equivalent to the following

int i = 0;

while (i < strArray.length) {
String str = strArray[i];


 In Java, you can write for loops in a more concise way for an array or collection (list or set). For example

String[] strArray = {"a", "b", "c"};
for  (String str strArray)

This is called a for each loop. Note that it uses a colon instead of a semicolon.



A method is a series of statements combined into one block inside a class and given a name. In the Cold War days, these were called sub-routines, and many other languages call them functions. However, the main difference between a method and a function is that a method has to be associated with a class, whereas a function does not.


Call Me

Methods exist to be called. You can think of a method as a message that is sent or command is given. To call a method (also known as invoking a method), you simply write the name of the object, a dot, then the method name.

For example

Dragon dragon = new  Dragon();; // dragon is the object, and fly is the method The fly method would be defined within the Dragon class.
public void fly() { // flying code }


 In Java, void means that no result is returned.

Methods can also have parameters. A parameter is a value (or reference value) that is part of a method call. Together, the method’s name and parameters are called the method signature. For example, the following method has two parameters

public void fly(int x, int y) {

 // fly to that x, y coordinate.




non java

Other languages define methods (or functions) differently. For example, in Groovy, you can use the def keyword to define a method (in addition to Java’s normal syntax), as follows

def fly() { println("flying") }

Scala also uses the def keyword to define a method, but you also need an equal (=) sign.

def fly() = { println("flying") }

JavaScript uses the function keyword to define a function

 function fly() { alert("flying") }


Break It Down

Methods also exist to organize your code. One rule of thumb is to never have a method that is longer than one screen. It makes no difference to the computer, but it makes all the difference to humans (including you).


 It’s also very important to name your method well. For example, a method that fires an arrow should be called “fire arrow,” and not “fire,” “arrow,” or “arrowFartBigNow.” This may seem like a simple concept, but you might be surprised by how many people fail to grasp it.


Return to Sender

Often, you will want a method to return a result. In Java, you use the return keyword to do this.


For example

public Dragon makeDragonNamed(String name) {
 return new Dragon(name);


Once the return statement is reached, the method is complete. Whatever code called the method will resume execution. In some languages, such as Groovy and Scala, the return keyword is optional. Whatever value is put on the last line will get returned.

For example (Groovy)

def makeDragonNamed(name) {

new Dragon(name)




 In Java, a static method is a method that is not linked to an object instance. However, it must be part of a class. For example, the random() method in the java.util.Math class we learned about earlier is a static method.

To declare a static method, you simply add the word static, as in the following

public static String makeThemFight(Dragon d, Vampire v)

// a bunch of code goes here.


Because Java is an object-oriented programming language (OOP), in theory, static methods should be used sparingly, because they are not linked to any object. However, in real life, you will see them a lot.



Varargs, or “variable arguments,” allow you to declare a method’s last parameter with an ellipsis (...), and it will be interpreted to accept any number of parameters (including zero) and convert them into an array in your method. For example, see the following code

void printSpaced(Object... objects) {
             for (Object o objects) System.out.print(o + " ");

 Putting it all together, you can have the following code (with output in comments)
        printSpaced("A", "B", "C"); // A B C
       printSpaced(1, 2, 3); // 1 2 3


Main Method

 Now that you know about static methods, you can finally run a Java program (sorry it took so long). Here’s how you create an executable main method in Java

 import static java.lang.System.out;
/** Main class. */
public class Main {
public static void main(String ... args) {
out.println("Hello World!");


 Then, to compile it, open your command prompt or terminal and type the following

  • javac
  • java Main


Or, in NetBeans, do the following

  • Right-click the Main class.
  •  Choose Run File.


Polymorphic Spree

The title of this part is a play on the name of the band Polyphonic Spree. The term polymorphism refers to a principle in biology according to which an organism or species can have many different forms or stages.


This principle can also be applied to object-oriented programming (OOP) languages such as Java. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.



 Inheritance is a good way to share functionality between objects. When a class has a parent class, we say it inherits the fields and methods of its parent. In Java, you use the extends keyword to define the parent of a class.

For example

public class Griffon extends FlyingCreature {


 Another way to share functionality is called composition. This means that an object holds a reference to another object and uses it to do things.


For example

class Griffon {
Wing leftWing = new Wing()
Wing rightWing = new Wing()
def fly() {


 This way, you can also have a Bird class that also uses the Wing class, for example.



 What is an object anyway? An object is an instance of a class (in Java, Groovy, and Scala). In Java, classes have constructors, which can have multiple parameters for initializing the object. For example, see the following

class FlyingCreature {
String name;
// constructor
public FlyingCreature(String name) { = name;


The constructor of FlyingCreature has one parameter, name, which is stored in the name field. A constructor must be called using the new keyword, to create an object.


for example

String name = "Bob";
FlyingCreature fc = new  FlyingCreature(name);

Once an object is created, it can be passed around (this is called a pass by reference). Although String is a special class, it is a class, so you can pass around an instance of it, as shown in the preceding code.




 In JavaScript, a constructor is a function used to define a prototype. Inside the constructor, the prototype is referred to using this keyword. For example, you could define a Creature in JavaScript, as follows

function Creature(n) { = n;
var bob = new Creature('Bob');



A parent class defines shared functionality (methods) and state (fields) that are common to multiple classes. For example, let’s create a FlyingCreature class that defines a fly() method and has a name.

class FlyingCreature {

String name;
public FlyingCreature(String name) { = name;
public void fly() {
System.out.println(name + " is flying");
class Griffon extends FlyingCreature {
public Griffon(String n) { super(n); }
class Dragon extends FlyingCreature {
public Dragon(String n) { super(n); }
public class Parenting {
public static void main(String ... args) {
Dragon d = new Dragon("Smaug");
Griffon g = new Griffon("Gilda");; // Smaug is flying; // Gilda is flying


There are two classes in the preceding code, Griffon and Dragon, that extend FlyingCreature. FlyingCreature is sometimes referred to as the base class. Griffon and Dragon are referred to as subclasses. Keep in mind that you can use the parent class’s type to refer to any subclass.


For example, you can make any flying creature fly, as follows   

FlyingCreature creature = new Dragon("Smaug");; // Smaug is flying


This concept is called extension. You extend the parent class (FlyingCreature, in this case). In JavaScript, we can use prototypes to extend functionality. For example, let’s say we have a prototype called Undead.

function Undead() {

this.dead = false; = false;
Now let’s create two other constructors, Zombie and Vampire.
function Zombie() {;
this.deseased = true; = function() { alert("BRAINS!") }
Zombie.prototype = Object.create(Undead.prototype);
function Vampire() {;
this.pale = true; = function() { alert("BLOOD!") }
Vampire.prototype = Object.create(Undead.prototype);


Note how we set Zombie’s and Vampire’s prototype to an instance of the Undead prototype. This allows zombies and vampires to inherit the properties of Undead while having different talk functions, as follows

var zombie = new Zombie();
var vamp = new Vampire();; //BRAINS
zombie.deseased; // true; //BLOOD
vamp.pale; //true
vamp.dead; //false




 In Java (and related languages, Groovy, and Scala), a package is a namespace for classes. A namespace is just shorthand for a bin of names. Every modern programming language has some type of namespace feature.


This is necessary, owing to the nature of having lots and lots of classes in typical projects. As you learned in Section 3, the first line of a Java file defines the package of the class. 

for example  package com.github.modernprog;


Also, there is a common understanding that a package name corresponds to a URL (, in this case). However, this is not necessary.


Public Parts

You might be wondering why the word public shows up everywhere in the examples so far. The reason has to do with encapsulation. Encapsulation is a big word that just means “a class should expose as little as possible to get the job done” (some things are meant to be private). This helps reduce the complexity of code and, therefore, makes it easier to understand and think about.


 There are three different keywords in Java for varying levels of “exposure.”

  • Private Only this class can see it.
  • Protected Only this class and its descendants can see it.
  • Public Everyone can see it.


There’s also “default” protection (absent of a keyword), which limits use to any class in the same package. This is why classes tend to be declared public, because, otherwise, their usage would be very limited. However, a class can be private, for example, when declaring a class within another class, as follows

public class Griffon extends FlyingCreature {

private class GriffonWing {}



JavaScript does not have the concept of packages, but, instead, you must rely on scope. Variables are only visible inside the function they were created in, except for global variables.


[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]




An interface declares method signatures that will be implemented by classes that extend the interface. This allows Java code to work on several different classes without necessarily knowing what specific class is “underneath” the interface.


For example, you could have an interface with one method, as follows

 public interface  Beast  {

int getNumberOfLegs(); // all interface methods are public 3    }


Then you could have several different classes that implement that interface.

public class Griffon extends FlyingCreature implements Beast {

public int getNumberOfLegs() { return 2; }
public class Unicorn implements Beast {
public int getNumberOfLegs() { return 4; }


Note  JavaScript does not have an equivalent concept to the interface.


Abstract Class

An abstract is a class that can have abstract methods but cannot have instances. It is something like an interface with functionality, however, a class can only extend one superclass, while it can implement multiple interfaces.


For example, to implement the preceding Beast interface as an abstract class, you can do the following

 public abstract class Beast {

 public abstract int getNumberOfLegs();


 Then you could add non-abstract methods and/or fields.



 In Java, the enum keyword creates a type-safe, ordered list of values.

For example

public enum BloodType {

An enum variable can only point to one of the values in the enum.


For example

BloodType type = BloodType.A;

 The enum is automatically given a bunch of methods, such as            

  • values() Gives you an array of all possible values in the enum (static)
  • valueOf(String) Converts the given string into the enum value with the given name 
  • name() An instance method on the enum that gives its name Also, enums have special treatment in switch statements.


For example, in Java, you can use an abbreviated syntax (assuming type is a BloodType).

switch (type) {

case VAMPIRE return vampire();
case UNICORN return unicorn();
default return human();



Java annotations allow you to add meta-information to Java code that can be used by the compiler, various APIs, or even your own code at runtime. The most common annotation you will see is the @Override annotation, which declares to the compiler that you are overriding a method. For example


public String toString() {
return "my own string";


This is useful because it will cause a compile-time error if you mistype the method name, for example. Other useful annotations are those in javax. annotation, such as @Nonnull and @ Nonnegative, which declare your intentions. Annotations such as @Autowired and @Inject are used by direct-injection frameworks such as Spring and Google Guice,1 respectively, to reduce “wiring” code.




Although Java is an object-oriented language, this sometimes conflicts with its primitive types (int, long, float, double, etc.). For this reason, Java added autoboxing and unboxing to the language.


The Java compiler will automatically wrap a primitive type in the corresponding object when it’s necessary, for example, when passing in parameters to a function or assigning a variable, as in the following Integer number = 1.



This is simply the reverse of autoboxing. The Java compiler will unwrap an object to the corresponding primitive type, when possible. For example, the following code would work double d = new Double(1.1) + new Double(2.2).


Design Patterns

 In object-oriented programming (OOP), design patterns are useful organizations of state and behavior that make your code more readable, testable, and extensible.



The observer pattern allows you to broadcast information from one class to many others, without them having to know about each other directly. It is often used with events. For example, the KeyListener, MouseListener, and many other “Listener” interfaces in Java Swing implement the observer pattern and use events.


Another example of this pattern is the Observable class and Observer interfaces supplied in Java. Here is a simple example that simply repeats the same event forever

import java.util.Observable;
public class EventSource extends Observable implements Runnable { 4 @Override
public void run() {
while (true) {


Although the event is simply a string in this example, it could be of any type. The following class implements the Observer interface and prints out any events of type String

import java.util.Observable;

import java.util.Observer; /* this is Event Handler */
public class StringObserver implements Observer {
public void update(Observable obj, Object event) {
if (event instanceof String) {
System.out.println("nReceived Response " + event );
To run this example, simply do the following
final EventSource eventSource = new EventSource();
// create an observer
final StringObserver stringObserver = new StringObserver();
// subscribe the observer to the event source
// starts the event thread
Thread thread = new Thread(eventSource);



Model–view–controller (MVC) is possibly the most popular software design pattern.


As the name suggests, it consists of three major parts

  • Model The data or information being shown and manipulated
  • View What actually defines how the model is shown to the user
  • Controller Defines how actions can manipulate the model


This design allows the controller, model, and view to know very little about each other. This reduces coupling—the degree to which different components of the software rely on other components. When you have a low coupling, your software is easier to understand and easier to extend. We will look at a great example of MVC when I talk about grails.



A domain specific language (DSL) is a custom programming language made for a specific domain. For example, you can think of HTML as a DSL for displaying web pages.


Some languages allow you such freedom that you can create a DSL inside the language. For example, Groovy and Scala allow you to override the math symbols (+, -, etc.).


The other freedoms of these languages (optional parentheses and semicolons) allow for DSL-like interfaces. We call these DSL-like interfaces fluent interfaces. You can also create fluent interfaces in Java and other languages.




 Within Groovy, you can take a block of code (a closure) as a parameter and then call it, using a local variable as a delegate. For example, imagine that you have the following code for sending SMS texts

class SMS {
def from(String fromNumber) {
// set the from
def to(String toNumber) {
// set the to
def body(String body) {
// set the body of text
def send() {
// send the text.


In Java, you’d have to use this the following way

SMS m = new SMS();

m.body("Hey there!");


In Groovy, you can add the following static method to the SMS class for DSL-like usage

def static send(block) {

SMS m = new SMS()
block.delegate = m
This sets the SMS object as a delegate for the block, so that methods are forwarded to it. With this you can now do the following 1 SMS.send {
from '555-432-1234'
to '555-678-4321'
body 'Hey there!'


Overriding Operators

 In Scala or Groovy, you could create a DSL for calculating speeds with specific units, such as meters per second.

val time = 20 seconds
val dist = 155 meters
val speed = dist / time
println(speed.value) // 7.75


By overriding operators, you can constrain users of your DSL to reduce errors. For example, time/dist would cause a compilation error in this DSL.

Here’s how you would define this DSL in Scala

class Second(val value Float) {}

class MeterPerSecond(val value Float) {}
class Meter(val value Float) {
def /(sec Second) = {
new MeterPerSecond(value / sec.value)
class EnhancedFloat(value Float) {
def seconds = {
new Second(value)
def meters = {
new Meter(value)
implicit def enhanceFloat(f Float) = new EnhancedFloat(f) Scala has the implicit keyword, which allows the compiler to do implicit conversions for you.


Notice how the divide/operator is defined just like any other method. In Groovy, you overload operators by defining methods with special names1 such as plus, minus, multiply, div, etc.



The actor design pattern is a useful pattern for developing concurrent software. In this pattern, each actor executes in its own thread and manipulates its own data. The data cannot be manipulated by anyone else. When data can only be changed by one thread at a time, we call it thread-safe.

There are many implementations of this pattern that you can use, including the following

  •  Akka
  • Jetlang
  •  FunctionalJava
  • GPars


Functional Programming

Functional Programming

Functional programming (FP) is a programming style that focuses on functions and minimizes changes of state (using immutable data structures). It is closer to expressing solutions mathematically, rather than through step-by-step instructions.


In FP, functions should be “side-effect free” (nothing outside the function is changed) and referentially transparent (a function returns the same value every time when given the same arguments).


FP is an alternative to the more common imperative programming, which is closer to telling the computer the steps to follow. Although functional-programming could be achieved in Java pre-Java-8,1 Java 8 enabled language-level FP support with lambda expressions and functional interfaces.


Java 8, JavaScript, Groovy, and Scala all support functional-style programming, although they are not FP languages.

Note  Prominent functional programming languages such as Common Lisp, Scheme, Clojure, Racket, Erlang, OCaml, Haskell, and F# have been used in industrial and commercial applications by a wide variety of organizations. Clojure2 is a Lisp-like language that runs on the JVM.


 Functions and Closures


Of course, “functions as a first-class feature” is the basis of functional programming. The first-class feature means that a function can be used anywhere a value can be used.

For example, in JavaScript, you can assign a function to a variable and call it

var func = function(x) { return x + 1; }

var three = func(2); //


Although Groovy doesn’t have first-class functions, it has something very similar closures. A closure is simply a block of code wrapped in curly brackets with parameters defined left of the -> (arrow).

For example

def closr = {x -> x + 1}

println( closr(2) ); //3

If a closure has one argument, it can be referenced as it in Groovy.

For example

def closr = {it + 1}


Java 8 introduced the lambda expression, which is something like a closure that implements an interface. The main syntax of a lambda expression is “parameters -> body.” The Java compiler uses the context of the expression to determine which functional interface is being used (and the types of the parameters).

For example

Function<Integer,Integer> func = x -> x + 1;

int three = func.apply(2);


Here, the functional interface is Function, which has the apply method. The return value and parameter type of both Integers, thus Integer, Integer, are the generic type parameters.


In Java 8, a functional interface is defined as an interface with exactly one abstract method. This even applies to interfaces that were created with previous versions of Java.

In Scala, everything is an expression, and functions are a first-class feature. Here’s a function example in Scala

var  f =  (x  Int) =>  x + 1;



Although both Java and Scala are statically typed, Scala actually uses the right-hand side to infer the type of function being declared, whereas Java does the opposite. In Java, Groovy, and Scala, the return keyword can be omitted, if there is one expression in the function/closure. However, in Groovy and Scala, the return keyword can also be omitted, if the returned value is the last expression.



Immutability and FP go together like peanut butter and jelly. Although it’s not necessary, they blend nicely. In purely functional languages, the idea is that each function has no effect outside itself—no side effects.


This means that every time you call a function, it returns the same value given the same inputs. To accommodate this behavior, there are immutable data-structures. An immutable data-structure cannot be directly changed but returns a new data-structure with every operation.


For example, as you learned earlier, Scala’s default Map is immutable.

val map = Map("Smaug" -> "deadly")
val map2 = map + ("Norbert" -> "cute")
println(map2) // Map(Smaug -> deadly, Norbert -> cute) So, in the preceding, map would remain unchanged.


Each language has a keyword for defining immutable variables (values).

  • Scala uses the value keyword to denote immutable values, as opposed to var, which is used for mutable variables.
  • Java has the final keyword for declaring immutable variables.
  • In addition to the final keyword, Groovy includes the @Immutable annotation3 for declaring a whole class immutable.
  • JavaScript uses the const keyword.


For example (in Groovy)

public class Centaur {
final String name
public Centaur(name) {}
Centaur c = new Centaur("Bane");
println( // Bane = "Firenze" //error


This works for simple references and primitives, such as numbers and strings, but for things such as lists and maps, it’s more complicated. For these cases, open source immutable libraries have been developed for the languages in which it’s not included, such as the following

  • Guava5 for Java and Groovy
  • Immutable-JS6 for JavaScript


 Java 8


In Java 8, the Stream interface was introduced. A stream is like an improved iterator that supports chaining methods to perform complex operations.


To use a stream, you must first create one in one of the following ways

  • Collection's stream() method or parallelStream() method These create a stream backed by the collection.
  • method Used for converting arrays to streams


  • Stream.generate(Supplier<T> s) Returns an infinite sequential stream in which each element is generated by the given supplier •     Stream.iterate(T seed, UnaryOperator<T> f) Returns an infinite sequential ordered stream produced by iterative application of a function to an initial element seed, producing a stream consisting of seed, f(seed), f(f(seed)), etc.


 Once you have a stream, you can then use a filter, map, and reduce operations to concisely perform calculations on the data. For example

String longestName =
             .filter(d -> != null)
             .map(d ->
             .reduce((n1, n2) -> n1.length() > n2.length() ? n1 n2)



 In Groovy, findAll and other methods are available on every object but are especially useful for lists and sets. The following method names are used in Groovy


  • findAll Much like a filter, it finds all elements that match a closure.
  • collect Much like a map, this is an iterator that builds a collection.
  • inject Much like reduce, it loops through the values and returns a single value.
  • each Iterates through the values using the given closure
  • eachWithIndex Iterates through with two parameters value and an index
  • find Finds the first element that matches a closure
  • findIndexOf Finds the first element that matches a closure and returns its index
  • any True if any element returns true for the closure
  • every True if all elements return true for the closure


For example, the following assumes dragons is a list of dragon objects

String longestName = dragons.
             findAll { != null }.
             collect { }.
             inject("") { n1, n2 -> n1.length() > n2.length() ? n1 n2 }

Remember that it in Groovy can be used to reference the single argument of a closure.




 Scala has many such methods on its built-in collections, including the following

  •  map Converts values
  • flatMap Converts values and then concatenates the results together
  • filter Limits the returned values, based on some Boolean expression
  • find Returns the first value matching the given predicate
  • forAll True only if all elements match the given predicate
  • exists True if at least one element matches the given predicate
  • foldLeft Reduces the values to one value using the given closure, starting at the last element and going left
  • foldRight Same as foldLeft, but starting from the first value and going up


For example, you can use the map to perform an operation on a list of values, as follows

 val list = List(1, 2, 3)  * 2) // List(2, 4, 6)


Much like it in Groovy, in Scala, you can use the underscore to reference a single argument.

Assuming dragons is a List of dragon objects, you can do the following in Scala

var longestName = dragons.filter(_ != null).map("")( 2    (n1String,n2String) => if (n1.length() > n2.length()) n1 else n2)



Refactoring means changing the code in a way that has no effect on functionality. It is only meant to make the code easier to understand or to prepare for some future addition of functionality, For example, sometimes you refactor code to make it easier to test. There are two categories of refactoring I am going to cover, Object-Oriented and Functional, corresponding to the two different programming styles.


Object-Oriented Refactoring

Object-Oriented Refactoring

The following actions are common refactorings in OOP

  • Changing a method or class name (renaming)
  • Moving a method from one class to another (delegation)
  • Moving a field from one class to another
  • Creating a new class using a set of methods and fields from a class
  • Changing a local variable to a class field
  • Replacing a bunch of literals (strings or numbers) with a constant (static final) 
  • Moving a class from an anonymous class to a top-level class
  • Renaming a field


Functional Refactoring

 The following actions are common refactorings in FP

  • Renaming a function
  • Wrapping a function in another function and calling it
  • Inline a function wherever it is called
  • Extract common code into a function (the opposite of the previous.
  •  Renaming a function parameter
  • Adding a parameter


 You might notice some similarities between both lists. The principles of refactoring are universal.

Refactoring Examples

Refactoring Examples

Here are some examples of refactoring code


Renaming a Method

public static void main(String...args) {
public static void animateDead() {}
public static void main(String...args) {
public static void doCoolThing() {}


Moving a Method from One Class to Another Before


Replacing a Bunch of Literals (Strings or Numberswith a Constant (Static FinalBefore

public static void main(String...args) {

public static void animateDead(int n) {}
public static final int NUM = 123;
public static void main(String...args) {
public static void animateDead(int n) {}


Renaming a Function


function castaNastySpell() { /* cast a spell here */ }


function castSpell() { /* cast a  spell here  */ }


Wrapping a Function in Another Function and Calling It Before

castSpell('my cool spell');
(function(spell) { castSpell(spell) })('my cool spell'); 11.3.6 Inline a Function Wherever It Is Called
function castSpell(spell) { alert('You cast ' + spell); } 2 castSpell('crucio');
alert('You cast ' + 'crucio');
alert('You cast ' + 'expelliarmus');


Extract Common Code into a Function Before

alert('You cast crucio');

alert('You cast expelliarmus');


 function castSpell(spell) { alert('You cast ' + spell); } 2  castSpell('crucio');



The java.util package contains many useful classes for everyday programming. Likewise, JavaScript and other languages come with many built-in objects for doing common tasks. I am going to cover a few of these.


Dates and Times


You should never store date values as text. It’s too easy to mess up. Java 8 comes with a new and improved Date-Time application program interface (API) that is much safer, easier to read, and more comprehensive than the previous API. For example, creating a date looks like the following 

LocalDate date = LocalDate.of(2014, Month.MARCH, 2);


There’s also a LocalDateTime class to represent date and time, LocalTime to represent only time, and ZonedDateTime to represent time with a time zone.


Before Java 8, there were only two built-in classes to help with dates Date and Calendar. These should be avoided.

  •  The date actually represents both a date and time.
  • The calendar is used to manipulate dates.


In Java 7, you’d have to do the following to add five days to a date  

Calendar cal = Calendar.getInstance();


cal.add(5, Calendar.DAY);


Groovy Date

Groovy has a bunch of built-in features that make dates easier to work with. For example, numbers can be used to add/subtract days, as follows def date = new Date() + 5; //adds 5 days


Groovy also has TimeCategory1 for manipulating dates and times. This lets you add and subtract any arbitrary length of time. For example

import groovy.time.TimeCategory

now = new Date()
println now
use(TimeCategory) {
nextWeekPlusTenHours = now + 1.week + 10.hours - 30.seconds 6 }
println nextWeekPlusTenHours


A Category is a class that can be used to add functionality to other existing classes.  In this case, TimeCategory adds a bunch of methods to the Integer class.



This is one of the many meta-programming techniques available in Groovy. To make a category, you create a bunch of static methods that operate on one parameter of a particular type (e.g., Integer). When the category is used, that type appears to have those methods. The object on which the method is called is used as the parameter. Take a look at the documentation for TimeCategory for an example of this in action.


JavaScript Date


 JavaScript also has a Date object.

 You can create an instance of a Date object in several ways (these all create the same date)

Date.parse('June 13, 2014')
new Date('2014-06-13')
 new Date(2014, 5, 13)

Note that if you adhere to the international standard (yyyy-MM-dd), a UTC time zone will be assumed; otherwise, it will assume you want a local time. As usual with JavaScript, the browsers all have slightly different rules, so you have to be careful with this.


Don’t ever use getYear in both Java and JavaScript, the Date object’s getYear() method doesn’t do what you think and should be avoided. For historical reasons, getYear does not actually return the year (e.g., 2014). You should use getFullYear() in JavaScript and LocalDate or LocalDateTime in Java 8.


Java Date Format

Although DateFormat is in java.text, it goes hand-in-hand with java.util.Date.The SimpleDateFormat is useful for formatting dates in any format you want.

For example

SimpleDateFormat sdf = new  SimpleDateFormat("MM/dd/yyyy");

Date date = new  Date();


This would format a date per the US standard month/day/year.



 In Java, Currency is useful if your code has to deal with currencies in several countries. It provides the following methods

getSymbol() Currency symbol for the default locale
getSymbol(Locale) Currency symbol for the given locale
static getAvailableCurrencies() Returns the set of available currencies.


 For example

String pound = Currency.getSymbol(Locale.UK);




In Java 8, time zones are represented by the java.time.ZoneId class. There are two types of ZoneIds, fixed offsets, and geographical regions. This is to compensate for practices such as daylight saving time, which can be very complex.


You can get an instance of a ZoneId in many ways, including the following two

ZoneId mountainTime = ZoneId.of("America/Denver");

ZoneId myZone = ZoneId.systemDefault();


To print out all available IDs, use getAvailableZoneIds(), as follows


Write a program that does this and run it.



The scanner can be used to parse files or user input. It breaks the input into tokens, using a given pattern, which is whitespace by default (“white space” refers to spaces, tabs, or anything that is not visible in the text).

For example, use the following to read two numbers from the user

System.out.println("Please type two numbers");
             Scanner sc = new Scanner(;
             int num1 = sc.nextInt();
             int num2 = sc.nextInt();


Write a program that does this and try it out.


The build process is one of compiling the source files of a project and producing a finished product. In some companies, there are whole teams whose sole job is the build process. There are many other build tools, but I’m just going to cover three

  • Ant
  • Maven
  • Gradle



Ant is the first really popular project builder for Java that existed. It is XML-based and requires you to create tasks in XML that can be executed by Ant. A task is a division of work. Tasks depend on other tasks. For example, the “jar” task usually depends on the “compile” task. Although Maven threw away the task concept, it was used again in Gradle. Critics of Ant complain that it uses XML (a much-loathed format) and requires a lot of work to do simple things.



 Maven is an XML-based declarative project manager. Maven is used for building Java projects but is capable of much more. Maven is also a set of standards that allows Java/ JVM developers to easily define and integrate dependencies into large projects. Maven somewhat replaces Ant but can also integrate with it and other build tools.


Maven was mostly a reaction to the huge number of open source libraries Java projects tend to rely on. It has a built-in standard for dependency management (managing the interdependencies of open source libraries).


Although Maven is an Apache open source project, it could be said that the core of Maven is Maven Central, a repository of open source libraries run by Sonatype, the company behind Maven. There are many other repositories that follow the Maven standard, such as JFrog’s jCenter, so you are not restricted to Maven Central.

Ivy is a similar build tool but is more closely related to Ant. Many build tools, such as Ivy and Gradle, build on top of Maven’s concept.


Using Maven

The main file that defines a Maven project is the POM (Project Object Model). The POM file is written in XML and contains all of the dependencies, plug-ins, properties, and configuration data that is specific to the current project. The POM file is generally composed of the following

  • Basic properties (artifactId, groupId, name, version, packaging)
  • Dependencies
  • Plug-ins

There is a Maven plug-in for every major Java-based IDE out there (Eclipse, NetBeans, and IntelliJ IDEA), and they are very helpful. You can use the Maven plug-in to create your project, add dependencies, and edit your POM files.


Starting a New Project

 Starting a New Project

There is a simple way to create a new configuration file (pom.xml) and project folders using the archetype generates command.

mvn archetype generates


That will list all the different kinds of projects you can create. Pick a number representing the type of project you want (there are 726 options right now), then answer some questions regarding the name of your project. After that process, run the following command to build the project

mvn package

If you want to use any additional third-party libraries, you will have to edit the POM to include each dependency. Fortunately, most IDEs make it easy to add dependencies to the POM.


Life Cycle

Maven uses a declarative style (unlike Ant, which uses a more imperative approach). This means that instead of listing the steps to take, you describe what should happen during certain phases of the build. The phases in Maven are as follows

  • validate Validates that the project is correct and all necessary information is available
  • compile Compiles the source code of the project
  •  test Tests the compiled source code, using a suitable unit-testing framework


  • package Takes the compiled code and packages it in its distributable format, such as a JAR
  • integration-test Processes and deploys the package, if necessary, into an environment in which integration tests can be run
  •  verify Runs any checks to verify that the package is valid and meets quality criteria


  • install Installs the package into the local repository, for use as a dependency in other projects locally
  • deploy Copies, in an integration or release environment, the final package to the remote repository, for sharing with other developers and projects There are more phases,7 but you don’t need to know all of them until you are doing more complex builds.


Executing Code


Sometimes, however, you just need more control over your build. In Maven, you can execute Groovy code, Ant build files, Scala code, and you can even write your own plug-ins in Groovy.

For example, you can put Groovy code in your POM file in the following way

def depFile = new File(, 'deps.txt') 14
project.dependencies.each() {
depFile.write("${it.groupId}${it.artifactId}${it. version}") 17 }
ant.copy(todir ) {


The preceding code would write out every dependency of the project into the file deps.txt. Then it would copy all of the source files into the outputDirectory (usually target/classes).



Gradle is a Groovy-based DSL (domain specific language) system for building projects. The Gradle website describes it as follows. Gradle combines the power and flexibility of Ant with the dependency management and conventions of Maven into a more effective way to build. Powered by a Groovy DSL and packed with innovation, Gradle provides a declarative way to describe all kinds of builds through sensible defaults. —


Projects and Tasks

Each Gradle build is composed of one or more projects, and each project is composed of tasks. The core of the Gradle build is the build. gradle file, which is called the build script. Tasks are defined by writing task, then a task-name followed by a closure.

For example 

task upper {
             String someString = 'test'
             println "Original $someString"
             println "Uppercase " + someString.toUpperCase()


Tasks can contain any Groovy code, but you can take advantage of existing Ant tasks; for example ant.loadfile(class='lazy' data-srcFile file, property 'x') //loads file into x ant.checksum(file file, property "z") // put checksum into z println["z"] //accesses ant property z The preceding code would load a file into Ant-property "x", save the file’s checksum in Ant-property "z", and then print out that checksum.


Much as in Ant, a task can depend on other tasks, which means they must be run before the task. You simply call dependsOn with any number of task names as arguments. For example

task buildApp {

depends on clean, installApp, process assets




The gradle core has very little built-in. It has powerful plug-ins to allow it to be very flexible.

 A plug-in can do one or more of the following

  • Add tasks to the project (e.g., compile, test)
  •  Pre-configure added tasks with useful defaults
  • Add dependency configurations to the project

Add new properties and methods to an existing type, via extensions We’re going to concentrate on building Java-based projects, so we’ll be using the Java plug-in; however, Gradle is not limited to Java projects!


apply plugin 'java'

This plug-in uses Maven’s conventions. For example, it expects to find your production source code under class='lazy' data-src/main/java and your test source code under class='lazy' data-src/test/java.


Maven Dependencies

 Every Java project tends to rely on many open source projects to be built. Gradle builds on Maven, so you can easily include your dependencies, using a simple DSL, such as in the following example

apply plugin 'java'
          sourceCompatibility = 1.7
         repositories {
           dependencies {
          compile ''
          compile 'org.bitbucket.dollardollar1.0-beta2'
          testCompile group 'junit', name 'junit', version '4.+'
          testCompile "org.mockitomockito-core1.9.5"

This build script uses sourceCompatibility to define the Java source code version of 1.7 (which is used during compilation). Next, it tells Maven to use the local repository first (mavenLocal), then Maven Central.


In the dependencies block, this build script defines two dependencies for the compile scope and two for the testCompile scope. Jars in the testCompile scope are only used in tests and won’t be included in any final products. The line for JUnit shows the more verbose style for defining dependenciesOnline Documentation  Gradle has a huge online user guide available online at 




Testing is a very important part of software creation. Without automated tests, it’s very easy for bugs to creep into the software. In fact, some go as far as to say that you should write tests before you write the code. This is called TDD (test-driven development).


Types of Tests

 The following are different types of tests you might write

  • Unit test Test conducted on a single API call or some isolated code
  •  Integration test Test of a higher order code that requires a test harness, mocking, etc.
  • Acceptance test High-level test that matches the business requirements


  • Compatibility Making sure that things work together
  • Functionality Ensuring that stuff works
  •  Black box Test conducted without knowing/thinking about what’s going on in the code


  • White box Tests are written with the inside of code in mind • Gray box Hybrid of black and white box testing
  • Regression Creating a test after finding a bug, to ensure that the bug does not reappear
  • Smoke A huge sampling of data


 •    Load/Stress/Performance How the system handles load The type and number of tests you write vary, based on a number of factors. The simpler a piece of code is, the less testing it requires. For example, a “getter” or “setter” does not require a test at all.




JUnit is a simple framework to write repeatable tests.

A typical JUnit 4.x test consists of multiple methods annotated with the @Test annotation. At the top of every JUnit test class, you should include all the static Assert methods, and annotations, like so

import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;


Use @Before, to annotate initialization methods that are run before every test, and @After, to annotate breakdown methods that are run after every test.


Each test method should test one thing, and the method name should reflect the purpose of the test. For example

public void toStringYieldsTheStringRepresentation() {
String[] array = {"a", "b", "c"};
ArrayWrapper<String> arrayWrapper = new ArrayWrapper<String>(array);
assertEquals("[a, b, c]", arrayWrapper.toString());



 In more recent versions (JUnit 4.4+2), JUnit also includes Hamcrest matchers.

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
You can create more readable tests using the Hamcrest core matchers. For example
public void sizeIs10() {
assertThat(wrapper.size(), is(10));



Often, there are variables outside of a test that are beyond your control but which your test assumes to be true. When an assumption fails, it shouldn’t necessarily mean that your test fails. For this purpose, JUnit added assume that, which you may import, like so 1   import static org.junit.Assume.*;


You can verify assumptions before your assertions in your tests. For example

assume that(File.separatorChar, is('/'));

When an assumption fails, the test is either marked as passing or ignored, depending on the version of JUnit Input/Output




In Java, the class is used to represent files and directories. For example

File file = new  File("path/file.txt");

File dir = new File("path/"); //directory


Java 7 added several new classes and interfaces for manipulating files and filesystems. This new application program interface (API) allows developers to access many low-level OS operations that were not available from the Java API before, such as the WatchService and the ability to create links (in Linux/Unix operating systems).


Paths are used to more consistently represent file or directory paths.

Path path = Paths.get("/path/file");

This is shorthand for the following

Path path = FileSystems.getDefault().getPath("/path/file");


The following list defines some of the most important classes and interfaces of the API Files This class consists exclusively of static methods that operate on files, directories, or other types of files.

  • Paths This class consists exclusively of static methods that return a path by converting a path string or URI.
  • WatchService An interfaces for watching various file-system events, such as create, delete, modify.


Reading Files

To read a text file, use BufferedReader.

public void readWithTry() {
Charset utf = StandardCharsets.UTF_8;
try (BufferReader reader = Files.newBufferedReader(path, utf)) {
for (String line = br.readLine(); line != null; line = br.readLine())
} catch (IOException e) {

The new automatic resource management feature of Java 7 makes dealing with resources, such as files, much easier. Before Java 7, users needed to explicitly close all open streams, causing some very verbose code. By using the preceding try statement, BufferedReader will be closed automatically.


However, in Groovy, this can be reduced to one line (leaving out exception handling), as follows println path.toFile().text

A getText() method is added to the File class in Groovy that simply reads the whole file.


Writing Files

 Writing is similar to reading. For writing to text files, you should use PrintWriter. It includes the following methods (among others)

  •  print(Object) Prints the given object directly calling toString() on it 
  • println(Object) Prints the given object and then a newline
  •  println() Prints the newline character sequence
  •  printf(String format, Object…args) Prints a formatted string using the given input There are other ways to output to files, such as DataOutputStream,

for example

public void writeWithTry()

             try (FileOutputStream fos = new FileOutputStream("blogs.txt");
            DataOutputStream dos = new

DataOutputStream(fos)) {
             dos.writeUTF("Modern Java");
             } catch (IOException e) {
             // log the exception

DataOutputStream allows an application to write primitive Java data types to an output stream. You can then use DataInputStream to read the data back in.

In Groovy, you can more easily write to a file, as follows new File("blogs.txt").text = "Modern Java"

Groovy adds a setText method to the File class, which allows this syntax to work.


Downloading Files

Although you might not ever do this in practice, it's fairly simple to download a web page/ file in code. The following Java code opens an HTTP connection on the given URL (http//, in this case), reads the data into a byte array, and prints out the resulting text.

URL url = new URL("http//");

             InputStream input = (InputStream) url.getContent();
             ByteArrayOutputStream out = new ByteArrayOutputStream();
              int n = 0;
             byte[] arr = new  byte[1024];
          while  (-1 != (n =
             out.write(arr, 0, n);
        System.out.println(new String(out.toByteArray()));

However, in Groovy, this also can be reduced to one line (leaving out exceptions). println "http//".toURL().text

A toURL() method is added to the String class, and a getText() method is added to the URL class in Groovy.


Version Control

Version Control

 As soon as people start their programming careers, they are hit with the ton of bricks that is the version control system (VCS). Version control software is used to keep track of, manage, and secure changes to files. This is a very important part of modern software development projects.I am going to cover two popular ones, but there are many more

  • SVN (Subversion)
  • Git (git)

 Every VCS has the following basic actions

  • Add
  • Commit
  • Revert
  • Remove
  • Branch
  • Merge

 IDEs have plug-ins for dealing with version control systems and usually have built-in support for popular systems such as SVN and Git.



SVN1 was made as an improvement to an ancient and very popular VCS called CVS. It was a huge leap forward. Among other benefits, it allows any directory in the hierarchy to be checked out of the system and used. To begin using SVN on the command line, you will check out a project and then commit files, as follows

svn checkout http//
svn add file
svn commit


Install SVN. Using your command prompt, check out a project from Google Code. For example svn checkout http// wiquery-read-only.




Git is a distributed version control system. This means that every copy of the source code contains the entire history of the code. To begin using Git on a new project, simply run the following command

git init


Create a file called README and then commit it, as follows

git add README
git commit -m "this is my comment"

Install Git. Go to github.com4 and clone a repository. For example git clone git@ github.comadamd/modern-java-examples.git.



Mercurial predates Git but is very similar to it. It’s used for a lot of projects on Google Code and Bitbucket. Install Mercurial. Go to Bitbucket and clone a repository using Mercurial. For example hg clone https//


The Interweb


 The Web is a complex beast. Here’s what you need to know

  • Server The computer serving web pages
  • Client The computer that receives web pages and is used by a person
  • HTML The language used to create web pages
  • CSS “Cascading style-sheets”; store the styles of the web page
  • JavaScript A programming language that is used within web pages and executed on the client               


My First Web App

 You should make something very basic for your first web application. This way, you will have a better understanding of what’s going on “behind the scenes” of many web frameworks. Create a file called and copy the following code into it

public class App
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "<html> Hello Inter-webs! </html>";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
System.out.println("Server running at http//localhost8000/"); 24 }


 All this does is create an HTTP server that listens for connections on port 8000 and responds with a message.

  •  After running this code (javac && java App), open your web browser and point it to http//localhost8000/.
  •  localhost refers to the computer you’re on, and 8000 refers to port 8000.
  •  Congratulations! You just made a web application!


The Holy Grails


Grails is a web framework for Groovy that follows the example of Ruby on Rails (hence Grails). It is an opinionated web framework with a command-line tool that gets things done really fast. Grails uses convention over configuration to reduce configuration overhead.


Grails lives firmly in the Java ecosystem and is built on technologies such as Spring and Hibernate. Grails also include an object-relational mapping (ORM) framework called GORM and have a large collection of plug-ins.


After installing Grails,1 you can create an app by running the following on the command line

$ grails create-app

This overview is based on Grails 2.1.4, but the basics should remain the same for all versions of Grails. Then, you can run commands such as create-domain-class and generate-all to create your application as you go. Run grails help to see the full list of commands available.


Grails applications have a very specific project structure. The following is a simple breakdown of most of that structure

  • grails-app The Grails-specific folder
  • conf Configuration, such as the data source and Bootstrap
  • Controllers with methods for index/create/edit/ delete, or anything else


  • Domain model; classes representing your persistent data
  • i18n Message bundles
  • jobs Any scheduled jobs you might have gone here
  • You can very easily define your own tags for use in your GSP files.
  •  Views of MVC; typically, these are GSP files (HTML-based)
  • class='lazy' data-src Any utilities or common code that doesn’t fit anywhere else
  • Java code
  •  groovy Groovy code
  • web-app
  • CSS CSS style sheets
  • Images used by your web application
  • js Your JavaScript files

 WEB-INF Spring’s applicationContext.xml goes here. To create a new domain (model) class, run the following


$ grails create-domain-class

It’s a good idea to include a package for your domain classes (such as for example.Post). A domain class in Grails also defines its mapping to the database. For example, here’s a domain class representing a blog post (assuming User and Comment have already been created)

class Post {

String text
int rating
Date created = new Date()
User createdBy
static hasMany = [comments Comment]
static constraints = {

The static hasMany field is a map that represents one-to-many relationships in your database. Grails uses Hibernate in the background to create tables for all your domain classes and relationships. Every table gets an id field for the primary key by default.


To have Grails automatically create your controller and views, run the following

$ grails generate-all

Grails will ask if you want to overwrite existing files if they exist. So, be careful when using this command. When you want to test your app, you simply run the following


$ grails run-app

 When you’re ready to deploy to a server, you can create a “war” file by typing this $ grails war



The Grails ecosystem now includes over 1,000 plug-ins. To list all of the plug-ins, simply execute  $ grails list-plugins When you’ve picked out a plug-in you want to use, execute the following (with the plug-in name and version)

$ grails install-plugin [NAME] [VERSION]


This will add the plug-in to your project. If you decide to uninstall it, simply use the uninstall-plugin command. This has been only a brief overview of Grails. Many blogs have been written about Grails and how to use it. For more information on using Grails, please visit



Grails is supported by the following cloud providers

  • CloudFoundry
  • Amazon
  • Heroku

 However, it is not within the scope of this blog to go over all of them, so I’ll talk about Heroku.


Heroku is owned by It was one of the first cloud platforms and has been in development since June 2007. When it began, it supported only Ruby, but it has since added support for Java, Scala, Groovy, Node.js, Clojure, and Python. Heroku supports multiple tiered accounts, including a free account.


Heroku relies on git for pushing changes to your server. For example, to create an app in Heroku using the CLI, do the following

$ Heroku create

$ git push heroku master

Your app will be up and running, and Heroku will identify the URL where you will find it. Go launch a Grails app on Heroku!



REST stands for REpresentational State Transfer.8 It was designed in a Ph.D. dissertation and has gained some popularity as the new web-service standard. Many developers have praised it as a much better standard than SOAP.


At the most basic level in REST, each CRUD (create, read, update, delete) operation is mapped to an HTTP method.

  • Create POST
  • Read GET
  • Update PUT
  • Delete DELETE

The transport mechanism is assumed to be HTTP, but the message contents can be of any type, usually XML or JSON. The JSR community has designed the JAX-RS API for building RESTful Java web services, while Groovy and Scala both have some built-in support for XML and JSON and various way of building web services.


Using Maven Archetypes

You can create a simple Java REST (JAX-RS) application using Maven, as follows mvn archetype generates. Wait for things to download and then choose “tomcat-maven-archetype” (type “tomcat-maven” and press Enter, then type “1”; Enter; Enter).


You will need to enter a groupId and artifactId. After creating your application, you can start it by typing the following command  mvn tomcat run




Swing is the Java API for building cross-platform GUIs (graphical user interfaces). If you ever want to write a graphical program (a computer game, for example), you will have to use Swing or some similar API. There are many other libraries for doing graphics in Java, but Swing is built in. All of the code for this section can be found on the GitHub repository.

Hello Window


The most basic concept of graphics is getting stuff onto the screen. The easiest way to do this in Swing is to use JWindow, for example  Running this code will create a window at the top left of your screen, with the words “Hello Window” printed on it.


In the constructor, the following occurs

  •  The width and height of the window are both set to 500 pixels.
  • The window is set to always be displayed (above all other windows) with the setAlwaysOnTop method.
  • Finally, setVisible(true) is called to make the window visible.


 The paint method gets called every time the window is drawn on the screen. This method simply does the following

Sets the font size to 20

Draws the string “Hello World” at coordinates x=10, y=20 (coordinates are always in pixels) You might notice that the “window” doesn’t have any edges, header, menu, or minimize/maximize icons that you’re used to. To get these things, you use a JFrame. Here’s a very simple example

import javax.swing.*;

public class HelloFrame extends JFrame {
public HelloFrame() {
setSize(500, 500);
public static void main(String[] args) {
new HelloFrame();

Running this code creates a 500×500 “window with frame” with the name “Hello,” and closing the window would exit the application.


Push My Buttons


 Buttons are one of the ways that users can interact with your program. To cause something to happen when a button is pressed, you use an “ActionListener,” for example

JButton button = new JButton("Talk!");

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(HelloFrame.this, "Hello!"); 5 }


The showMessageDialog method of JOptionPane is similar to JavaScript’s alert method, in that it shows a pop-up window.


In Java 8, the ActionListener part can be shortened to the following

button.addActionListener(e -> JOptionPane.showMessageDialog(this, "Hello!"));
The Groovy syntax is slightly different (it only requires a { and }).
button.addActionListener({e ->JOptionPane.showMessageDialog(this, "Hello!")}) 


Swing has many interfaces that end with the word “Listener,” such as




 The Listener pattern is very similar to the Observer design pattern.


Fake Browser

Let’s make a web browser! Let’s begin by creating the fields and constructor for the class, as follows

public class Browser extends JFrame {
JTextField urlField = new JTextField();
JEditorPane viewer = new JEditorPane();
JScrollPane pane = new JScrollPane();
public Browser() {


JTextField will be used to input the URL. JEditorPane is used to show the HTML, and the JScrollPane allows the page to be scrollable. Next, we define the init() method to put everything together.

private void init() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(2,2));
panel.add(pane, BorderLayout.CENTER);
panel.add(urlField, BorderLayout.NORTH);
urlField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {

The viewer is set as the viewport view of the JScrollPane, so it can be scrolled. JPanel is created with a BorderLayout. This allows us to arrange urlField on top of the scroll pane, much as in a real browser. KeyListener is used to call handleKeyPress whenever a key is pressed inside urlField.


Next, we fill out the handleKeyPress method.

private void handleKeyPress(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
viewer.setPage(new URL(urlField.getText()));
} catch (MalformedURLException ex) {
} catch (IOException ex) {

This method simply sets the page of JEditorPane to the URL from urlField whenever the Enter key is pressed. Finally, we define the main method.

public static void main(String[] args) {

new  Browser().setVisible(true);




Griffon is a Groovy-based framework for creating Swing GUIs. It has a command-line interface very similar to Grails. To begin a new project type, use the following griffon create-app griffon-example -archetype=jumpstart Here, the name of the project is “griffon-example. Griffon uses the MVC design pattern and Groovy DSL to make it much easier to build Swing applications.


Advanced Graphics

 Although far beyond the scope of this blog, there are several libraries that can be used for 2D or 3D graphics. Here are some of them.

 Java 2D

  • JavaFX
  • JFreeChart
  • Piccolo2D
  • JMagick

Java 3D

  • JOGL
  • JMonkeyEngine

 JavaScript 2D

  • d3
  • Highcharts

JavaScript 3D

  •  three.js


Graphics Glossary


UX design

Component Any graphical element defined in the Java graphics API Double-Buffering A technique used in graphics in which elements are drawn in memory before being sent to the computer screen. This avoids flicker.


Frame In Swing, the frame (JFrame) is used to represent what we typically call a “window” in the GUI. GUI Graphical user interface Layout Strategy used by Swing for arranging components within a panel or other component Menu There are two kinds of menus a windows built-in menu (JMenu) and a pop-up menu (JPopupMenu).


Menu item In Swing, the JMenuItem represents one line of a menu that can have an action associated with it. Panel In Swing, JPanel is used to contain other components. Pixel Smallest unit of the screen that is drawable.


A typical screen has millions of pixels that are arranged in a grid. Window Rectangular section of the screen. In Swing, the Window object has no border, so it can be used for a splash image, for example.


Creating a Magical User Experience

 First, you should be aware of the following acronyms

  •  UX User experience
  •  UI User interface
  •  KISS Keep it simple, stupid



Application Hierarchy

 You should prioritize your UX according to the following characteristics, from highest to lowest

  • 1.   Functionality Software does what it should.
  • 2.   Usefulness Is the software easy to use?
  • 3.   Efficiency Can the user work efficiently?
  • 4.   Magicalness Is the experience magical?

 You can’t focus on being usable if your software is not functional. You can’t focus on being efficient if your software is not usable. After you have mastered all the basics (functionality, usability, and efficiency), only then can you attempt to make your UI magical.


Consider Your Audience

It’s always important to consider the audience for your software. You should get to know them. Those of you familiar with Harry Potter (or magic, in general) will recognize the words wizard/witch and muggle. In Potter’s world, a Squib is someone who’s aware of magic but not able to practice it, and a muggle is a normal person who’s unaware of magic.


We can apply this analogy to software.

  • Random User Muggle
  • Rock Star Squib
  • Genius Wizard/Witch


Choice Is an Illusion

The more choices a person has, the more thinking they are required to do. As a designer, you should do the following

  • Limit choices
  •  Prepare for every possible choice
  • Tailor choices for your audience

You will often have to decide whether to give your user a choice or make the choice for them. The easy way is always to let the user decide, but the better way is generally to give the user one less choice. This will make your software simpler and, therefore, easier to use.



Work instinctively—instinct is your friend. Motion is a subtle and effective way of getting the user’s attention. Of course, too much motion is a distraction, so it should be kept to a minimum.


Another instinctual image is the human face. Faces are noticed first. This is why you always see faces on the left-hand side of text (in languages that read from left to right). The eye is drawn first to the face and then to the accompanying text.



Skeuomorph is something from real life that is imitated in software.


Simulating real-life features, such as edges, bevels, and buttons can be useful for communicating affordability (what the user can do with something). However, you have to get it 100% right, if you’re simulating a complete object. This is why skeuomorphism is generally a bad idea. Imitating something from the real world comes across as fake if it is not done perfectly.


Windows 8 exemplifies the opposite approach—it attempts to remove all metaphor. The new UI of Windows (sometimes called Metro) is very flat and edgeless. Of course, you can take this concept too far. For example, what is clickable should still be obvious.



Above all, keep things simple—simple for the user. For example, in general, there should always be one way to do something in the software. Also, as a general rule, your UI should follow the conventions set by existing software/websites (for example, always underline links). 


As your software grows, you will constantly have to make choices about new UI features. In addition to other considerations, you should also contemplate how they can be made simpler.


You Are Not the User

Unless you are building software only for yourself, the overwhelming probability is that your users are very different from you. For this reason, you must not only try to think like your user but also really get to know him or her. This means ideally that you sit down and watch your users operate the software.




Databases are an extremely important component of most software projects. If you’re not familiar with a database, it is a software system that stores data and enables calculations on those data, somewhat like a spreadsheet.


An original database is known as a relational database because it stores relationships between tables in the database. A database typically consists of several highly structured data tables with defined constraints. For example, each column of a table has a type, whether or not it can be null if it must be unique, and other constraints.


There is a highly standardized language for performing operations and calculations on a database called SQL (Structured Query Language). SQL has been around a long time and could easily warrant its own blog, so I will only cover the basics here.


Since the advent of so-called big-data projects (such as a particular “face”-themed social network), the second category of databases has emerged NoSQL databases. Typically, these are more like key-value pairs than relational databases. They include Redis, MongoDB, Cassandra, and many others.


The SQL/NoSQL categorization is an oversimplification, but it provides an easier narrative than the actual complex reality. In other words, “Here be dragons!”.


SQL or Relational Databases

Part of classic relational databases is the concept of ACID1 (atomicity, consistency, isolation, durability). To summarize ACID, it means that the database is always in a consistent state (with enforced constraints), even if the system crashes in the middle of an update.


For example, if a column in a table is marked as “nonnull,” it will never be null. This may seem like a simple thing to achieve, but it is actually very hard. Some good open source databases include PostgreSQL, MySQL, and H2.



The basic language of relational databases is SQL. It includes the ability to define tables and perform complex queries on those tables. For example, creating a table looks something like the following

dragon_id INTEGER,
dragon_name VARCHAR(100),
birth_date DATE NOT NULL,
PRIMARY KEY (dragon_id)


A table always needs to have a primary key—it acts as the identifier for each row of the table. In this case, the primary key is dragon_id.

Database types cover the basics, such as INTEGER, but other unfamiliar types include the following

VARCHAR(length) is similar to the String object. It has a given maximum length.

TIMESTAMP is used to store dates and times.

NUMERIC(precision, scale) or DECIMAL(precision, scale) is used to store numbers such as currency values (for example, the number 123.45 has a precision of 5 and a scale of 2).


BLOB is typically used to store binary data.

To find the birthday of your oldest dragon, you might perform the following query


SELECT MIN(birth_date) FROM dragon;

Or, to select all dragons whose names start with S (in alphabetic order), run the following

SELECT dragon_id, dragon_name FROM dragon

WHERE dragon_name LIKE 'S%'
ORDER BY dragon_name;


Foreign Keys

A foreign key is simply a column in a table that references the primary key of another table. For example, let’s say you have a wizard table, and each wizard has multiple dragons they keep as pets. If the wizard table’s primary key is wizard_id, the “dragon” table would have the following column and foreign key constraint

owner INTEGER,
FOREIGN KEY owner REFERENCES wizard (wizard_id)

Although SQL keywords are shown in uppercase, this is not required by all databases.



A database system typically runs as a separate process, and your code connects to it in some way. There are many different ways to do this. In Java, the most basic standard for connecting to databases is called JDBC. It allows you to run SQL statements on the database. You will need a specific driver for your database.


There are also object-relational mapping (ORM) frameworks, such as Hibernate. These frameworks have you map Java objects to data tables. They are built on top of JDBC. For example, Hibernate has its own query language, called HQL, which is translated into SQL by Hibernate. Grails uses Hibernate.


Alternatively, there are code-generating frameworks that allow you to use a DSL for queries. One such framework for Java is jOOQ. It allows you to write type-safe queries in the native language. For example

, create.selectFrom(DRAGON)




NoSQL Databases

Big web projects (such as Wikipedia) had problems using relational databases to scale up to millions of users. They had to partition their database onto multiple machines (called sharding), which broke foreign key references.


So, over time, big-data projects moved to NoSQL databases, which are basically key-value stores that can be scaled up more easily. NoSQL databases are used by Netflix, Reddit, Twitter, GitHub, Pinterest, eBay, eHarmony, craigslist, and many others.

Note  I will cover some NoSQL databases here, but there are many others.



Redis4 is a key-value store. Everything is stored as a string in Redis, including binary data. It’s written in C and has a long list of commands.5 There are multiple clients for using Redis from many different languages, including Java, Node.js, Scala, Ruby, Python, and Go.



MongoDB6 calls itself a document database. It stores JSON-style (JavaScript) documents and has a rich query syntax. It’s written in C++, but JavaScript can be used in queries and aggregation functions.


MongoDB supports indexing of any field in a document. It scales horizontally using sharding and provides high availability and increased throughput using replication. MongoDB can also be used as a file system.



Cassandra was originally developed at Facebook and was released as an open source project in July 2008. It’s written in Java and is now a mature, top-level Apache project.


Cassandra is scalable, decentralized, fault-tolerant, and has tunable consistency. It also uses replication for fault-tolerance and performance. Cassandra has a SQL-like alternative called CQL (Cassandra Query Language). Language drivers are available for Java (JDBC), Python (DBAPI2), and Node.JS (Helenus).



VoltDB8 provides a counter-example to the SQL/NoSQL divide. It’s distributed, in-memory, and lightning-fast, but it’s also a relational database and supports SQL.