Java Modifiers

Java modifiers are some specifc words that we put before : classes, attribute,  methode, or constructor to define a way of use.

There is 2 types of Java modifiers

  • Java Access Modifiers.
  • Java Non-Access Modifiers.

example of using :

public class book {

private int numberOfPages;

public static void main(String arg[]){

System.out.println("hello");

}

}

I) Java Access Modifiers.

There are modifiers used to set access levels for classes, variables, or methods and constructors. The four access levels are −

  • Without modifier (default access level): visibility to the package only.
  • “private” : Visible in the class only.
  • “public” : Visible any where inside a package or outside it.
  • “protected” :Visible in the package and all subclasses.

II)Java Non-Access Modifiers.

There are modifier that specify the way of managing classes object, attributes, or methods.

  • “static” :

-Make attribute myAttribute or method  myMethode() in a class MyClass simply accessible by MyClass.myAttribute and MyClass.myMethode(). without instantiate an object of MyClass to access them

Only in case of nested class (class MyClass inside an other class MyOuterClass) it make MyClass  accessible  simply by  MyOuterClass.MyClass without instantiate an object of MyOuterClass.

  • “final” : Make definition of class, attribute or method final (not changeable).

Final class cannot be derived, final method cannot be overridden, final attribute : basic attribute cannot been changed (like constant in C/C++) , for  attribute type object it’s the reference how will be constant not the value, like array in this  example:

public final int[] myArray={1,5,10};

...

myArray[0]=2 ;// the value of first item  can be changed but not the reference

  • “transient”: Make attribute myAttribute excluded when the object (instance of class having the attribute myAttribute ) is serialized. if the object is deserialized, the attribute will take the default value.
  • “synchronized” : Make method accessed by only one thread at a time.
  • “volatile” : Make attribute value allways read / write directly from / to the main memory , so there is no cach done by thread for the attribute value.
  • “abstract” :

-Make class impossible to instantiate, but still be possible to be drived.

-Make method declared without an implementation, so without braces :

 abstract void myMethod(int a); 

NB: if an abstract method myMethod() is part of a class MyClass,  the MyClass should be abstract

Install OpenJDK 11 (win , mac, linux)

OpenJDK 11 is an open-source build of the Java Development Kit (JDK: kit for developing Java programs ),  under the [GNU General Public License, version 2,with the Classpath Exception]. We will not explain in this post the difference between OpenJDK and OracleJDK it’s a long story (don’t worry there is few changes between them). but just keep in mind that there is 2 versions: open source version (OpenJDK) and commercial version of JDK (Oracle JDK)

NB: Big thanks for Oracle to participate in maintaining the openSource JDK version beside the Oracle JDK. The SUN still shine! I guess Java is in good hands !

Well will not focus on Oracle JDK (commercial version) but you can download it from this link: https://www.oracle.com/technetwork/java/javase/downloads/index.html

so lets install Open Jdk

I) Installation on Windows

  • From the link https://jdk.java.net/11/ download the zip of Windows / x64 extract it in <your_java_home> for example in my case   c:\tools\java\jdk-11.0.1
  • Add the <your_java_home>\bin to your Path : with right mouse button click on your pc icon then select properties

 Select  Advanced system settings.

press  Environment Variables button .

select Path variable , click on edit and add <your_java_home>\bin, press ok

 

NB: It’ s nice to create JAVA_HOME environment variable and has <your_java_home> as value, this is used by most of tools and API using JDK.

NB: There is 2 locations of environment variables  local user location (blue rectangle) and system location (red rectangle), add java bin directory to both Path variables

 

  • Test OpenJDK installation, open cmd.exe and type :

java -version

example of result :

openjdk version “11.0.1” 2018-10-16
OpenJDK Runtime Environment 18.9 (build 11.0.1+13)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.1+13, mixed mode)

II)Install on Linux Centos.

  • From the link https://jdk.java.net/11/ download the tar.gz of Linux / x64 tar.gz extract it in <your_java_home> for example in my case  /opt/java/jdk-11.0.1

sudo tar xvzf openjdk-11.0.1_linux-x64_bin.tar.gz -C /opt/java/

  • Add the <your_java_home>\bin to your Path : I will use my .bash_profile file to get bin directory commands load in the login in linux session

vi ~/.bash_profile

then make following lines in end of file

PATH=$PATH:/opt/java/jdk-11.0.1/bin
export PATH

  • exit from linux session and reconnect again and execute:

java -version

example of result :

openjdk version “11.0.1” 2018-10-16
OpenJDK Runtime Environment 18.9 (build 11.0.1+13)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.1+13, mixed mod

III) Install on Mac OS ( test for jdk-11.0.2).

  • From the link  https://jdk.java.net/11/download the tar.gz of macOS/x64 tar.gz extract it in <your_java_home>for example in my case  /opt/java/jdk-11.0.2.jdk

sudo tar xvzf openjdk-11.0.2_osx-x64_bin.tar  -C /opt/java/

  • Add the /opt/java/jdk-11.0.2.jdk/Contents/Home/bin
     to your /etc/paths  to get bin directory commands load in start or macOS you can use vi command likeÂ

sudo vi /etc/paths

then add the following line:

/opt/java/jdk-11.0.2.jdk/Contents/Home/bin

  • restart your Mac OS  and execute:

java -version

example of result :

openjdk version “11.0.2” 2018-10-16

OpenJDK Runtime Environment 18.9 (build 11.0.2+7)

OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+7, mixed mode)

 

 

Singleton implementation in Visual Studio C++ sample project

In this post I will create an implementation of the Singleton design pattern in a Visual Studio C++ (2017)  project, my sample has passed the sonar quality check  (it’s the case of all take4make sample).

This is the structure of the c++ project :

NB: thanks to Microsoft for making available the visual studio version 2017 free for learning purpose.

Basically I create Singleton class [header= Singleton.hpp implementation Songleton.cpp ]  and Caller.cpp that use the Singleton class

So to succeed  the C++ Singleton class implementation I need to answer these 2 questions.

How  to instantiate the singleton class only one time during execution life (in other words  how to  make impossible to instantiate more than one instance  )?

How to get access on the alone singleton instance from every where?

So we need to create Singleton class with a private constructor (see Singleton.hpp) so that it will be impossible to instantiate it by other c++ source file. Also we need to create a static attribute of type Singleton MyInstance which will hold the unique instance reference. Last thing we will create static method GetInstance() that check if MyInstance null and then create it using the private constructor. So GetInstance() will  take in charge  checking that we have only an alone instance of Singleton class, and return it. Also it will create if it’s not already created. This will guarantee instantiation in the first call.

Singleton.hpp

/*
* created in scope of www.take4make.com samples
* @author khalil CHARA
*/

#pragma once

/**
* Singleton Class tha show the singleton designe pattern implementation
*/
class Singleton
{
private:
/**
* single instance of Singleton class , it's private to avoid access directly by other classes
*/
static Singleton *MyInstance;
/**
* double number to check unicity of singleton instance
*/
double RandomNumber = 0;
/** private constructor to avoid use by other classes
* the constructor chose random number to fill randomNumber variable,
* this will show us in case of many call of singleton that it's about the same instance.
*/
Singleton();
~Singleton();

public:
/**
* get local and single instance myInstance
* it has static modifier to be the point of access
* this method create the single instance in the first call. see the Caller class to complete the vision
*/
static Singleton *GetInstance();
/**
*Simple getter of randomUmber to see if it's about many instantiation or single instantiation
*/
double GetRandomNumber();
};

 

NB: The random attribute is for test purpose in Caller.cpp to show that only one instance of singleton is created

Singleton.cpp

/*
* created in scope of www.take4make.com samples
* @author khalil CHARA
*/

#include "pch.h"
#include "Singleton.hpp"
#include <stdlib.h>

//constructor implementation
Singleton::Singleton()
{
//generate random number to prove for caller that there is only one instance created
Singleton::RandomNumber = rand();
}

//destructor implementation
Singleton::~Singleton()
{
//put free instruction if you did allocation in singleton class.
}
//get_instance implementation
Singleton *Singleton::GetInstance() {
//check if myInstance already created , otherwise create it and return it for callers.
if (!Singleton::MyInstance) {
Singleton::MyInstance = new Singleton;
}
return Singleton::MyInstance;
}
//get_random_number implementation
double Singleton::GetRandomNumber() {
return Singleton::RandomNumber;
}
// Instantiation t0 = null pointer
Singleton *Singleton::MyInstance = nullptr;

Caller.cpp

/*
* created in scope of www.take4make.com samples
* @author khalil CHARA
*/

#include "pch.h"
#include <iostream>
#include "Singleton.hpp"

int main()
{
Singleton *sngltnT1 = Singleton::GetInstance();
Singleton *sngltnT2 = Singleton::GetInstance();
std::cout << "sngltnT1 number is : " << sngltnT1->GetRandomNumber() << "\n";
std::cout << "sngltnT2 number is : " << sngltnT2->GetRandomNumber() << "\n";
}

// Execute the software : Ctrl+F5
// debug the software : F5

Result of the execution :

sngltnT1 number is : 41

sngltnT2 number is : 41

you can see that it’s about the same instance (for sngltnT1 and sngltnT2) because the random number is the same. if it was about different instances the random number will be different.

Down load the full project :  T4MCppSingleton

Singleton implementation in Maven Java sample project

In this post I will create an implementation of the Singleton design pattern in a Maven Java project, my sample has  passed the sonar quality check   (it’s the case of all take4make sample ).

This the structure of the maven java project :

basically I create Singleton class  and Caller class which calls Singleton

So to create the Java  Singleton class I need to answer these 2 questions.

How  to instantiate the singleton class only one time during execution life (in other words  how to  make impossible to instantiate more than one instance  )?

How to get access on the alone singleton instance from every where?

So we need to create singleton class with a private constructor so that it will be impossible to instantiate it by other classes. Also we need to create a static attribute of type Singleton myInstance which will hold the unique instance reference. last thing we will create static method getInstance() that check if myInstance null and then create it using the private constructor. So getInstance() will  take in charge checking that we have only an alone instance of Singleton class, and return it. Also it will create if it’s not already created. This will guarantee instantiation in the first call.

Tt’s useful to use synchronized  modifier for getInstance() method to avoid problem in case of simultaneous use by many thread.

Singleton.java

/*
* created in scope of www.take4make.com samples
* @author khalil CHARA
*/

package com.take4make.singleton;

/**
* Singleton class created in scope of www.take4make.com samples
* @author khalil CHARA
*/
public final class Singleton
{
/**
* single instance of Singleton class , it's private to avoid access directly by other classes
*/
private static Singleton myInstance;

/**
* double number to check unicity of singleton instance
*/

private double randomNumber;
/** private constructor to avoid use by other classes
* the constructor chose random number to fill randomNumber variable,
* this will show us in case of many call of singleton that it's about the same instance.
*/
private Singleton()
{
//generate random number to prove for caller that there is only one instance created
this.randomNumber=Math.random();
}

/**
* get local and single instance myInstance
* it has static modifier to be the point of access
* it has synchronized modifier to avoid use by many thread at the same time.
* this method create the single instance in the first call. see the Caller class to complete the vision
* @return
*/
public static synchronized Singleton getInstance()
{
if (myInstance == null)
{
myInstance = new Singleton();
}
return myInstance;
}
/**
* get Random Number
* @return double
*/
public double getRandomNumber()
{
return randomNumber;
}
}

 

NB: The random attribute is for test purpose in Caller class to show that only one instance of singleton is created

Caller.java

/*
* created in scope of www.take4make.com samples
* @author khalil CHARA
*/

package com.take4make.singleton;
import org.apache.log4j.Logger;

/**
* Caller Class that use the Singleton class, created in scope of www.take4make.com samples
* @author khalil CHARA
*/
public class Caller
{
/**
* Logger for logging information in the consol
*/
private static final Logger LOGGER = Logger.getLogger(Singleton.class);
/**
* main methode to execute singleton sample
* @param args
*/
public static void main(String[] args)
{
//this first call of getInstance will create the single instance of Singleton class and return it.
Singleton sngltnT1=Singleton.getInstance();
//this second call of getInstance will just return the single instance already created before.
Singleton sngltnT2=Singleton.getInstance();
LOGGER.debug("sngltnT1 number is : "+sngltnT1.getRandomNumber());
LOGGER.debug("sngltnT2 number is : "+sngltnT2.getRandomNumber());
}
}

Result of the execution :

2019-01-06 20:38:21 DEBUG Singleton:16 – sngltnT1 number is : 0.48172858244605954
2019-01-06 20:38:21 DEBUG Singleton:17 – sngltnT2 number is : 0.48172858244605954

You can see that it’s about the same instance (for sngltnT1 and sngltnT2) because the random number is the same. If it was about different instances the random number will be different.

Down load the full project : T4MJavaSingleton

Singleton design pattern basic concept and implementations

Singleton is a creation design pattern according to Gang Of Four book ( it’ s a book made  by 4 persons  with a big knowledge of programming also called  “Design Pattern: Elements of Reusable Object-Oriented Software” )

basically a singleton is a class to instantiate one time  in  execution life. a singleton is used when we manage a class throw one and only one instance: for example to avoid waste of memory resources, or having global point of access to this one instance from all other classes in the same application . It’s very helpful for logger or configuration resources loader.

To create singleton we need to answer 2 questions:

-How to get access on the alone singleton instance from every where?

-How  to instantiate the singleton class only one time during execution life (in other words  how to  make impossible to instantiate more than one instance)?

So it does not matter if we develop in Java, C++, C#,  or Objectif C , the important thing is to ask throw the programming language the previous  2 questions

I have made 4  singleton implementations all of them are compliance with sonar quality check  and are well commented:

 

SonarQube tutorial and installation guide

In this post I will talk about SonarQube tool. I will describe installation and use in Java maven project.

I ) SonarQube Introduction

SonarQube is a tool created by sonarsource  for measuring quality of code, it support many programming languages. it’ s very helpful for the developer and team of developers.

SonarQube can generate for you a user-friendly and clear reports containing information that help  to correct , improve quality of code, like:

Duplicated code=> same code in many code parts that need to be factorized for better performance. Make your code modular: try to make each instructions block for a common feature in a separate class or  method  to be used by all other codes elements, and avoid duplicate same block of instruction in difference places. Doing so will improve performance, readability of code, and help you correct or improve the common part one time. 

-Coding standards=> code that does not respect the standard programming rules. Respecting programming standard rules is good for code visibility and performance. 

-Unit tests coverage=> bad unit test code coverage rate is not healthy. Having well covered code with unit test make recognising of regression bug very simple after any modification. 

-Code complexity=> very complicated code like nested loop is affecting performance. If you have complex feature try to split it throw many methods or function,  avoid make a lot of nested looping.

-Comments=> poor comment rate, will make your code incomprehensible (not easy to understand) for the others developers, and for you also after a while. Try at least to comment  the class and method headers as well as the code part with a high added value (important code).

-Risky parts of code=> Bug code, or code which can cause future bugs or security vulnerabilities, Try to have Zero Critical or Blocker issue, and reduce the Major and Minor issue.

NB: big Thanks to sonarsource team for this very helpful opensource tool.

II) Install SonarQube 7.4 on windows 7 machine.

  • Make sure that you have java installed in your machine : with cmd execute java -version. (if you want to install Java follow this post )
  • Download the SonarQube Community Edition from : https://www.sonarqube.org/downloads/ (download last version: we will use 7.4 in this post)
  • Unzip the directory in your desired path <your_local_path>\sonarqube-7.4
  • Open cmd and execute  StartSonar.bat located in <your_local_path>\sonarqube-7.4\bin\windows-x86-64 or <your_local_path>\sonarqube-7.4\bin\windows-x86-32  (Depending on your arch of machine x86 or x64, in my case I have x64 arch)
  • Try with any internet browser to confirm installation throw this url: http://localhost:9000
  • On your maven java project add new profile to existing profiles in the  pom.xml :

<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>

<properties>
<sonar.host.url>http://localhost:9000</sonar.host.url>
</properties>
</profile>
</profiles>

  • With maven you can build and generate sonar report using this command :

mvn clean install sonar:sonar

  • Then go to the url http://localhost:9000/projects you will find your project analyse report:

NB: You can see for example in my singleton project that all aspect are good except test coverage, so for learning purpose and to avoid make my samples in www.take4make.com very complicated with many test unit (Dont worry I will provide some of unit test to get an idea), I will disable test coverage aspect from sonar:

  • You need to login with admin/admin (user/password) it’s the default created user. go to Administration > Analysis Scope > Coverage Exclusions. enter the  pattern  **/*.* to exclude sources from coverage test.

 

  • Once you have save the exclusion you can use maven to make report again mvn sonar:sonar

You can see now that the result is good ! I like green color.