Casting variables in Java

Casting a varibale in java is indicating to the compiler that a variable of type A will be used as an other type B. There are two types of casting, implicit and explicit.

Implicit casting

Implicit casting in Java is when you assign a variable of a lower (or child) type to a greater (or parent) type.

Examples of implicit casting:

// example 1 : a was implicitly casted from int to double
int a = 10;
double d=a;

// example 2 : student was implicitly casted from Student to Person
// we suppose that Student is a subclass of Person
Student student= new Student();
Person person = student;

Explicit casting

Explicit casting in Java is when you explicitly indicate to the compiler the target type you want to convert the value of your variable to (otherwise your code will not compile).

It is like if you tell the compiler : Trust me, my varibale can be cast to the target type !

The source data type must be compatible with the target data type at runtime (when you execute the program). If not, you will get a ClassCastException.

Examples of explicit casting:

// 256.1234f will be converted to int and the 
// digits after the period (.) will be lost
float f = 256.1234f;
int i = (int)f;

// p is converted to Student datatype
// Student must be a sub-type of Person 
Person p= new Person();
Student s = p;

Casting primitives

Java  allows primitive types to be cast implictly from lower to higher data types . For explicit cast of primitives, you have to be careful with the loss of precision and varibale truncating when you cast higher to lower datatypes (Example : from  double to int).

The following is a summary of what are the implicit and explicit casts allowed for primitive types in Java.

Primitives casting in Java

Primitives casting in Java

 

 

 

Java 8 Lambda expressions tutorial

What are Lambda expressions

Lambda expressions are a new feature of Java 8 that can be seen as replacement of anonymous inner classes using expressions, allowing to pass functionality as method arguments. They can also be seen as anonymous methods (nameless) implementing a method defined by a functional interface.
Before going further, I will describe what a functional interface is in the next section.

Functional Interfaces

A functional interface (FI) is any interface that contains :

  1. One single abstract method;
  2. Zero or more static methods;
  3. Zero or more default methods.

To be able to write a Lambda expression you must have a corresponding functional interface. Lambda expressions implement the method defined by that interface. The signature of it’s abstract method must match the lambda expression in terms of parameters and return type.

It is preferable to add the annotation @FunctionalInterface to your FI but it’s not mandatory. However, doing so will make your code more readable and allows the EDI (ie: eclipse) to give you some refactoring suggestions like replacing anonymous inner classes by lambda expressions. Functional interfaces are also called Single Abstract Methods (SAM).

Th package java.util.function includes a lot functional interfaces that can be used in specific situation. An example with Predicate and Consumer functional interfaces will be discussed later in this tutorial. You can check the Javadoc for the complete list of these functional interfaces. Before you define your own FIs, you may want to verify the existence of an FI that satisfies your specific need.

Why lambda expressions

The following simple example will help you to better understand the use of lambda expressions.

Consider the Operation interface, representing an abstract arithmetic operation. The interface contains the calculate() method representing the calculating functionality. Since the interface offers only and only one abstract method, we can consider that the interface Operation itself represents the calculate functionality:

interface Operation {
  int calculate(int a,int b);
}

Please note that the Operation interface contains one and only one abstract method which is calculate(), such interfaces are called Functional Interfaces.

The Test class contains the displayResult() method that calls the method calculate of Operation and displays the result. It takes three parameters:

  1. The first parameter of the calculation;
  2. The second parameter of the calculation;
  3. The Operation we want to execute.
public class Test {

 public static void main(String[] args) {
   // calculations to be added later ...
 }

 static void displayResult(Operation operation, int a, int b){
   System.out.println(operation.calculate(a, b));
 }

}

In other words, the displayMethod() will receive the calculation functionality as parameter, execute it and display the result.

In Java 7 and earlier, we can implement a calculation by implementing the interface Operation. In the following example, I will define an addition and multiplication operations :

// Addition
public class PlusOperation implements Operation {

 @Override
 public int calculate(int a, int b) {
  return a+b;
 }

}

// Multiplication
public class MultiplicationOperation implements Operation {

 @Override
 public int calculate(int a, int b) {
  return a*b;
 }

}

We can now instantiate the concrete operations (Addition and Multiplication) inside the Test class, and pass them as argument to the Test.displayResult() method:

// Addition of 1 and 2
Operation plusOperation = new PlusOperation();
displayResult(1, 2, plusOperation);

// Multiplication of 4 by 4
Operation multiplicationOperation = new MultiplicationOperation();
displayResult(4, 4, multiplicationOperation);

An other option to implement a custom calculation is to create an anonymous inner class in place, and pass it directly to the displayResult() method as parameter. Let’s say we want to implement the exponent of 10 in 20 :

// other operation, 10 exponent 20
displayResult( 10, 20,
 new Operation() {
  @Override
  public int calculate(int a, int b) {
   return a^b;
  }
 }
);

 

All the examples above can be implemented in less lines of code using Lambda expressions. We will see in the next section how to write a lambda expression, but remember that a lambda expression represents a behavior, a functionality we can pass as a method argument:

// the above operations using lambda expressions
displayResult(1,2, (a,b)->a+b); // addition
displayResult(4,4, (a,b)->a*b); // multiplication
displayResult(10,20, (a,b)-> a^b); // exponent

The final code of the Test class looks like this :

public class Test {

 public static void main(String[] args) {

  // Addition of 1 and 2
  Operation plusOperation = new PlusOperation();
  displayResult(1, 2, plusOperation);

  // Multiplication of 4 by 4
  Operation multiplicationOperation = new MultiplicationOperation();
  displayResult(4, 4, multiplicationOperation);

  // other operatio, 10 exponent 20
  displayResult( 10, 20,
  new Operation() {

   @Override
   public int calculate(int a, int b) {
    return a^b;
   }
  }
  );

  // all the above operations using lambda expressions

  displayResult(1,2, (a,b)->a+b); // addition
  displayResult(4,4, (a,b)->a*b); // multiplication
  displayResult(10,20, (a,b)-> { // exponent
   return a^b;
   }
  );

 }

 static void displayResult( int a, int b, Operation operation){
  System.out.println(operation.calculate(a, b));
 }

}

 

And the output of the program is the same using lambda expressions or the old way:

3 ⇐ Using the old way
16
30
3 ⇐ Using lambda expressions
16
30

How to write a Lambda Expression

Lambda expressions are composed of two statements, linked by an arrow (->):

  1. The left statement: Represents the parameters statement;
  2. The right statement : Represents the body statement .
// general syntax
(parameters) -> (Body)

Lambda’s left statement

The left statement of a lambda expression is similar to the parameters statement in a method definition, with the difference that you can choose to indicate or not the data types of the parameters. If there are no parameters, you can simply use empty parentheses.
The parentheses become optional if the left statement contains one single parameter.

Lambda’s right statement

The right statement of a lambda expression is similar to the body of a method definition, with the difference that the curly braces ( { } ) and the return keyword are optional if the body contains one single expression. However, this becomes necessary when the body statement is composed of more than one expression;

 

Examples of valid lambda expressions

The following is a list of valid lambda expressions:

// Full syntax
(Double x, Double y) -> {return x * y;}

// Omitting curly braces
(Double x, Double y) -> return x * y

// Omitting curly braces and return keyword
(Double x, Double y) -> x * y

// Omitting the data types
(x, y) -> {return x * y;}

// The parentheses become optional if the left side
// contains only one parameter
x -> System.out.print(x)

// Lambda expression including many
// statements in the body
(x,y) -> {
 if(x>y){
  System.out.println("x is greater than y");
  return true;
 }else{
  System.out.println("y is greater or equal to x")
 }
 return false;
}

// Lambda expression with no parameters
() -> 99

 

Use case of lambda with the Collections framework

Streams have been introduced in Java 8 to support the Collections framework.
A Stream is a sequence of elements supporting sequential and parallel aggregate operations.
Some of these operations are simply methods that can take lambda expressions as parameter, allowing the programmer to process data in a simpler way compared to previous versions of Java.

To obtain a stream from a collection you can use the stream() method to obtain a sequential stream, and parallelStream() to obtain a parallel stream. For more informations about streams check this page talking about streams in java 8.

In the following example I will show how to filter and display a List in two lines of code, using lambda expressions and streams. Here are the steps:

  1. Create a list of Integers ;
  2. Populate it with random integers;
  3. Filter the list and keep only the pair numbers;
  4. Display the list.

To Create the list, I will simply use an ArrayList of Integers :

List<Integer> list = new ArrayList<Integer>();

The populateList() method populates the list with 1000 random integers:

// Implementation of the populateList() method
public static void populateList(List<Integer> list){
 Random random = new Random();
 for(int i=0;i<1000;i++){
  list.add(random.nextInt());
 }
}


// calling the populateList() method
populateList(list);

I will then obtain a stream from the list using the stream() method, filter it using the filter() method and collect the results into a filtered new list.

List<Integer> filteredList = list.stream().filter(e -> e%2==0).collect(Collectors.toList());

I will explain every element in the above line of code:

  • The stream() method returns a sequential stream obtained from the list we created before;
  • The filter() method is obtained from the stream, as you can understand from it’s name, the filter() method allow to filter the stream using a lambda expression;
  • The filter() method takes an object of type Predicat as parameter, it’s a functional Interface, that means we can use a lambda expression;
  • The Predicate functional interface is included in the package java.util.function (as well as other useful FIs). According to the signature of it’s abstract method ( boolean test(T t) ) It represents a boolean-valued function of one argument.
  • Finally, we must convert the stream to a List again, we will use the collect() method with the parameter (Collectors.toList()) .

Please note that the chaining the methods above is called a Pipeline, and all the operations of that pipeline are executed only after the method collect() is called.

Once we got a filteredList, we can display it. The method forEach( ) is a new facility added to the Collections framework allowing to iterate through the elements of a list. It takes an object of type Consumer (an other functional interface of the package java.util.function).

The consumer functional interface represents an operation that takes a single input argument and returns no value, this is similar to the behavior we want : displaying a value. Here is how to display the filteredList in Java 8 :

filteredList.forEach(e -> System.out.println(e));

To recapitulate, our code will look like this :

// Create the list
List<Integer> list = new ArrayList<Integer>();
    
// Populate the list
populateList(list);

// Filter the list
List<Integer> filteredList = list.stream().filter(e -> e%2==0).collect(Collectors.toList());

// Display the elements of the list
filteredList.forEach(e -> System.out.println(e));

Conclusion

In this tutorial we saw what are lambda expressions, why and how to use them. Using Lambda expressions allows to write less code and helps manipulation data withing the Collections framework, streams and pipelines  (iteration, filtering, sorting, etc) beside other things.  However, lambda expressions come with some limitations, for example, if there are problems in your code debugging may be harder with lambda expressions.

 

Java Expressions, Statements and Blocks

In java, Statements are composed of one or many expressions. They may also be grouped into blocks.

Expressions

Expressions in java are made of variables, operators and method invocations. An expression always evaluates to a single value.

//Examples of valid expressions
a =0;
"Hello "+firstName + " "+ lastName
d = a + b;

 

Statements

A statement in java is a complete unit of execution. Assignment expressions, pre-increment operators, pre-decrement operators, post-increment operators, post-decrement operators, method invocation and object instantiation expressions can compose a statement by terminating the expression with a semicolon (;) .

// using the Examples to create valid statements
int a =0;
System.out.println("Hello "+firstName + " "+ lastName);
double d = a + b;

 

Blocks

A block in Java is composed of zero or more statements enclosed inside curly braces { }. Blockes are allowed wherever statements are allowed. Blocks can be nested.

// Example of two blocks
if(condition)
{ // block 1 beginning
  int x=0;
  System.out.println("Block 1 is executed");
} // block 1 ending
else
{ // block 2 beginning
  System.out.println("Block 2 is executed");
} // block 2 ending

 

 

How to prevent Firefox and Chrome from forcing dev and foo domains to use https

In their last update, Chrome and Firefox browsers now redirect all domains with the pattern *.dev and *.foo to https. This can be annoying for develepers and campanies who must deal with such domain names.

It is possible to disable this behavior for Firefox, but not for Chrome, unless you have an alternative solution.

In the following I will show the solution for Firefox and give some alternatives for Chrome.

Firefox

  1. Visit the address about:config
  2. Search for the parameter network.stricttransportsecurity.preloadlist and change it’s value to false

Chrome

You can find some solutions on the Internet talking about the chrome://net-internals/#hsts  but this doesn’t seem to be working. if you know a working solution, please let me know in the comments section.

Other alternatives

  • Change your URLs and use new domains .
  • Modify the hosts file, If you point on IP addresses or virtual hosts, you can modify your hosts file to use local domains
  • Or, Use SSL, you can choose to activate SSL on your web server.

 

 

How to get the root exception of any exception

Sometimes, the root exception causing your code to fail is hidden behind an other exception or a set of nested exceptions.

Nested Exceptions

Nested Exceptions

 

The following code (function) searches for the root exception of any exception and returns it :

public static Throwable getRootException(Throwable exception){
 Throwable rootException=exception;
 while(rootException.getCause()!=null){
  rootException = rootException.getCause();
 }
 return rootException;
}

Example of usage :

catch(MyException e){
  System.out.println(getRootException(e).getLocalizedMessage());
}

 

 

What is the order of initialization in a Java class

The order of initialization of a Java class is the following:

  1. Static constants, variables and blocks are first initialized in the order in which they appear in the code;
  2. Then non-static constants, variables and blocks are first initialized in the order in which they appear in the code;

Consider the following code :

public class Sample{
 
 static Sample2 a = new Sample2();
 
 
 Sample2 b = new Sample2("Instance variable");
 
 public Sample(){
 System.out.println("Constructor");
 }
 
 static{
 System.out.println("Static block");
 }
 
 public static void main(String[] args) {
 new Sample();
 }
}

class Sample2{
 
 public Sample2(){
 System.out.println("Sample2 Constructor");
 }
 
 public Sample2(String str){
 System.out.println(str);
 }

}

Accoding the above points 1 and 2, the displayed result will be :

Sample2 Constructor
Static block
Instance variable
Constructor

 

 

Java Certification Path

Java Certifications are managed and delivered by Oracle who offers a lot of certifications in many IT fields.

The following is an optimal path of certification for a Java Developer. The image does not cover all java certifications and this path is not the only possible one for a Java Developer.

Java Certification Path

Optimal Java Certification Path

 

To get one of these certifications you need complete an exam. To register for an exam you have to register with the Oracle Education System and buy a voucher.

How to create automated backups for your web server?

If you have a web server running one or many websites or applications and hosting a database server it may be a good idea to have an automated backup process.

Most (or all) Web Hosting providers will charge you for such service, but the good news is that you can create your own automated backup process. Do not wait until you wake up a morning and discover that your homepage has changed into this :

You have boon hacked

The following tutorial has been written and tested with the following configuration:

  • Operating System : Ubuntu Linux 14.04.4 with root access
  • Web Server : Apache2
  • Database Server : Mysql 5.5.49
  • Scripting tool : Unix Shell

You can adapt the script or paths to meet your configuration’s needs. I will not cover any  external file transfer process, the files will be stored on the same server, but it’s not a big deal to automate the transfer of files to an other server.

Before we start, I will summarize the backup strategy .

  1. Create folder structures that will contain the backup files;
  2. The backup program consists of a shell script (.sh) that runs everyday at a fixed hour using a CRON task. The logic of that script will be the following :
    • Rename the existing (yesterday’s files) backup files by prefixing them with the the current date;
    • Delete backups older than X days (in our case it will be 5 days);
    • Take backupa of databases and compress the files;
    • Take backup of the Apache www folder and compress it.
  3. And finally, create the CRON task and set the appropriate permissions.

 

Folder Structure

We will create two folders:

  • /bkp : will be used to store the backup files ;
  • /opt/backup/ : will contain the backup script (backup.sh) .

To create the two folder execute the following commands :

mkdir /bkp
mkdir /opt/backup

 

Backup Script

We start by creating the script and give it the right permissions. On the command line execute the following commands:

# create the script file
touch /opt/backup/backup.sh

# make the file executable
chmod +x /opt/backup/backup.sh

Then we will start editing the script using VI editor (or your preferred text editor):

vi /opt/backup/backup.sh

Since it’s a shell script, it must start with the following line :

#!/bin/sh

The following sections will cover content that will be added to the backup.sh shell script.

Rename the old backup files

The next steps of the script will consist of creating new backup files. We don’t want our backup files to be replaced by the new ones. We will prefix the last created backup files with the current day’s date.

Add these lines to the script:

# rename existing backup files

## Switch to the backups folder
cd /bkp

## get the current date
current_date=$(date +"%Y-%m-%d")
shopt -s extglob

## Rename the files not starting with a date
for file in !([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*.gz); do
  mv "$file" "${current_date}_$file"
done

 

Delete backups older than X days

Your server space may be limited. We have to make a decision about the number of days we want to keep. For this tutorial we will choose 5 days.

# delete backups older than 5 days under /bkp folder
find /bkp -type f -name '*' -mtime +5 -exec rm {} \;

 

Take database backups

We will use the mysqldump command to create backups of the databases. Lets say we have 3 mysql databases : db1, db2 and db3. The backups will consist of what we call mysql dumps .

In addition, we will compress these mysql dumps (or backup files) in order to save space on the server.

Add the following lines to the script (replace database names, usernames and passwords with you own values):

# take compressed backups of databases
mysqldump -u root yourPassword db1| gzip -9 > /bkp/db1.sql.gz
mysqldump -u root yourPassword db2| gzip -9 > /bkp/db2.sql.gz
mysqldump -u root yourPassword db3| gzip -9 > /bkp/db3.sql.gz

 

Take folders backup

Now we will add the commands to backup our website’s files and folders. For Apache web server, website files or commonly stored in /var/www, but it’s not a rule, configuration my change. For this tutorial we suppose that our files are located in /var/www folder .

To take a backup, we will simply use the tar command to create a compressed archive for the whole www folder.

Add the following lines to the script (Replace the paths with you own values) :

# take compressed backup of important folders
tar -zcf /bkp/www.tar.gz /var/www/

Note: you can also use the same command to take a backup of any important folders located on your server.

Save the backup.sh file. Here is the final structure of the script :

#!/bin/sh

# rename existing backup files

# Switch to the backups folder
cd /bkp

# get the current date
current_date=$(date +"%Y-%m-%d")
shopt -s extglob

# Rename the files not starting with a date
for file in !([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*.gz); do
  mv "$file" "${current_date}_$file"
done

# delete backups older than 5 days under /bkp folder
find /bkp -type f -name '*' -mtime +5 -exec rm {} \;

# take compressed backups of databases
mysqldump -u root yourPassword db1| gzip -9 > /bkp/db1.sql.gz
mysqldump -u root yourPassword db2| gzip -9 > /bkp/db2.sql.gz
mysqldump -u root yourPassword db3| gzip -9 > /bkp/db3.sql.gz

# take compressed backup of important folders
tar -zcf /bkp/www.tar.gz /var/www/

 

Create the CRON task

Now that our script is ready, you can test the process by executing it and make sure it has the behavior you wanted. When satisfied with the results, you can automate the process using the CRON tasks.

For this tutotrial, we want our script be executed every day at 00:01 AM. On a shell command line execute the following command to start editing the crontab :

sudo crontab -e

Then add the following line and save the file :

01 0 * * * /opt/backup/backup.sh

At this point everything must be OK, you have to wait until 00:01 AM to see the results.

Restoring the files

If you need to use the saved backup files simply do the following:

MySQL dumps

  1. Uncompress the files usinng gunzip command ( ex: gunzip db1.gz)
  2. This will produce an SQL file.
  3. Import the SQL file using any importing tool (phpmyadmin, MySQL Workbench, MySQL Administrator, etc)
  4. Sometimes you will experience some problems with file encoding, in most cases you have to remove or change some parameters.

tar archives

  1. Just uncompress the tar archive and copy the files in their appropriate location which is /var/ww for this tutorial. (Example : tar xzvf www.tar.gz)

 

 

Labeled statements in Java 8

Labeled statements are transfer of control statements used to give a statement a prefixed label.

Referred statements can be loops, switch statements or blocks {statements enclosed in curly braces}. Example :

loop1: for(int i=0;i<10<i++){
          System.out.println(i);
       }

 

Labeled statements are used in conjunction with break and continue statements.

To understand better, lets take the following example of two nested for loops and a break statement. The use of the break statement inside of the inner loop will cause the program to interrupt the innermost for loop when j become equal to 5  . It will not interrupt the outer loop.

 

for(int i=0;i<=10;i++){
 for(int j=0;j<=10;j++){
  System.out.println(i + " - " + j);
  if(j>=5){
   break;
  }
 }
}

 

Now we will label the outer for loop, and add the same label to the innermost break statement. This will cause the program to interrupt the outer loop (the labeled one) .

label1:
for(int i=0;i<=10;i++){
 for(int j=0;j<=10;j++){
  System.out.println(i + " - " + j);
  if(j>=5){
   break label1;
  }
 }
}

 

As mentioned earlier, labeled statements can be used in conjunction with a break statement inside a loop or a switch statement. or with a continue statement inside a loop.

The following example will interrupt the outer for loop when j == 5 which is the labelled for loop.

label1:
for(int i=0;i<=10;i++){
 for(int j=0;j<=10;j++){
  System.out.println(i + " - " + j);
  switch(j){
   case 5:
    break label1;
   default:
    // do nothing
  }
 }
}

 

How to display an animated gif in java swing

The type ImageIcon (sub-type of Icon) allows to display an animated GIF. Example :

// We suppose you have already set your JFrame 
Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);