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);

 

Java native keyword

When applied to a method declaration, the Java « native » keyword indicates to the jvm that the method is implemented in the platform code .
A method marked as native cannot have a body.

Oracle’s definition of the native keyword :

A Java keyword that is used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language.

 

Access modifiers in java : public, protected, default, private

In Java, access modifiers are keywords that help setting the accessibility of classes, methods or members. There are four access modifiers in Java language, they are exposed in the following from the least restrictive (public) to the most restrictive (private).

 

Public

Means that the class or the member variable or method can be accessed from anywhere in the code, from the same package or from a different one.

Protected

Can be used with inner variables, methods or inner classes. This access modifier means that the member can be accessed only from the same class or a subclass.

Default (or package private)

This is the default access modifier that will be applied when we don’t specify any. It can be used with a class or member variable or method.
It means that the member can be accessed only from the same package. Please note that a default member cannot be accessed from a subclass in an other package as well.

Private

The private keyword can be used for members (variables, methods or inner classes , when used it limits access to members to only the same class only.

Note

The native keyword in java is not considered as an access modifier.

Summary

class package Sub-class

(same package)

Sub-class

(other package)

World
public  ✔  ✔  ✔  ✔
Protected  ✔  ✔  ✔  ✔  x
default  ✔  ✔  ✔  x  x
private  ✔  x  x  x  x

How to display all system properties in Java

This code displays all system (jvm) properties in java :

import java.util.Iterator;
import java.util.Properties;

public class Test {

 public static void main(String[] args) {
   Properties properties = System.getProperties();
   Iterator<Object> iter = properties.keySet().iterator();
   while(iter.hasNext()){
    String key = (String) iter.next();
    System.out.println(key + " = " + properties.getProperty(key));
   }
  }
 }

 

Here is a set of default system properties you can access:

java.runtime.name
sun.boot.library.path
java.vm.version
user.country.format
java.vm.vendor
java.vendor.url
path.separator
java.vm.name
file.encoding.pkg
user.country
user.script
sun.java.launcher
sun.os.patch.level
java.vm.specification.name
user.dir
java.runtime.version
java.awt.graphicsenv
java.endorsed.dirs
os.arch
java.io.tmpdir
line.separator
java.vm.specification.vendor
user.variant
os.name
sun.jnu.encoding
java.library.path
java.specification.name
java.class.version
sun.management.compiler
os.version
user.home
user.timezone
java.awt.printerjob
file.encoding
java.specification.version
java.class.path
user.name
java.vm.specification.version
sun.java.command
java.home
sun.arch.data.model
user.language
java.specification.vendor
user.language.format
awt.toolkit
java.vm.info
java.version
java.ext.dirs
sun.boot.class.path
java.vendor
file.separator
java.vendor.url.bug
sun.io.unicode.encoding
sun.cpu.endian
sun.desktop
sun.cpu.isalist

How to create directories in Java

In java you can create a directory (or directories) using the standard IO package or using the java NIO package.

Create directories using the java IO package

// create a single directory
new File("c:\\myDir").mkdir();

// create a directory and all its sub-directories
new File("c:\\myRootDir\\Subdir1\\SubDir2").mkdirs();

 

Create directories using the java NIO package

This will work only on Java 7 and above.

Path path = Paths.get("C:\\Mydir");
Files.createDirectories(path);

You have to import the classes java.nio.file.Paths and java.nio.file.Files .

 

 

 

How to access to class private members in Java

It is possible to use to access class private instance variables and methods using Reflexion.

Access to private instance variables

MyClass myClass = new MyClass();
Field field = MyClass.class.getDeclaredField("myField");
field.setAccessible(true);
Object value = field.get(myClass);
System.out.println(value);

 

Access to private methods

MyClass myClass = new MyClass();
Method method = myClass.getClass().getDeclaredMethod("myMethodName");
method.setAccessible(true);
Object o = method.invoke(object);