Todas las entradas de: xavsal

OCP11 – Creating nested classes (V) – Defining an Anonymous Class

A anonymouys class is a specialized form of a local class that does not have a name.

It is declared and instantiated all in one statement using the new keyword, a type name with parenthesis, and a set of braces {}.

Anonymous classes are required to extend an existing class or implement an existing interface.

Example using an Abstract class:

  public class ZooGiftShop {
     abstract class SaleTodayOnly {
        abstract int dollarsOff();
     public int admission(int basePrice) {
        SaleTodayOnly sale = new SaleTodayOnly() {
           int dollarsOff() { return 3; }
        };  // Don't forget the semicolon!
        return basePrice - sale.dollarsOff();
} }

Line 2 through 4 define an abstract class through .
Line 6 through 8 define the anonymous class (it hasn’t a name).
The code says to instantiatea new SaleTodayOnly object. It is abstract but it is ok because we provide the class body right there – anonymously.
In this example, writing an anonymous class is equivalent to writing a local class with an unspecified name that extends SaleTodayOnly and then immediately using it.
Line 8 specifically we are declaring a local variable on these lines. Local variable declarations are required to end with semicolons, just like ohter java statements – even if they are long and happen to contain an anonymous class.

Seguir leyendo OCP11 – Creating nested classes (V) – Defining an Anonymous Class

OCP11 – Creating nested classes (IV) – Writing a local class

A local class is a nested class defined within a method.

Like local variables, a local class declaration does not exist until the method is invoked and it goes out of scope when the method returns.

This means you can create instances only from within the method. Those instances can still be returned from the method. This is how local variables work.

IMPORTANTE NOTE TO CONSIDER FOR THE EXAM: Local classes are not limited to being declared only inside methods. They can be declared inside constructors and initializers too. For simplicity, we limit our discussion to methods.

Local Classes have the following properties:

  • They do not have an access modifier.
  • They cannot be declared static and cannot declare static fields or methods, except for static final fields.
  • They have access to all fields and methods of the enclosing class (when defined in an instance method).
  • They can access local variables if the variables are final or effectively final.

IMPORTANTE NOTE TO CONSIDER FOR THE EXAM: Effectively final refers to a local variable whose value does not change after it is set. A simple test for effectively final is to add the final modifierto the local vairable declaration. If it still compiles, then the local variable is effectively final.

Example – Multiply two numbers in a complicated way:

1:  public class PrintNumbers {
2:     private int length = 5;
3:     public void calculate() {
4:        final int width = 20;
5:        class MyLocalClass {
6:           public void multiply() {
7:              System.out.print(length * width);
8:           }
9:        }
10:       MyLocalClass local = new MyLocalClass();
11:       local.multiply();
12:    }
13:    public static void main(String[] args) {
14:       PrintNumbers outer = new PrintNumbers();
15:       outer.calculate();
16:    }
17: }

Line 5 is the local class.
Line 7 refers to an instance variable and a final local variable, so both variables references are allowed from within the local class.
Line 9 is the local class.
Line 12 is the place where the class’ scope ends.

Local variables references are allowed if they are final or effectively final

The compile is generatinga .class file from the local class. A separate class has no way to refer to local variables.

If the local variable is final, Java can handle it by passing it to the constructor of the local class or by storing it in the .class file.

If it weren’t effectively final, these tricks wouldn’t work becuase the value could change after the copy was made.


public void processData() {
   final int length = 5;
   int width = 10;
   int height = 2;
   class VolumeCalculator {
      public int multiply() {
         return length * width * height; // DOES NOT COMPILE
   width = 2;  // Variable reassignation - origin of the error compilation

The length and height variables are final and effectively final, respectively, so neither causes a compilation issue.

On the other hand, the width variable is reassigned during the method so it cannot be effectively final. This is the reason why the local class declaration does not compile.

OCP11 – Creating nested classes (III) – Creating an static nested class

A static nested class is a static type defined at the member level. Unlike an inner class, a static nested class can be instantiated without an instance of the ecnlosing class.

The trade-off though, is it can’t access instance variables or methods in the outer class directly. It can be done but it requires an explicit reference to an outer class variable. It is like a top-level class except for:

  • The nesting creates a namespace because the cnlosing class name must be used to refer it.
  • It can be made private or use one of the other access modifiers to encapsulate it.
  • The enclosing class can refer to the fields and methods of the static nested class.


1: public class Enclosing {
2:    static class Nested {
3:       private int price = 6;
4:    }
5:    public static void main(String[] args) {
6:       Nested nested = new Nested();
7:       System.out.println(nested.price);
8: } }

Line 6 instantiates the nested class. Since the class is static, you don’t need an instance of Enclosing to use it.
Line 7 allows you to access private instance variables.

Importing a static Nested Class

Importing a static nested class is done using the regular import.

    package bird;
    public class Toucan {
       public static class Beak {}
    package watcher;
    import bird.Toucan.Beak; // regular import ok
    public class BirdWatcher {
       Beak beak;

Since it is static you can also use a static import:

import  static  bird.Toucan.Beak;

IMPORTANT TO CONSIDER HERE FOR THE EXAM: Java treats the cnsloing class as if were a namespace.

OCP11 – Creating nested classes (II) – Declaring an Innner Class

An inner class, also called a member inner class, is a non‐ static type defined at the member level of a class (the same level as the methods, instance variables, and constructors). Inner classes have the following properties:

  • Can be declared public, protected, package‐private (default), or private
  • Can extend any class and implement interfaces
  • Can be marked abstract or final
  • Cannot declare static fields or methods, except for static final fields
  • Can access members of the outer class including private members. The last property is actually pretty cool. It means that the inner class can access variables in the outer class without doing anything special.

Example – Ready for a complicated way to print Hi three times?

1:  public class Outer {
2:     private String greeting = "Hi";
4:     protected class Inner {
5:        public int repeat = 3;
6:        public void go() {
7:           for (int i = 0; i < repeat; i++)
8:              System.out.println(greeting);
9:        }
10:    }
12:    public void callInner() {
13:       Inner inner = new Inner();
14:       inner.go();
15:    }
16:    public static void main(String[] args) {
17:       Outer outer = new Outer();
18:       outer.callInner();
19: } }

Line 8 shows that the inner class just refers to greeting as if it were available. It works even though the variable is private being on the same class.

Line 13 shows that an instance of the outer class can instantiate Inner normally. It works because callInner() is an instance method on Outer. Both Inner and callInner() are members of Outer.

Seguir leyendo OCP11 – Creating nested classes (II) – Declaring an Innner Class

OCP11 – Creating nested classes (I)

A nested class is a class that is defined within another class. We have four different nested classes types:

  1. Inner class: A non-static type defined at the member level of a class.
  2. Static nested class: A static type defined at the member level of a class.
  3. Local class: A class defined within a method body.
  4. Anonymous class: A special case of a local class that does not have a name.

By convention we use the term inner or nested class to apply to other Java types, including enums and interfaces.

Interfaces and enums can be declared as both inner classes and static nested classes but not as local or anonymous classes.

We will explain each one of these nested classes in a different post and we will use this post to show which are the syntax rules permitted in Java for nested classes in three tables.

Seguir leyendo OCP11 – Creating nested classes (I)

OCP 11 – Language Enhancements (Java Fundamentals – Enumerations)

Generally speaking an Enumeration is like a fixed set of constants. But in Java an enum (short for enumerated type) can be a top-level type like a class or a interface, as well as a nested type like an inner class.

Using an enum is much better than using a lot of constants because it provides type safe checkline. With numeric or Strings contants you can pass an invalid value and not find out until runtime. On the other hand, with enums it is impossible to create an invalid value without introducing a compiler error.

Seguir leyendo OCP 11 – Language Enhancements (Java Fundamentals – Enumerations)

OCP 11 – Language Enhancements (Java Fundamentals – Final modifier)


Final modifier can be applied to variables, methods and classes.
Marking a:

  1. Variable final means the value cannot be changed after it is assigned.
  2. Method or a class means it cannot be overridden (for methods) or extended (for classes).

Declaring final local variables

For final variables there are several aspects to consider.

We do not need to assign a value to the final variable when we declare it. What we have to assure is the a value has been assigned to it before this final variable is used. We will get a compilation error in case we don’t follow this rule. Example which illustrates this:

private void printZooInfo(boolean isWeekend) {
    final int giraffe = 5;
    final long lemur;
    if (isWeekend) lemur = 5;
    giraffe = 3; // DOES NOT COMPILE   
    System.out.println(giraffe+" "+lemur); // DOES NOT COMPILE

Here we have two compilation errors:

  1. The giraffe variable has an assigned value so we can’t assign a new value because it has been declared as final. We will get a compilation error.
  2. When attempting to use lemur variable we will get a compilation error. If condition isWeekend is false we can’t assign the value to lemur so we will the error the error compilation because a local variable to has to be declared and assigned before using it (despite the fact of being declared as final or not).

When we mark a variable as final it does not mean that the object associated with it cannot be modified. Example to illustrate this:

final StringBuilder cobra = new StringBuilder();

We have declared the variable as constant but the content of the class can be modified.

Adding final to Instance and static variables

Instance and static class variables can be marked as final too.

When we mark as final a:

  1. Instance variable which it means that it must be assigned a value when it is declared or when the object is instantiated (Remember: We can only assign once, like Local Variables). Example to illustrate this:

    public class PolarBear {
    final int age = 10;
    final int fishEaten;
    final String name;
    { fishEaten = 10; }
    public PolarBear() {
      name = "Robert";
    public PolarBear(int height) {

    Does this code compile? Yes. Everything. Exercise: Explain why.

  2. Static variable which it means they have to use static initializers instead of instance initializers. Example to illustrate this:

    public class Panda {
    // We assign a value when we declare the final variable
    final static String name = "Ronda";
    static final int bamboo;
    static final double height; // DOES NOT COMPILE - Why? Because we do not have assign any value to height variable  
    // It will work because we are initializing a final static variable through an static initializer
    static { bamboo = 5;}}

Writing final methods

Methods marked as final cannot be overriden by a subclass. This avoids polymorphic behavior and always ensures that it is always called the same version method. Be aware because a method can have abstract or final modifier but not both at the same time.

When we combine inheritance with final methods we always get an error compilation.

We cannot declare a method final and abstract at the same time. It is not allowed by the compiler and of course we will get a compilation error.
Example to illustrate this:

abstract class ZooKeeper {   
    public abstract final void openZoo(); // DOES NOT COMPILE

Marking Classes final

A final class is one class that cannot be extended. In fact we will get a compilation error if we tried. Example to illustrate this:

public final class Reptile {}
public class Snake extends Reptile {} // DOES NOT COMPILE

We cannot use abstract and final modifiers at the same time.

public abstract final class Eagle {} // DOES NOT COMPILE

It also happens the same for interfaces.

public final interface Hawk {} // DOES NOT COMPILE

We will get a compilation error in both cases.

OCP11 – Local Variable Type Inference

Working with Local Variable Type Inference

After Java 10 we can use the keyword var instead of the type for local variables (like the primitive or the reference type) under certain conditions within a code block.

public void whatTypeAmI {
    var name = "Hello";
    var size = 7;

The formal name of this feature is local variable type inference but we have to consider two main parts for this feature.

Seguir leyendo OCP11 – Local Variable Type Inference


Java 11


Backup BDD
HTTPS certificate (Let’s encrypt a Bitnami)
Lombok – Annotation processor (Xavi / Toni)


TestNG with Mockito


Construcció Native Image java (Manual i Maven)
Stack Prometheus, Grafana, Loki
Introducció (Context)
Instal.lacció stack
Provisionament de dades
Prometheus per metriques
Loki per logs
Administració de grafana (datasources i dashboards)

Configurar firewall linux con Firehole
Documentar màquina virtual desenvolupament ARM (Raspberry)
ConnectionManager HttpClient
SecurityManager: Funcionamiento y implementación custom correcta
Provisionament VM – Ansible

Sdkman – The Software Development Kit Manager

SDKMAN! es una herramienta para manejar versiones paralelas de múltiples Kits de Desarrollo de Software en la mayoría de los sistemas basados en Unix. En este post, aunque originalmente está pensando para sistemas Unix veremos su utilización mediante Java en su version 11 en entornos Windows, concretamente con Windows 10.

Proporciona una conveniente Interfaz de Línea de Comando (CLI) y API para instalar, cambiar, eliminar y listar candidatos.

Anteriormente conocido como GVM el Groovy enVironment Manager, fue inspirado por las muy útiles herramientas RVM y rbenv, utilizadas en general por la comunidad Ruby.

Para poder ser utilizando en entornos Windows es neceasario realizar una refacorización del código fuente del script bash original.

Existe una sección (install) en la propia página web dónde se indican los pasos a seguir para su instalación y utilización en entornos Windows.

Para mostrar su uso en Windows 10 se utiliza el Shell de Git Bash mediante el uso de este script get_sdkman_io (ya preparado para funcionar en entornos Windows).

Seguir leyendo Sdkman – The Software Development Kit Manager